diff --git a/Cargo.lock b/Cargo.lock index 806d5d9707..f55b9ebc77 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", @@ -6712,7 +6844,7 @@ dependencies = [ "vectorcraft-tools", "vectorcraft-trace", "wat", - "zune-core 0.5.3", + "zune-core", "zune-jpegxl", ] @@ -6721,11 +6853,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 +6932,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 +6952,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 +6993,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 +7021,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 +7046,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 +7086,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 +7115,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", @@ -7026,7 +7163,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", @@ -7043,7 +7180,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", @@ -7058,6 +7195,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", @@ -7734,7 +7872,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]] @@ -8012,7 +8150,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", @@ -8027,6 +8165,7 @@ dependencies = [ "windows", "windows-core", "windows-implement", + "windows-numerics", "xml", ] @@ -8486,12 +8625,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" @@ -8507,22 +8640,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]] @@ -8531,7 +8655,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]] diff --git a/Cargo.toml b/Cargo.toml index 64f85eb450..89d6328ea7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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 `` from the XML itself and never gives usvg a font. A test of the SVG -# crate turns `text` on. +# SVG import reads `` 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" } diff --git a/NOTICE b/NOTICE index c5c5511ba0..a6a1299cde 100644 --- a/NOTICE +++ b/NOTICE @@ -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 + +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 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. + */ diff --git a/crates/affinity/Cargo.toml b/crates/affinity/Cargo.toml index 798b0734f5..8e3bce12a9 100644 --- a/crates/affinity/Cargo.toml +++ b/crates/affinity/Cargo.toml @@ -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 } diff --git a/crates/affinity/tests/it/raster.rs b/crates/affinity/tests/it/raster.rs index 794b4c4f13..46e96c2013 100644 --- a/crates/affinity/tests/it/raster.rs +++ b/crates/affinity/tests/it/raster.rs @@ -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])); } diff --git a/crates/cad/Cargo.toml b/crates/cad/Cargo.toml index 4084e75d24..f2f9158730 100644 --- a/crates/cad/Cargo.toml +++ b/crates/cad/Cargo.toml @@ -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 } diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs index a5e229c2a4..3fc68180d0 100644 --- a/crates/cad/src/scene.rs +++ b/crates/cad/src/scene.rs @@ -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)) } } diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index 48f6010925..dda09a0696 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -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(), diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml index 3a5626054b..a7d2850a1e 100644 --- a/crates/doc/Cargo.toml +++ b/crates/doc/Cargo.toml @@ -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 } diff --git a/crates/doc/src/cmyk.rs b/crates/doc/src/cmyk.rs index 60a6db4074..d1b9b4a6ed 100644 --- a/crates/doc/src/cmyk.rs +++ b/crates/doc/src/cmyk.rs @@ -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 { /// 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 { - 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> { /// 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> { - 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 { - 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> { - 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::(Tag::Compression).ok().flatten()?; @@ -1143,12 +1120,8 @@ pub fn group3_tiff_rgba(bytes: &[u8]) -> Option(Tag::Unknown(292)).ok().flatten().unwrap_or(0); let lsb_first = d.find_tag_unsigned::(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 = 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, ¶ms, 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 { + 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 = (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"); + } } diff --git a/crates/doc/src/decode.rs b/crates/doc/src/decode.rs new file mode 100644 index 0000000000..11d1b2d72b --- /dev/null +++ b/crates/doc/src/decode.rs @@ -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>); + +/// `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 { + 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, 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 { + 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 })) +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 2d956ed30a..f590a46497 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -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; diff --git a/crates/doc/src/links.rs b/crates/doc/src/links.rs index 80740b7cc2..b8a9998fda 100644 --- a/crates/doc/src/links.rs +++ b/crates/doc/src/links.rs @@ -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.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)> { - 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> { /// `bytes` decoded and shrunk to fit [`PROXY_SIZE`] as a PNG; `None` when small enough already or /// undecodable. fn proxy_png(bytes: &[u8]) -> Option> { - 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 { + let mut out = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]; + let push = |out: &mut Vec, 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()); + } } diff --git a/crates/doc/src/pixels.rs b/crates/doc/src/pixels.rs index c451fea7be..b2d8e569f9 100644 --- a/crates/doc/src/pixels.rs +++ b/crates/doc/src/pixels.rs @@ -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 { - 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 { 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 { - 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 { + 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::, _>::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)); + } } diff --git a/crates/doc/src/setup.rs b/crates/doc/src/setup.rs index bc558d2702..4dd8394ce2 100644 --- a/crates/doc/src/setup.rs +++ b/crates/doc/src/setup.rs @@ -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())); diff --git a/crates/effects/Cargo.toml b/crates/effects/Cargo.toml index 6d58ad9d74..e737bc5ad8 100644 --- a/crates/effects/Cargo.toml +++ b/crates/effects/Cargo.toml @@ -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 } diff --git a/crates/effects/src/pixel/loaded.rs b/crates/effects/src/pixel/loaded.rs index bb885b239c..fe822ffd64 100644 --- a/crates/effects/src/pixel/loaded.rs +++ b/crates/effects/src/pixel/loaded.rs @@ -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 { - 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 { - 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 diff --git a/crates/effects/src/pixel/tests.rs b/crates/effects/src/pixel/tests.rs index 34212ddd66..6dd7942e5e 100644 --- a/crates/effects/src/pixel/tests.rs +++ b/crates/effects/src/pixel/tests.rs @@ -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); diff --git a/crates/effects/src/svg_filter.rs b/crates/effects/src/svg_filter.rs index 67826614e1..6cb0c45e65 100644 --- a/crates/effects/src/svg_filter.rs +++ b/crates/effects/src/svg_filter.rs @@ -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>) -> 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> { - 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(…)`. diff --git a/crates/effects/src/svg_filter/tests.rs b/crates/effects/src/svg_filter/tests.rs index 4ab6328359..ddd19f5580 100644 --- a/crates/effects/src/svg_filter/tests.rs +++ b/crates/effects/src/svg_filter/tests.rs @@ -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 { - 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 { - 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]); diff --git a/crates/effects/src/tests/imageoutline.rs b/crates/effects/src/tests/imageoutline.rs index 5ef3955254..9c2a5543ee 100644 --- a/crates/effects/src/tests/imageoutline.rs +++ b/crates/effects/src/tests/imageoutline.rs @@ -15,10 +15,13 @@ fn fx(id: &str) -> Effect { } /// `img` encoded as `format`. -fn encoded(img: image::DynamicImage, format: image::ImageFormat) -> Vec { - 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 { + 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 { 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)); diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index b46678804b..cd91a0bfbb 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -44,10 +44,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 +78,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 +99,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. diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index f5a51beabb..703d81ddc3 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -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 { diff --git a/crates/engine/src/cmd/addons/color/tests.rs b/crates/engine/src/cmd/addons/color/tests.rs index ed8137d6a9..213bc5ccf7 100644 --- a/crates/engine/src/cmd/addons/color/tests.rs +++ b/crates/engine/src/cmd/addons/color/tests.rs @@ -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) } diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs index 43e86caf52..d1bd77727d 100644 --- a/crates/engine/src/cmd/addons/document/tests.rs +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -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(); diff --git a/crates/engine/src/cmd/addons/image.rs b/crates/engine/src/cmd/addons/image.rs index 898c28c707..5ef567e9b3 100644 --- a/crates/engine/src/cmd/addons/image.rs +++ b/crates/engine/src/cmd/addons/image.rs @@ -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, bool, Option>)> { - 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 diff --git a/crates/engine/src/cmd/addons/image/mask.rs b/crates/engine/src/cmd/addons/image/mask.rs index 0dd8fabe3c..7fdb0c5c3e 100644 --- a/crates/engine/src/cmd/addons/image/mask.rs +++ b/crates/engine/src/cmd/addons/image/mask.rs @@ -287,9 +287,7 @@ fn apply_color_mask(s: &mut Session, p: &Value) -> Result { /// 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 diff --git a/crates/engine/src/cmd/addons/image/mask/tests.rs b/crates/engine/src/cmd/addons/image/mask/tests.rs index b9b56a5e4a..7fa1cd50fb 100644 --- a/crates/engine/src/cmd/addons/image/mask/tests.rs +++ b/crates/engine/src/cmd/addons/image/mask/tests.rs @@ -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 { 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)); } diff --git a/crates/engine/src/cmd/addons/image/tests.rs b/crates/engine/src/cmd/addons/image/tests.rs index ae59efad87..30673c7677 100644 --- a/crates/engine/src/cmd/addons/image/tests.rs +++ b/crates/engine/src/cmd/addons/image/tests.rs @@ -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 { 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> { } 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 = 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 diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index bf03c86746..c7421ac391 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -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)); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 0ac559c874..f38e23bb5d 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -526,26 +526,34 @@ fn doc_compare(s: &mut Session, p: &Value) -> Result { /// 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 { - 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")] diff --git a/crates/engine/src/cmd/fileio/affinity.rs b/crates/engine/src/cmd/fileio/affinity.rs index c8ef3235ec..e10495e815 100644 --- a/crates/engine/src/cmd/fileio/affinity.rs +++ b/crates/engine/src/cmd/fileio/affinity.rs @@ -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}; diff --git a/crates/engine/src/cmd/fileio/affinity/import.rs b/crates/engine/src/cmd/fileio/affinity/import.rs index 0b0d587d8d..27964bc665 100644 --- a/crates/engine/src/cmd/fileio/affinity/import.rs +++ b/crates/engine/src/cmd/fileio/affinity/import.rs @@ -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, diff --git a/crates/engine/src/cmd/fileio/affinity/layout.rs b/crates/engine/src/cmd/fileio/affinity/layout.rs index 262f688b13..da7ce9aaee 100644 --- a/crates/engine/src/cmd/fileio/affinity/layout.rs +++ b/crates/engine/src/cmd/fileio/affinity/layout.rs @@ -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) -> Option> { - 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`). diff --git a/crates/engine/src/cmd/fileio/jp2read.rs b/crates/engine/src/cmd/fileio/jp2read.rs index 9e0752c2c5..ebbc250704 100644 --- a/crates/engine/src/cmd/fileio/jp2read.rs +++ b/crates/engine/src/cmd/fileio/jp2read.rs @@ -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 { }) } -/// 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| 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 { - 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, ()> { - 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 { - 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()) } diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index f10541a55d..e26d9a765a 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -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 { - 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 { pub(crate) fn size_note(bytes: &[u8]) -> Option { 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 { 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 { _ => 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 { 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 { 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()) } }; diff --git a/crates/engine/src/cmd/fileio/pngtext.rs b/crates/engine/src/cmd/fileio/pngtext.rs index 94a30d13f0..798c59d0ac 100644 --- a/crates/engine/src/cmd/fileio/pngtext.rs +++ b/crates/engine/src/cmd/fileio/pngtext.rs @@ -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); diff --git a/crates/engine/src/cmd/fileio/ppi.rs b/crates/engine/src/cmd/fileio/ppi.rs index 119201bb87..bff476b6f4 100644 --- a/crates/engine/src/cmd/fileio/ppi.rs +++ b/crates/engine/src/cmd/fileio/ppi.rs @@ -114,7 +114,41 @@ mod tests { fn png_of(w: u32, h: u32) -> Vec { 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))); diff --git a/crates/engine/src/cmd/fileio/tests_affinity.rs b/crates/engine/src/cmd/fileio/tests_affinity.rs index d5f5149bab..db9a0657d2 100644 --- a/crates/engine/src/cmd/fileio/tests_affinity.rs +++ b/crates/engine/src/cmd/fileio/tests_affinity.rs @@ -4,12 +4,45 @@ use super::*; use proptest::prelude::*; use serde_json::json; -use std::io::Cursor; fn png() -> Vec { 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 } diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 78cca92873..d89dab774f 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -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::>()); }); 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"); diff --git a/crates/engine/src/cmd/fileio/tests_artboard_fill.rs b/crates/engine/src/cmd/fileio/tests_artboard_fill.rs index 371cdc05ab..a735b72b42 100644 --- a/crates/engine/src/cmd/fileio/tests_artboard_fill.rs +++ b/crates/engine/src/cmd/fileio/tests_artboard_fill.rs @@ -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"); diff --git a/crates/engine/src/cmd/fileio/tests_eps.rs b/crates/engine/src/cmd/fileio/tests_eps.rs index db667e6ef2..e37fd2be37 100644 --- a/crates/engine/src/cmd/fileio/tests_eps.rs +++ b/crates/engine/src/cmd/fileio/tests_eps.rs @@ -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). diff --git a/crates/engine/src/cmd/fileio/tests_epsimport.rs b/crates/engine/src/cmd/fileio/tests_epsimport.rs index 6245a001bd..47dadb0226 100644 --- a/crates/engine/src/cmd/fileio/tests_epsimport.rs +++ b/crates/engine/src/cmd/fileio/tests_epsimport.rs @@ -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}"); diff --git a/crates/engine/src/cmd/fileio/tests_exportas.rs b/crates/engine/src/cmd/fileio/tests_exportas.rs index 1908c39685..49680347b2 100644 --- a/crates/engine/src/cmd/fileio/tests_exportas.rs +++ b/crates/engine/src/cmd/fileio/tests_exportas.rs @@ -16,7 +16,24 @@ fn b64(v: &Value) -> Vec { } 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 { diff --git a/crates/engine/src/cmd/fileio/tests_jp2read.rs b/crates/engine/src/cmd/fileio/tests_jp2read.rs index e028350150..6075afd224 100644 --- a/crates/engine/src/cmd/fileio/tests_jp2read.rs +++ b/crates/engine/src/cmd/fileio/tests_jp2read.rs @@ -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 { @@ -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::>(), 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::>(), + 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::>(), 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::>(), + COLORS + ); assert!(load::texture_image(bytes).is_ok()); } } diff --git a/crates/engine/src/cmd/fileio/tests_palette.rs b/crates/engine/src/cmd/fileio/tests_palette.rs index 703ea41c36..e54aababec 100644 --- a/crates/engine/src/cmd/fileio/tests_palette.rs +++ b/crates/engine/src/cmd/fileio/tests_palette.rs @@ -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 + ); } diff --git a/crates/engine/src/cmd/fileio/tests_pcxread.rs b/crates/engine/src/cmd/fileio/tests_pcxread.rs index 8cab621bd3..8885a01781 100644 --- a/crates/engine/src/cmd/fileio/tests_pcxread.rs +++ b/crates/engine/src/cmd/fileio/tests_pcxread.rs @@ -49,7 +49,27 @@ fn rle(raw: &[u8]) -> Vec { /// 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). diff --git a/crates/engine/src/cmd/fileio/tests_pdf.rs b/crates/engine/src/cmd/fileio/tests_pdf.rs index f5b1b8e34d..e4173eb71e 100644 --- a/crates/engine/src/cmd/fileio/tests_pdf.rs +++ b/crates/engine/src/cmd/fileio/tests_pdf.rs @@ -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 [ diff --git a/crates/engine/src/cmd/fileio/tests_pdf13.rs b/crates/engine/src/cmd/fileio/tests_pdf13.rs index 53c1bf9acf..99daa023a5 100644 --- a/crates/engine/src/cmd/fileio/tests_pdf13.rs +++ b/crates/engine/src/cmd/fileio/tests_pdf13.rs @@ -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 } diff --git a/crates/engine/src/cmd/fileio/tests_pdfedit.rs b/crates/engine/src/cmd/fileio/tests_pdfedit.rs index b7b0ddde59..c38dfc390d 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfedit.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfedit.rs @@ -807,7 +807,28 @@ fn image_outline(doc: &vectorcraft_doc::Document) -> Vec { ((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"); diff --git a/crates/engine/src/cmd/fileio/tests_pdfimport.rs b/crates/engine/src/cmd/fileio/tests_pdfimport.rs index 5ae8bd6409..703c29fe74 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfimport.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfimport.rs @@ -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}"); } } diff --git a/crates/engine/src/cmd/fileio/tests_pdfx.rs b/crates/engine/src/cmd/fileio/tests_pdfx.rs index 68df66bd93..243df812c2 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfx.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfx.rs @@ -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(); diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index 298f3d22dc..6c227c0e17 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -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) diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index 2a7340a79e..ac728c8cb9 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -215,7 +215,24 @@ fn exported(s: &mut Session, p: Value) -> Vec { #[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(); diff --git a/crates/engine/src/cmd/fileio/tests_pxrread.rs b/crates/engine/src/cmd/fileio/tests_pxrread.rs index f9e89e38f1..8ef614a8e5 100644 --- a/crates/engine/src/cmd/fileio/tests_pxrread.rs +++ b/crates/engine/src/cmd/fileio/tests_pxrread.rs @@ -72,7 +72,27 @@ fn wide(samples: &[u16]) -> Vec { /// 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::>(), 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); diff --git a/crates/engine/src/cmd/fileio/tests_raster.rs b/crates/engine/src/cmd/fileio/tests_raster.rs index 80001476a4..b43f3d0547 100644 --- a/crates/engine/src/cmd/fileio/tests_raster.rs +++ b/crates/engine/src/cmd/fileio/tests_raster.rs @@ -16,7 +16,24 @@ fn b64(v: &Value) -> Vec { } 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::, _>::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}"); +} diff --git a/crates/engine/src/cmd/fileio/tests_screens.rs b/crates/engine/src/cmd/fileio/tests_screens.rs index 1746be6c97..362cc7a874 100644 --- a/crates/engine/src/cmd/fileio/tests_screens.rs +++ b/crates/engine/src/cmd/fileio/tests_screens.rs @@ -34,7 +34,25 @@ fn names(r: &Value) -> Vec { } 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"}]}), diff --git a/crates/engine/src/cmd/fileio/tests_selexport.rs b/crates/engine/src/cmd/fileio/tests_selexport.rs index 57db4891a5..5e485ae355 100644 --- a/crates/engine/src/cmd/fileio/tests_selexport.rs +++ b/crates/engine/src/cmd/fileio/tests_selexport.rs @@ -43,13 +43,47 @@ fn rect_of(v: &Value) -> Rect { /// What the canvas draws of the whole document over `r`, at 1 px per point. fn canvas(s: &Session, r: Rect) -> image::RgbaImage { let img = vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, r, 1.0, false); - image::load_from_memory(&img.to_png().unwrap()).unwrap().to_rgba8() + craft_image_codecs::decode(&img.to_png().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() + .to_rgba8() } /// The pixels of `png` that differ from `want` by more than 64 in a channel (anti-aliased edges /// differ by less), and every pixel when the sizes differ. fn differing(png: &[u8], want: &image::RgbaImage) -> usize { - let got = image::load_from_memory(png).unwrap().to_rgba8(); + let got = 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(); if got.dimensions() != want.dimensions() { return (want.width() * want.height()) as usize; } @@ -86,7 +120,41 @@ fn export_selection_of_a_clipped_object_keeps_its_clip() { let board = t.doc().unwrap().doc.artboards[0].rect; let reopened = canvas(&t, board); let mut png = vec![]; - reopened.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = reopened.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 off = differing(&png, &canvas(&s, Rect::new(150.0, 150.0, 350.0, 350.0))); assert!(off < 200, "the reopened SVG: {off} pixels differ from the canvas"); } @@ -162,7 +230,24 @@ fn a_selected_clipping_path_and_a_blend_object_export_on_their_own() { // The clipping path alone: the clip group's other art stays out. run(&mut s, "select.set", json!({"ids": [circle]})); let r = run(&mut s, "document.exportSelection", json!({"format": "png", "scale": 1})); - let img = image::load_from_memory(&b64(&r)).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&b64(&r)) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(img.dimensions(), (200, 200), "cropped to the clipping path"); assert!(!img.pixels().any(|p| p[0] > 200 && p[1] < 80 && p[3] > 0), "the clipped square is left out"); // An object of a blend goes in on its own, without the blend's steps. @@ -176,7 +261,24 @@ fn a_selected_clipping_path_and_a_blend_object_export_on_their_own() { let r = run(&mut s, "document.exportSelection", json!({"format": "png", "scale": 1})); let got = rect_of(&r["bounds"]); assert!(got.x1 < 90.0 && got.y1 < 90.0, "the blend object's own bounds: {got:?}"); - let img = image::load_from_memory(&b64(&r)).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&b64(&r)) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); let centre = img.get_pixel(img.width() / 2, img.height() / 2); assert!(centre[0] > 200 && centre[3] > 200, "the object is drawn: {centre:?}"); } @@ -191,7 +293,25 @@ fn a_css_picture_of_a_clipped_object_is_clipped() { let r = run(&mut s, "css.export", json!({"ids": [star], "rasterize": true, "unnamed": true})); let image = r["images"].as_array().and_then(|i| i.first()).unwrap_or_else(|| panic!("no picture: {r}")); let png = b64(image); - let size = image::load_from_memory(&png).unwrap().to_rgba8().dimensions(); + let size = 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(); assert_eq!(size, (100, 100), "the picture is cropped to the clip"); assert!(differing(&png, &canvas(&s, Rect::new(200.0, 200.0, 300.0, 300.0))) < 100, "the picture matches the canvas"); } @@ -204,7 +324,24 @@ fn an_asset_on_a_hidden_layer_is_drawn_clipped() { let asset = run(&mut s, "assets.add", json!({"ids": [square]}))["assets"][0].as_u64().unwrap(); run(&mut s, "layer.setProps", json!({"id": layer, "visible": false})); let r = run(&mut s, "assets.export", json!({"assets": [asset], "formats": [{"format": "png", "scale": 1}]})); - let img = image::load_from_memory(&b64(&r["files"][0])).unwrap().to_rgba8(); + let img = 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(); assert_eq!(img.dimensions(), (200, 200), "cropped to the clip"); let (centre, corner) = (img.get_pixel(100, 100), img.get_pixel(3, 3)); assert!(centre[0] > 200 && centre[3] > 200, "the square is drawn: {centre:?}"); @@ -233,7 +370,27 @@ fn export_for_screens_and_assets_by_selection_keep_the_clip() { /// The red pixels of `png`. fn red(png: &[u8]) -> usize { - image::load_from_memory(png).unwrap().to_rgba8().pixels().filter(|p| p[0] > 200 && p[1] < 80 && p[3] > 200).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] > 200 && p[1] < 80 && p[3] > 200) + .count() } #[test] @@ -248,7 +405,41 @@ fn a_selection_on_a_non_printing_layer_exports_to_pdf() { run(&mut t, "document.open", json!({"name": "sel.pdf", "dataBase64": vectorcraft_format::base64_encode(&pdf)})); let page = t.doc().unwrap().doc.artboards[0].rect; let mut png = vec![]; - canvas(&t, page).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (canvas(&t, page)).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(); assert!(red(&png) > 20_000, "the PDF draws the square: {} red pixels", red(&png)); assert!(differing(&png, &canvas(&s, Rect::new(150.0, 150.0, 350.0, 350.0))) < 300, "the PDF draws what the canvas draws"); } diff --git a/crates/engine/src/cmd/fileio/tests_svg.rs b/crates/engine/src/cmd/fileio/tests_svg.rs index 121cc0b279..c7716940a1 100644 --- a/crates/engine/src/cmd/fileio/tests_svg.rs +++ b/crates/engine/src/cmd/fileio/tests_svg.rs @@ -27,9 +27,41 @@ fn tmp_dir(tag: &str) -> std::path::PathBuf { /// A session whose document holds one embedded 2×2 PNG. pub(super) fn image_session() -> Session { let mut png = Vec::new(); - image::RgbaImage::from_pixel(2, 2, image::Rgba([10, 200, 30, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(2, 2, image::Rgba([10, 200, 30, 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 mut s = Session::new(); s.execute("document.open", &json!({"name": "dot.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); s @@ -120,7 +152,26 @@ fn linked_images_are_written_next_to_the_svg() { let path = dir.join("pic.svg").to_string_lossy().to_string(); let r = s.execute("document.export", &json!({"path": path, "images": "link"})).unwrap(); let linked = r["linked"][0].as_str().unwrap(); - assert!(image::load_from_memory(&std::fs::read(linked).unwrap()).is_ok(), "{linked}"); + assert!( + craft_image_codecs::decode(&std::fs::read(linked).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()), + } + }) + .is_ok(), + "{linked}" + ); let text = std::fs::read_to_string(&path).unwrap(); let name = std::path::Path::new(linked).file_name().unwrap().to_string_lossy().to_string(); assert!(text.contains(&format!("href=\"{name}\"")), "{text}"); diff --git a/crates/engine/src/cmd/fileio/tests_svgimport.rs b/crates/engine/src/cmd/fileio/tests_svgimport.rs index d898d389cf..053c74e839 100644 --- a/crates/engine/src/cmd/fileio/tests_svgimport.rs +++ b/crates/engine/src/cmd/fileio/tests_svgimport.rs @@ -32,9 +32,41 @@ impl Drop for Folder { fn png(w: u32, h: u32) -> Vec { let mut out = vec![]; - image::RgbaImage::from_pixel(w, h, image::Rgba([230, 20, 20, 255])) - .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(w, h, image::Rgba([230, 20, 20, 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| out.extend_from_slice(&__b)) + } + .unwrap(); out } diff --git a/crates/engine/src/cmd/fileio/tests_text.rs b/crates/engine/src/cmd/fileio/tests_text.rs index 4ba819ff95..0abf12d7a7 100644 --- a/crates/engine/src/cmd/fileio/tests_text.rs +++ b/crates/engine/src/cmd/fileio/tests_text.rs @@ -65,7 +65,29 @@ fn webp_is_lossless_and_says_so_when_lossy_is_asked_for() { let r = s.execute("document.export", &json!({"format": "webp", "lossless": false, "quality": 60, "background": "black"})).unwrap(); assert_eq!(&b64(&r)[12..16], b"VP8L"); assert!(r["warnings"][0].as_str().unwrap().contains("lossless"), "{r}"); - assert_eq!(image::load_from_memory(&b64(&r)).unwrap().to_rgba8().get_pixel(29, 19).0, [0, 0, 0, 255]); + assert_eq!( + craft_image_codecs::decode(&b64(&r)) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .get_pixel(29, 19) + .0, + [0, 0, 0, 255] + ); } #[test] @@ -74,12 +96,51 @@ fn save_for_office_writes_a_png_at_the_resolution() { s.execute("file.new", &json!({"width": 612, "height": 792, "artboards": 2})).unwrap(); let r = s.execute("document.exportForOffice", &json!({"ppi": 150})).unwrap(); assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(1275), Some(1650)), "Letter at 150 ppi"); - let img = image::load_from_memory(&b64(&r)).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&b64(&r)) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(img.dimensions(), (1275, 1650)); assert_eq!(img.get_pixel(0, 0).0, [255, 255, 255, 255], "on white"); let r = s.execute("document.exportForOffice", &json!({"ppi": 72, "transparent": true, "artboard": 1})).unwrap(); assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(612), Some(792))); - assert_eq!(image::load_from_memory(&b64(&r)).unwrap().to_rgba8().get_pixel(0, 0)[3], 0, "transparent"); + assert_eq!( + craft_image_codecs::decode(&b64(&r)) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8() + .get_pixel(0, 0)[3], + 0, + "transparent" + ); assert!(s.execute("document.exportForOffice", &json!({"artboard": 2})).is_err()); assert!(s.execute("document.exportForOffice", &json!({"ppi": -3})).is_err()); let spec = crate::cmd::find_command("document.exportForOffice").unwrap(); diff --git a/crates/engine/src/cmd/fileio/tgaread.rs b/crates/engine/src/cmd/fileio/tgaread.rs index 2033e45e66..a8cf0abb68 100644 --- a/crates/engine/src/cmd/fileio/tgaread.rs +++ b/crates/engine/src/cmd/fileio/tgaread.rs @@ -23,6 +23,15 @@ pub(super) fn is_targa(bytes: &[u8]) -> bool { && descriptor & 0xc0 == 0 } +/// A Targa file's size, from its header (there is no signature for a size probe to go by). +pub(super) fn size(bytes: &[u8]) -> Option<(u32, u32)> { + let le = |at: usize| Some(u32::from(u16::from_le_bytes(bytes.get(at..at + 2)?.try_into().ok()?))); + if !is_targa(bytes) { + return None; + } + Some((le(12)?, le(14)?)) +} + /// Give `img`, decoded from Targa file `bytes`, the transparency the file stores. Bits 0 to 3 of /// the image descriptor give the number of attribute bits per pixel, and the extension area's /// Attributes Type, when the file has one, says what they hold: diff --git a/crates/engine/src/cmd/flatten/analysis.rs b/crates/engine/src/cmd/flatten/analysis.rs index 9771d18ef9..70eab3c3e5 100644 --- a/crates/engine/src/cmd/flatten/analysis.rs +++ b/crates/engine/src/cmd/flatten/analysis.rs @@ -70,9 +70,7 @@ pub(crate) fn carry(from: &Node, mut to: Node) -> Node { /// The keys of `doc`'s images that have see-through pixels (an alpha channel that isn't opaque /// everywhere). pub(crate) fn see_through_images(doc: &Document) -> BTreeSet { - let see_through = |b: &ImageBlob| { - b.mime != "image/jpeg" && image::load_from_memory(&b.bytes).is_ok_and(|i| i.color().has_alpha() && i.to_rgba8().pixels().any(|p| p[3] < 255)) - }; + let see_through = |b: &ImageBlob| b.mime != "image/jpeg" && b.has_transparency(); doc.images.iter().filter(|(_, b)| see_through(b)).map(|(k, _)| k.clone()).collect() } diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index ec850576de..1ec0f7ceaa 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -593,8 +593,8 @@ pub(crate) fn store_image(d: &mut Document, key: &str, full: ImageBlob, linked: /// Whether `bytes` are a PNG, JPEG, GIF or WebP file: the formats [`fileio::raster_image`] keeps /// as they are after reading only their header. pub(crate) fn kept_unread(bytes: &[u8]) -> bool { - use image::ImageFormat as F; - matches!(image::guess_format(bytes), Ok(F::Png | F::Jpeg | F::Gif | F::WebP)) + use craft_image_codecs::Format as F; + matches!(craft_image_codecs::detect(bytes), Some(F::Png | F::Jpeg | F::Gif | F::WebP)) } /// `blob`, an image [`fileio::raster_image`] read from a file, ready to keep. When `unread` (the @@ -2639,12 +2639,34 @@ const UNEMBED_EXTS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "tif", "tif /// Encoded image `bytes` re-encoded in the format of extension `ext` (JPEG without alpha). fn convert_image(bytes: &[u8], ext: &str) -> std::result::Result, String> { - let format = image::ImageFormat::from_extension(ext).ok_or_else(|| format!("can't write .{ext} images"))?; - let img = image::load_from_memory(bytes).map_err(|e| e.to_string())?; - let img = if format == image::ImageFormat::Jpeg { image::DynamicImage::ImageRgb8(img.to_rgb8()) } else { img }; - let mut out = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut out), format).map_err(|e| e.to_string())?; - Ok(out) + let format = match ext.to_ascii_lowercase().as_str() { + "png" => craft_image_codecs::Format::Png, + "jpg" | "jpeg" => craft_image_codecs::Format::Jpeg, + "gif" => craft_image_codecs::Format::Gif, + "webp" => craft_image_codecs::Format::WebP, + "tif" | "tiff" => craft_image_codecs::Format::Tiff, + "bmp" => craft_image_codecs::Format::Bmp, + _ => return Err(format!("can't write .{ext} images")), + }; + let mut opts = craft_image_codecs::DecodeOptions::default(); + opts.limits.max_alloc = vectorcraft_doc::MAX_RASTER_ALLOC; + opts.limits.max_width = u32::MAX; + opts.limits.max_height = u32::MAX; + let img = craft_image_codecs::decode_with(bytes, &opts).map_err(|e| e.to_string())?; + let raw = if format == craft_image_codecs::Format::Jpeg { + let rgb: Vec = img.to_rgba8().as_chunks::<4>().0.iter().flat_map(|p| [p[0], p[1], p[2]]).collect(); + craft_image_codecs::Image::from_raw( + img.width(), + img.height(), + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U8, + rgb, + ) + .map_err(|e| e.to_string())? + } else { + img + }; + craft_image_codecs::encode(&raw, format, &craft_image_codecs::EncodeOptions::default()).map_err(|e| e.to_string()) } fn unembed(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index ae07e1c860..2a073ab62a 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -719,10 +719,16 @@ fn cmyk_raster( if alpha.iter().all(|&a| a == 255) { return Ok((blob, None)); } - let mask = image::GrayImage::from_raw(img.width, img.height, alpha) - .ok_or_else(|| EngineError::Other("the image's transparency doesn't fit it".into()))?; - let mut png = Vec::new(); - mask.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| EngineError::Other(e.to_string()))?; + let mask = craft_image_codecs::Image::from_raw( + img.width, + img.height, + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U8, + alpha, + ) + .map_err(|_| EngineError::Other("the image's transparency doesn't fit it".into()))?; + let png = craft_image_codecs::encode(&mask, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map_err(|e| EngineError::Other(e.to_string()))?; Ok((blob, Some(png))) } @@ -1072,9 +1078,16 @@ pub(crate) fn check_resample_size(sw: u32, sh: u32, w: u32, h: u32) -> Result<() /// `img` as PNG bytes. fn encode_png(img: &image::RgbaImage) -> Result> { - let mut png = Vec::new(); - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| bad("object.cropImage", e.to_string()))?; - Ok(png) + let fail = |e: craft_image_codecs::CodecError| bad("object.cropImage", e.to_string()); + let raw = craft_image_codecs::Image::from_raw( + img.width(), + img.height(), + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + img.as_raw().clone(), + ) + .map_err(fail)?; + craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).map_err(fail) } fn crop_image(s: &mut Session, p: &Value) -> Result { @@ -1221,22 +1234,24 @@ fn crop_image(s: &mut Session, p: &Value) -> Result { /// The image's pixels as RGBA, held to the allowance opening a raster has. fn decode_rgba(c: &str, blob: &vectorcraft_doc::ImageBlob) -> Result { // Print rasters run to gigabytes decoded: the same allowance opening them has. - let reader = || { - image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice())) - .with_guessed_format() - .map_err(|_| bad(c, "the image's pixels can't be read")) - }; // The image's size as RGBA, read from its header, is held to that allowance before anything // is decoded (#1717). - let (w, h) = reader()?.into_dimensions().map_err(|e| bad(c, format!("the image's pixels can't be read: {e}")))?; - if u64::from(w) * u64::from(h) > crate::cmd::fileio::MAX_RASTER_ALLOC / 4 { + let header = vectorcraft_doc::header_size(&blob.bytes); + if let Some((w, h)) = header + && u64::from(w) * u64::from(h) > crate::cmd::fileio::MAX_RASTER_ALLOC / 4 + { return Err(bad(c, format!("an image of {w} × {h} pixels is too large to draw"))); } - let mut reader = reader()?; - let mut limits = image::Limits::default(); - limits.max_alloc = Some(crate::cmd::fileio::MAX_RASTER_ALLOC); - reader.limits(limits); - Ok(reader.decode().map_err(|e| bad(c, format!("the image's pixels can't be read: {e}")))?.to_rgba8()) + let mut opts = craft_image_codecs::DecodeOptions::default(); + opts.limits.max_pixels = crate::cmd::fileio::MAX_RASTER_ALLOC / 4; + opts.limits.max_alloc = crate::cmd::fileio::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(c, "the image is too large to draw"), + _ => bad(c, format!("the image's pixels can't be read: {e}")), + })?; + let (w, h) = img.dimensions(); + image::RgbaImage::from_raw(w, h, img.to_rgba8()).ok_or_else(|| bad(c, "the image's pixels can't be read")) } /// Crop Image's trim: the image cut to the box of its pixels that aren't fully transparent, the @@ -1265,9 +1280,12 @@ fn trim_image(s: &mut Session, id: NodeId, im: ImageObject) -> Result { return Ok(json!({ "id": id.0, "width": w, "height": h, "trimmed": false })); } let cut = image::imageops::crop_imm(&px, x0, y0, x1 - x0, y1 - y0).to_image(); - let mut png = Vec::new(); - cut.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| bad(C, e.to_string()))?; let (cw, ch) = (x1 - x0, y1 - y0); + let raw = + craft_image_codecs::Image::from_raw(cw, ch, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, cut.into_raw()) + .map_err(|e| bad(C, e.to_string()))?; + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map_err(|e| bad(C, e.to_string()))?; put_pixels(s, id, png, cw, ch, im.xf * Affine::translate((f64::from(x0), f64::from(y0))))?; Ok(json!({ "id": id.0, "width": cw, "height": ch, "trimmed": true })) } diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 250642285d..4463cf5885 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -1070,15 +1070,9 @@ fn queue(s: &mut Session, p: &Value) -> Result { /// The colour mode an image file stores its pixels in. fn color_mode(bytes: &[u8]) -> &'static str { - use image::{ExtendedColorType as E, ImageDecoder as _}; - let kind = image::ImageReader::new(std::io::Cursor::new(bytes)) - .with_guessed_format() - .ok() - .and_then(|r| r.into_decoder().ok()) - .map(|d| d.original_color_type()); - match kind { - Some(E::L1 | E::La1 | E::L2 | E::La2 | E::L4 | E::La4 | E::L8 | E::La8 | E::L16 | E::La16) => "Grayscale", - Some(E::Cmyk8 | E::Cmyk16) => "CMYK", + match craft_image_codecs::decode(bytes).ok().map(|img| img.layout()) { + Some(craft_image_codecs::ChannelLayout::Gray | craft_image_codecs::ChannelLayout::GrayA) => "Grayscale", + Some(craft_image_codecs::ChannelLayout::Cmyk | craft_image_codecs::ChannelLayout::CmykA) => "CMYK", _ => "RGB", } } diff --git a/crates/engine/src/cmd/place/document.rs b/crates/engine/src/cmd/place/document.rs index 0d9a1470a8..454f7302a8 100644 --- a/crates/engine/src/cmd/place/document.rs +++ b/crates/engine/src/cmd/place/document.rs @@ -366,17 +366,30 @@ fn preview(doc: &Document, art: &Node, frame: Rect) -> Option> { }) .collect(); let rgba = image::RgbaImage::from_raw(w, h, px)?; - let mut out = vec![]; - // Opaque but for the edge's anti-aliasing (an artboard drawn to whole pixels) and compositing's - // rounding: JPEG. let inner = |x: u32, y: u32| x > 0 && y > 0 && x + 1 < w && y + 1 < h; if rgba.enumerate_pixels().all(|(x, y, p)| p[3] >= 250 || !inner(x, y)) { let rgb = image::DynamicImage::ImageRgba8(rgba).to_rgb8(); - image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 80).encode_image(&rgb).ok()?; + let raw = craft_image_codecs::Image::from_raw( + rgb.width(), + rgb.height(), + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U8, + rgb.into_raw(), + ) + .ok()?; + let opts = craft_image_codecs::EncodeOptions { jpeg_quality: 80, ..Default::default() }; + craft_image_codecs::encode(&raw, craft_image_codecs::Format::Jpeg, &opts).ok() } else { - rgba.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).ok()?; + let raw = craft_image_codecs::Image::from_raw( + rgba.width(), + rgba.height(), + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + rgba.into_raw(), + ) + .ok()?; + craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() } - Some(out) } /// `s` stored in `d` (objects showing the same thing share one blob). diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index b6c500749f..1d5286b11d 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -314,7 +314,10 @@ pub const PREF_SPECS: &[PrefSpec] = &[ ("or", "Odia"), ("as", "Assamese"), ("sa", "Sanskrit"), - ("ur", "Urdu") + ("ur", "Urdu"), + ("ne", "Nepali"), + ("kok", "Konkani"), + ("sd", "Sindhi") ]) ), p!("hyphenationExceptions", "Hyphenation", "", "Exceptions (comma separated)", text), diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 566a87b22f..b51bb4a97d 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -1984,7 +1984,41 @@ mod tests { /// A `size` px image of one color `rgba`. fn blob(rgba: [u8; 4], size: u32) -> ImageBlob { let mut png = Vec::new(); - image::RgbaImage::from_pixel(size, size, image::Rgba(rgba)).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(size, size, image::Rgba(rgba))).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(); ImageBlob::png(png) } @@ -2025,9 +2059,42 @@ mod tests { let d = Document::new(100.0, 100.0); let red = blob([255, 0, 0, 255], 64); let mut png = Vec::new(); - image::RgbaImage::from_fn(64, 64, |x, y| image::Rgba(if x >= 56 && y >= 56 { [0, 0, 255, 255] } else { [255, 0, 0, 255] })) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = + (image::RgbaImage::from_fn(64, 64, |x, y| image::Rgba(if x >= 56 && y >= 56 { [0, 0, 255, 255] } else { [255, 0, 0, 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 corner = ImageBlob::png(png); let mut t = Theme::new(&d); let whole = ImageRead { clip: None, ..clipped(&corner, 64.0, 4) }; diff --git a/crates/engine/src/cmd/webexport.rs b/crates/engine/src/cmd/webexport.rs index d1c66d9d3c..078391d5b7 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -782,9 +782,9 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 /// An optimised image as straight RGBA → `(pixels, width, height)` (the dialog's preview). pub fn decode(o: &Optimized) -> std::result::Result<(Vec, u32, u32), String> { - let img = image::load_from_memory(o.display()).map_err(|e| format!("the optimised image can't be read back: {e}"))?.to_rgba8(); + let img = craft_image_codecs::decode(o.display()).map_err(|e| format!("the optimised image can't be read back: {e}"))?; let (w, h) = img.dimensions(); - Ok((img.into_raw(), w, h)) + Ok((img.to_rgba8(), w, h)) } /// Seconds to download `bytes` at `kbps` kilobits per second. diff --git a/crates/engine/src/tests/adjust.rs b/crates/engine/src/tests/adjust.rs index be4dd6a2d1..ca348ea4fa 100644 --- a/crates/engine/src/tests/adjust.rs +++ b/crates/engine/src/tests/adjust.rs @@ -31,7 +31,41 @@ pub(crate) fn fill_hex(n: &Node) -> String { fn red_image(s: &mut Session) -> NodeId { let img = image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 255])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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.edit("Place", |d, sel| { d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(png)); let id = d.alloc_id(); @@ -108,13 +142,47 @@ fn an_embedded_image_is_adjusted_for_export_without_changing_its_pixels() { let baked = vectorcraft_render::effects::bake_document(&doc).unwrap(); let NodeKind::Image(im) = &baked.node(id).unwrap().kind else { panic!("not an image") }; assert_ne!(im.key, "pic", "a recoloured copy"); - let px = image::load_from_memory(&baked.images[&im.key].bytes).unwrap().to_rgba8(); + let px = craft_image_codecs::decode(&baked.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, [0, 255, 0, 255]); assert_eq!(doc.images.len(), 1, "the document keeps its one image"); // Through Expand Appearance too. s.execute("effect.expandAppearance", &json!({})).unwrap(); let NodeKind::Image(im) = &node(&s, id).kind else { panic!("not an image") }; - let px = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8(); + let px = craft_image_codecs::decode(&s.doc().unwrap().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!(px.get_pixel(0, 0).0, [0, 255, 0, 255]); } diff --git a/crates/engine/src/tests/assets.rs b/crates/engine/src/tests/assets.rs index 64ef55d7ab..1d571884a0 100644 --- a/crates/engine/src/tests/assets.rs +++ b/crates/engine/src/tests/assets.rs @@ -140,7 +140,24 @@ fn an_asset_exports_its_art_alone() { run(&mut s, "assets.add", json!({"ids": [red]})); let out = files(&run(&mut s, "assets.export", json!({"formats": [{"format": "png", "scale": "2x"}]}))); assert_eq!(out[0].0, "Asset-1@2x.png"); - let img = image::load_from_memory(&out[0].1).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&out[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(); assert_eq!(img.dimensions(), (40, 40)); assert!(img.pixels().all(|p| p.0 == [255, 0, 0, 255]), "only the red square"); // Vector formats crop to it too. @@ -163,7 +180,24 @@ fn an_assets_crop_takes_in_its_drop_shadow() { // The shadow's reach (10 pt) on every side. assert_eq!(assets(&mut s)[0]["bounds"], json!([40.0, 40.0, 40.0, 40.0])); let out = files(&run(&mut s, "assets.export", json!({"formats": [{"format": "png", "scale": "1x"}]}))); - let img = image::load_from_memory(&out[0].1).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&out[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(); assert_eq!(img.dimensions(), (40, 40)); // The shadow's right half, x 70 to 80. assert!(img.get_pixel(35, 20)[3] > 0, "the shadow is in the image"); @@ -417,7 +451,29 @@ fn export_for_screens_writes_chosen_assets_and_keeps_its_rules() { let out = files(&r); assert_eq!(out.len(), 1); assert_eq!(out[0].0, "Asset-2@60w.png"); - assert_eq!(image::load_from_memory(&out[0].1).unwrap().to_rgba8().dimensions(), (60, 40), "the width of the asset, not the artboard"); + assert_eq!( + craft_image_codecs::decode(&out[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() + .dimensions(), + (60, 40), + "the width of the asset, not the artboard" + ); // The choice of art isn't remembered; the formats are. let settings = run(&mut s, "document.exportSettings", json!({}))["settings"].clone(); assert!(settings.get("assets").is_none() && settings["formats"][0]["scale"] == "60w"); @@ -466,7 +522,24 @@ fn assets_export_leaves_no_seam_between_abutting_shapes() { }), )); assert_eq!(out[0].0, "Asset-1.png"); - let img = image::load_from_memory(&out[0].1).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&out[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(); assert_eq!(img.dimensions(), (40, 20)); // Column 20 is the shared edge in crop space; green must stay red (no white bleed). let palest_g = (2..18).map(|y| img.get_pixel(20, y).0[1].max(img.get_pixel(19, y).0[1])).max().unwrap(); diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index eb77a0ca93..cf56247042 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -5391,7 +5391,41 @@ fn live_paint_bucket_alt_image_samples_fill_and_clears_stroke() { let mut s = session(); let img = image::RgbaImage::from_raw(1, 1, vec![0, 255, 0, 255]).unwrap(); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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.edit("Place", |d, _| { d.images.insert("px".into(), ImageBlob::png(png)); let id = d.alloc_id(); diff --git a/crates/engine/src/tests/clipflavours.rs b/crates/engine/src/tests/clipflavours.rs index 55e4cdff7f..5912fc6e8e 100644 --- a/crates/engine/src/tests/clipflavours.rs +++ b/crates/engine/src/tests/clipflavours.rs @@ -59,7 +59,24 @@ fn exported_png_of_a_red_square_is_red() { copy_red_square(&mut s); let r = run(&mut s, "clipboard.exportPng", json!({"scale": 2})); assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(80), Some(80))); - let img = image::load_from_memory(&decode(&r)).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&decode(&r)) + .map(|__cimg| { + let (__w, __h) = __cimg.dimensions(); + match (__cimg.layout(), __cimg.sample_type()) { + (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { + image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) + } + _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), + } + }) + .unwrap() + .to_rgba8(); assert_eq!(img.dimensions(), (80, 80)); assert_eq!(img.get_pixel(40, 40).0, [255, 0, 0, 255]); assert_eq!(img.get_pixel(2, 77).0, [255, 0, 0, 255], "cropped to the square"); @@ -155,7 +172,41 @@ fn import_image_then_paste_gives_an_image() { #[test] fn an_image_read_apart_loads_as_import_image_loads_it() { let mut bmp = vec![]; - image::RgbImage::from_pixel(30, 20, image::Rgb([200, 40, 40])).write_to(&mut std::io::Cursor::new(&mut bmp), image::ImageFormat::Bmp).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbImage::from_pixel(30, 20, image::Rgb([200, 40, 40]))).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(); let (mut at_once, mut apart) = (session(), session()); let p = json!({"mime": "image/bmp", "center": [100, 80]}); let mut with_data = p.clone(); @@ -195,7 +246,41 @@ fn a_pasted_bitmap_is_drawn_without_decoding_it_again() { // The image has pixels no other test uses, since every test shares the image store. let img = image::RgbImage::from_fn(300, 200, |x, y| image::Rgb([(x % 253) as u8, (y % 233) as u8, 17])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 s = session(); run(&mut s, "clipboard.importImage", json!({"dataBase64": vectorcraft_format::base64_encode(&png), "mime": "image/png"})); run(&mut s, "edit.paste", json!({})); @@ -278,7 +363,41 @@ fn copied_files_paste_by_their_content() { let png = decode(&run(&mut s, "clipboard.exportPng", json!({}))); let pdf = decode(&run(&mut s, "clipboard.exportPdf", json!({}))); let mut jpeg = vec![]; - image::RgbImage::new(2, 2).write_to(&mut std::io::Cursor::new(&mut jpeg), 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| jpeg.extend_from_slice(&__b)) + } + .unwrap(); let svg = b""; let of = |name: &str, bytes: &[u8]| file_flavour(name, &bytes[..bytes.len().min(FILE_HEAD)], &PASTE_ORDER); assert_eq!(of("red.png", &png), Some(PNG)); @@ -402,7 +521,23 @@ fn copy_leaves_out_the_png_of_art_too_large_to_scale_down() { run(&mut s, "select.set", json!({"ids": [id]})); run(&mut s, "edit.copy", json!({})); let png = s.clipboard.flavours(false, false).into_iter().find(|f| f.mime == PNG).expect("a PNG"); - let img = image::load_from_memory(&png.data).unwrap(); + let img = craft_image_codecs::decode(&png.data) + .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!(img.width() <= 4096 && img.height() <= 4096, "{}x{}", img.width(), img.height()); } @@ -445,7 +580,41 @@ fn noise_png(side: u32) -> Vec { }) .collect(); let mut out = vec![]; - image::RgbImage::from_raw(side, side, px).unwrap().write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbImage::from_raw(side, side, px).unwrap()).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 } diff --git a/crates/engine/src/tests/colorize.rs b/crates/engine/src/tests/colorize.rs index e281b3ee04..faa0af57db 100644 --- a/crates/engine/src/tests/colorize.rs +++ b/crates/engine/src/tests/colorize.rs @@ -15,7 +15,41 @@ fn session() -> Session { fn png(img: image::DynamicImage) -> ImageBlob { let mut out = Vec::new(); - img.write_to(&mut std::io::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(); ImageBlob::png(out) } diff --git a/crates/engine/src/tests/containers.rs b/crates/engine/src/tests/containers.rs index 42cebea2ad..5a5de63172 100644 --- a/crates/engine/src/tests/containers.rs +++ b/crates/engine/src/tests/containers.rs @@ -186,9 +186,41 @@ fn type_with_an_inline_graphic_stays_type_when_its_own_stroke_has_an_effect() { /// A selected 30×30 red image placed with its frame from (50, 50) to (80, 80). fn image(s: &mut Session) -> NodeId { let mut png = vec![]; - image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 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 r = run(s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [65, 65]})); NodeId(r["ids"][0].as_u64().unwrap()) } @@ -259,11 +291,44 @@ fn an_images_stroke_with_outline_object_draws_exports_and_expands_along_its_fram /// A 100×100 PNG, transparent but for an opaque red disc of radius 30 in its middle. fn disc_png() -> Vec { let mut png = vec![]; - image::RgbaImage::from_fn(100, 100, |x, y| { - let r = (f64::from(x) + 0.5 - 50.0).hypot(f64::from(y) + 0.5 - 50.0); - image::Rgba([255, 0, 0, if r <= 30.0 { 255 } else { 0 }]) - }) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_fn(100, 100, |x, y| { + let r = (f64::from(x) + 0.5 - 50.0).hypot(f64::from(y) + 0.5 - 50.0); + image::Rgba([255, 0, 0, if r <= 30.0 { 255 } else { 0 }]) + })) + .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(); png } @@ -316,9 +381,41 @@ fn an_images_stroke_with_outline_object_follows_its_opaque_area() { std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("opaque.png"); let mut png = vec![]; - image::RgbaImage::from_pixel(100, 100, image::Rgba([255, 0, 0, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(100, 100, image::Rgba([255, 0, 0, 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(); std::fs::write(&path, png).unwrap(); run(&mut s, "links.relink", json!({"ids": [im.0], "path": path})); assert_eq!([shade(&s, 41, 100), shade(&s, 45, 100), shade(&s, 64, 100)], ["white", "black", "red"]); diff --git a/crates/engine/src/tests/docsetup.rs b/crates/engine/src/tests/docsetup.rs index cf2e4a510f..21dd990087 100644 --- a/crates/engine/src/tests/docsetup.rs +++ b/crates/engine/src/tests/docsetup.rs @@ -174,6 +174,27 @@ fn language_picks_its_quotes_unless_quotes_are_given() { assert_eq!((setup(&s).quotes.double, setup(&s).quotes.single), (['“', '”'], ['‹', '›'])); } +/// Sanskrit, Nepali, Assamese, Konkani and Sindhi (#4943): each is a document language, new type +/// takes its tag, and each can be set on a text by name or tag. +#[test] +fn the_further_indian_languages_are_document_and_text_languages() { + let mut s = session(); + let id = create_text(&mut s, "a"); + for (name, tag) in [("Sanskrit", "sa"), ("Nepali", "ne"), ("Assamese", "as"), ("Konkani", "kok"), ("Sindhi", "sd")] { + s.execute("document.setup", &json!({"language": name.to_lowercase()})).unwrap(); + assert_eq!((setup(&s).language.as_str(), setup(&s).quotes.double), (name, ['“', '”'])); + let new = create_text(&mut s, "b"); + assert_eq!(text(&s, new).runs[0].style.language.as_deref(), Some(tag), "new type in {name}"); + s.execute("document.setup", &json!({"language": "English: USA"})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("text.setFormat", &json!({"language": name})).unwrap(); + assert_eq!(text(&s, id).runs[0].style.language.as_deref(), Some(tag), "{name} by name"); + s.execute("text.setFormat", &json!({"language": "English: USA"})).unwrap(); + s.execute("text.setFormat", &json!({"language": tag.to_uppercase()})).unwrap(); + assert_eq!(text(&s, id).runs[0].style.language.as_deref(), Some(tag), "{name} by tag"); + } +} + #[test] fn typographers_quotes_setting_changes_typed_quotes() { let mut s = session(); diff --git a/crates/engine/src/tests/dynamic_symbols.rs b/crates/engine/src/tests/dynamic_symbols.rs index c5ef8a1949..c3e8cf8ea0 100644 --- a/crates/engine/src/tests/dynamic_symbols.rs +++ b/crates/engine/src/tests/dynamic_symbols.rs @@ -798,7 +798,41 @@ fn a_blend_around_a_picked_objects_instance_is_left_alone() { fn image_symbol(s: &mut Session) -> (NodeId, Value) { let mut png = Vec::new(); let pixels = image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap()); - pixels.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = pixels; + 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 im = s .edit("Place", |d, _| { d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(png)); diff --git a/crates/engine/src/tests/editcolors.rs b/crates/engine/src/tests/editcolors.rs index a1abfeb259..a42f2c4ca7 100644 --- a/crates/engine/src/tests/editcolors.rs +++ b/crates/engine/src/tests/editcolors.rs @@ -403,14 +403,68 @@ fn blend_moves_a_mesh_to_the_blended_colour() { fn png(px: [[u8; 4]; 4]) -> Vec { let img = image::RgbaImage::from_raw(2, 2, px.concat()).unwrap(); let mut out = Vec::new(); - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 } fn pixels(s: &Session, id: NodeId) -> Vec<[u8; 4]> { let d = &s.doc().unwrap().doc; let NodeKind::Image(im) = &d.node(id).unwrap().kind else { panic!("not an image") }; - image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect() + 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() + .pixels() + .map(|p| p.0) + .collect() } /// A selected embedded 2×2 image. @@ -652,7 +706,41 @@ fn convert_to_indexed_refuses_bad_params() { /// An embedded `w` × `h` image of the pixels `f(x, y)`, placed and selected. fn placed(s: &mut Session, w: u32, h: u32, f: impl Fn(u32, u32) -> [u8; 4]) -> NodeId { let mut png = Vec::new(); - image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y))).write_to(&mut std::io::Cursor::new(&mut png), 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| png.extend_from_slice(&__b)) + } + .unwrap(); let r = s.execute("file.place", &json!({"name": "art.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); NodeId(r["ids"][0].as_u64().unwrap()) } @@ -681,7 +769,41 @@ fn convert_to_indexed_takes_ids_and_leaves_linked_and_colorized_images() { assert_eq!(image_key(&s, a), ka); assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step"); let mut png = Vec::new(); - image::GrayImage::from_pixel(4, 4, image::Luma([90])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::GrayImage::from_pixel(4, 4, image::Luma([90]))).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 r = s.execute("file.place", &json!({"name": "gray.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); let gray = NodeId(r["ids"][0].as_u64().unwrap()); s.execute("paint.setFill", &json!({"ids": [gray.0], "color": "#ff0000"})).unwrap(); diff --git a/crates/engine/src/tests/envelope_distort.rs b/crates/engine/src/tests/envelope_distort.rs index a0193a27f8..7c086afa77 100644 --- a/crates/engine/src/tests/envelope_distort.rs +++ b/crates/engine/src/tests/envelope_distort.rs @@ -117,7 +117,41 @@ fn the_frame_round_trips_natively() { fn red_image(s: &mut Session) -> NodeId { let img = image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 255])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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.edit("Place", |d, sel| { d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(png)); let id = d.alloc_id(); @@ -159,7 +193,41 @@ fn a_colorized_image_keeps_its_color_in_an_envelope() { let mut s = session(); let img = image::GrayImage::from_pixel(4, 4, image::Luma([0])); let mut png = vec![]; - image::DynamicImage::ImageLuma8(img).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = image::DynamicImage::ImageLuma8(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| png.extend_from_slice(&__b)) + } + .unwrap(); let im = s .edit("Place", |d, sel| { d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(png)); @@ -187,7 +255,41 @@ fn a_colorized_image_keeps_its_color_in_an_envelope() { fn two_color_image(s: &mut Session) -> NodeId { let img = image::RgbaImage::from_fn(2, 2, |x, _| if x == 0 { image::Rgba([255, 0, 0, 255]) } else { image::Rgba([0, 0, 255, 255]) }); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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.edit("Place", |d, sel| { d.images.insert("two".into(), vectorcraft_doc::ImageBlob::png(png)); let id = d.alloc_id(); diff --git a/crates/engine/src/tests/eyedropper.rs b/crates/engine/src/tests/eyedropper.rs index b3a9012e06..f4728f8a18 100644 --- a/crates/engine/src/tests/eyedropper.rs +++ b/crates/engine/src/tests/eyedropper.rs @@ -562,7 +562,41 @@ fn clicking_an_image_samples_its_pixel() { // Two pixels, orange and teal, 100 pt each, at (300, 0). let img = image::RgbaImage::from_raw(2, 1, [[255, 128, 0, 255], [0, 128, 128, 255]].concat()).unwrap(); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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.edit("Place", |d, _| { d.images.insert("px".into(), ImageBlob::png(png)); let l = d.layers[0].id; @@ -588,7 +622,41 @@ fn cmyk_doc_with_image(px: &[[u8; 4]]) -> Session { let w = px.len() as u32; let img = image::RgbaImage::from_raw(w, 1, px.concat()).unwrap(); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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.edit("Place", |d, _| { d.images.insert("px".into(), ImageBlob::png(png)); let l = d.layers[0].id; diff --git a/crates/engine/src/tests/file.rs b/crates/engine/src/tests/file.rs index b3b041e2e2..b2cbefee3d 100644 --- a/crates/engine/src/tests/file.rs +++ b/crates/engine/src/tests/file.rs @@ -459,7 +459,24 @@ fn export_selection_keeps_the_effects_in_the_crop() { assert_eq!(plain["bounds"], json!([99.5, 99.5, 21.0, 21.0]), "a plain path keeps its crop: {plain}"); s.execute("effect.apply", &json!({"effect": effect, "params": params})).unwrap(); let png = |v: &serde_json::Value| { - image::load_from_memory(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).unwrap().to_rgba8() + craft_image_codecs::decode(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).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() + .to_rgba8() }; let v = s.execute("document.exportSelection", &json!({"format": "png", "background": "transparent"})).unwrap(); let b: Vec = v["bounds"].as_array().unwrap().iter().map(|n| n.as_f64().unwrap()).collect(); @@ -485,7 +502,24 @@ fn a_screen_outer_glow_is_in_raster_exports() { s.execute("effect.apply", &json!({"effect": "stylize.outerGlow"})).unwrap(); let mut pixel = |p: serde_json::Value| { let v = s.execute("document.export", &p).unwrap(); - let img = image::load_from_memory(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).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() + .to_rgba8(); // 2 pt past the square's stroke, on the right. *img.get_pixel(122, 110) }; @@ -512,7 +546,24 @@ fn export_selection_keeps_a_groups_shadow_in_the_crop() { let b: Vec = v["bounds"].as_array().unwrap().iter().map(|n| n.as_f64().unwrap()).collect(); // The shadow of the right square reaches x = 158.5. assert!(b[0] < 99.5 && b[0] + b[2] >= 158.5, "{v}"); - let img = image::load_from_memory(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).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() + .to_rgba8(); assert!(img.get_pixel((155.0 - b[0]) as u32, img.height() / 2)[3] > 0, "the shadow is in the image"); } @@ -534,7 +585,24 @@ fn the_arts_bounds_take_in_the_shadow_of_a_group_and_of_type() { s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [id], "params": {"x": 8, "y": 0, "blur": 0}})).unwrap(); s.execute("select.set", &json!({"ids": [id]})).unwrap(); let png = |v: &serde_json::Value| { - image::load_from_memory(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).unwrap().to_rgba8() + craft_image_codecs::decode(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).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() + .to_rgba8() }; let art = s.execute("document.export", &json!({"format": "png", "useArtboards": false, "background": "transparent"})).unwrap(); let sel = s.execute("document.exportSelection", &json!({"format": "png", "background": "transparent"})).unwrap(); diff --git a/crates/engine/src/tests/fileinfo.rs b/crates/engine/src/tests/fileinfo.rs index 54482826b3..d573235335 100644 --- a/crates/engine/src/tests/fileinfo.rs +++ b/crates/engine/src/tests/fileinfo.rs @@ -499,7 +499,26 @@ fn png_exports_carry_text_chunks() { assert_eq!(get("Keywords"), Some("fair, Poster, print")); assert_eq!(get("Copyright"), Some("(c) 2026 Ada")); assert!(get("Creation Time").is_some_and(|t| t.ends_with('Z'))); - assert!(image::load_from_memory(&png).is_ok(), "still a valid PNG"); + assert!( + 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()), + } + }) + .is_ok(), + "still a valid PNG" + ); } #[test] diff --git a/crates/engine/src/tests/legacy_ai.rs b/crates/engine/src/tests/legacy_ai.rs index fefed0ad11..3ecdb4a065 100644 --- a/crates/engine/src/tests/legacy_ai.rs +++ b/crates/engine/src/tests/legacy_ai.rs @@ -300,7 +300,41 @@ fn a_radial_gradient_lists_its_stops_from_the_first() { /// A `w`×`h` PNG of one colour (`rgba`), 72 ppi. fn png(w: u32, h: u32, rgba: [u8; 4]) -> Vec { let mut out = vec![]; - image::RgbaImage::from_pixel(w, h, image::Rgba(rgba)).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(w, h, image::Rgba(rgba))).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 } @@ -402,7 +436,41 @@ fn disk(size: u32, r: f64) -> Vec { image::Rgba([0, 0, 0, ((r + 0.5 - d).clamp(0.0, 1.0) * 255.0).round() as u8]) }); let mut out = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 } @@ -530,7 +598,41 @@ fn colorized_bitmap_over_square() -> (Session, Vec) { s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); let gray = vec![0, 255, 0, 255, 255, 0, 255, 0]; let mut bytes = vec![]; - image::GrayImage::from_raw(4, 2, gray.clone()).unwrap().write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::GrayImage::from_raw(4, 2, gray.clone()).unwrap()).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(); let p = json!({"name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&bytes), "rect": [30, 10, 40, 20]}); s.execute("file.place", &p).unwrap(); s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap(); @@ -593,10 +695,41 @@ fn a_colorized_image_of_black_and_clear_pixels_is_written_as_an_image_mask() { s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); s.execute("swatch.new", &json!({"name": "Ink", "color": {"c": 100, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap(); let mut bytes = vec![]; - image::GrayAlphaImage::from_raw(2, 1, vec![0, 255, 0, 0]) - .unwrap() - .write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::GrayAlphaImage::from_raw(2, 1, vec![0, 255, 0, 0]).unwrap()).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(); let p = json!({"name": "c.png", "dataBase64": vectorcraft_format::base64_encode(&bytes), "rect": [30, 10, 20, 10]}); s.execute("file.place", &p).unwrap(); s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap(); @@ -732,7 +865,41 @@ fn an_artboard_the_document_does_not_have_is_refused_as_an_export_refuses_it() { fn checker(a: [u8; 4], b: [u8; 4]) -> Vec { let img = image::RgbaImage::from_fn(32, 32, |x, y| image::Rgba(if (x < 16) == (y < 16) { a } else { b })); let mut out = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 } @@ -760,7 +927,41 @@ fn colorized_pattern_over_blue() -> Session { let tile = image::GrayImage::from_fn(32, 32, |x, y| image::Luma([if (x < 16) == (y < 16) { 0 } else { 255 }])); let mut bytes = vec![]; - tile.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = tile.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(); let mut s = pattern_over_blue(&bytes, 1.0); let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); assert!(d.patterns[0].art.iter_mut().any(|art| colorize_image(std::sync::Arc::make_mut(art)))); diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index ada206784a..b3b98189fb 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -35,7 +35,41 @@ impl Drop for Folder { pub(crate) fn png(w: u32, h: u32, rgb: [u8; 3]) -> Vec { let mut out = vec![]; let [r, g, b] = rgb; - image::RgbaImage::from_pixel(w, h, image::Rgba([r, g, b, 255])).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(w, h, image::Rgba([r, g, b, 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| out.extend_from_slice(&__b)) + } + .unwrap(); out } @@ -200,7 +234,41 @@ fn linked_dib_and_pns_files_place_update_and_relink() { let bmp = |w: u32, h: u32, rgb: [u8; 3]| { let mut out = vec![]; let [r, g, b] = rgb; - image::RgbImage::from_pixel(w, h, image::Rgb([r, g, b])).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Bmp).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbImage::from_pixel(w, h, image::Rgb([r, g, b]))).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| out.extend_from_slice(&__b)) + } + .unwrap(); out }; let dir = Folder::new("dib"); @@ -1300,7 +1368,41 @@ pub(crate) fn cut_png(w: u32, h: u32) -> Vec { image::Rgb([v as u8, (v >> 8) as u8, (v >> 16) as u8]) }); let mut out = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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.truncate(out.len() / 2); out } @@ -1414,12 +1516,27 @@ fn low_res_proxy_eps_export_uses_full_resolution_from_the_linked_file() { let (full, warnings) = cmd::links::full_linked_images(&s.doc().unwrap().doc, Default::default()); assert!(warnings.is_empty(), "{warnings:?}"); assert!(!full.images[&key].is_proxy()); - let dim = - image::ImageReader::new(std::io::Cursor::new(full.images[&key].bytes.as_ref())).with_guessed_format().unwrap().into_dimensions().unwrap(); + let dim = craft_image_codecs::decode(full.images[&key].bytes.as_ref()).unwrap().dimensions(); assert_eq!(dim, (600, 300)); let png_out = s.execute("document.export", &json!({"format": "png"})).unwrap(); let bytes = vectorcraft_format::base64_decode(png_out["dataBase64"].as_str().unwrap()).unwrap(); - let rendered = image::load_from_memory(&bytes).unwrap(); + let rendered = 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(); assert!(rendered.width() >= 400 && rendered.height() >= 300); assert!(near(centre_colour(&s.doc().unwrap().doc), RED), "canvas still shows the preview"); } @@ -1489,7 +1606,41 @@ fn a_file_read_for_opening_has_its_links_read_and_its_type_laid_out() { let dir = Folder::new("read-for-open"); let tif = dir.file("art/photo.tif"); let mut tiff = vec![]; - image::RgbImage::from_pixel(600, 300, image::Rgb(RED)).write_to(&mut std::io::Cursor::new(&mut tiff), image::ImageFormat::Tiff).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbImage::from_pixel(600, 300, image::Rgb(RED))).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::Tiff, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| tiff.extend_from_slice(&__b)) + } + .unwrap(); write(&tif, &tiff); let (gone, changed) = (dir.file("gone.png"), dir.file("changed.png")); write(&gone, &png(300, 100, BLUE)); diff --git a/crates/engine/src/tests/live.rs b/crates/engine/src/tests/live.rs index c372bcf784..2aa182c8b9 100644 --- a/crates/engine/src/tests/live.rs +++ b/crates/engine/src/tests/live.rs @@ -1525,7 +1525,41 @@ fn two_colour_image(s: &mut Session, clear_right: bool, linked: bool) -> NodeId let right = image::Rgba([0, 0, 255, if clear_right { 0 } else { 255 }]); let img = image::RgbaImage::from_fn(8, 4, |x, _| if x < 4 { image::Rgba([255, 0, 0, 255]) } else { right }); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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.edit("Place", |d, sel| { d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(png)); let id = d.alloc_id(); diff --git a/crates/engine/src/tests/nativefile.rs b/crates/engine/src/tests/nativefile.rs index 4156dc7599..336c14dcea 100644 --- a/crates/engine/src/tests/nativefile.rs +++ b/crates/engine/src/tests/nativefile.rs @@ -126,7 +126,23 @@ fn preview_is_at_most_256_pixels() { let mut s = session(); let bytes = saved(&mut s, json!({"preview": true, "compress": true})); let png = vectorcraft_format::preview(&bytes).expect("a preview"); - 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()), (256, 128), "the 400×200 artboard fitted into 256 px"); assert!(vectorcraft_format::preview(&saved(&mut s, json!({}))).is_none(), "off by default"); } @@ -154,7 +170,41 @@ fn saving_writes_through_a_temporary_file() { fn unused_images_are_left_out_of_saves() { let mut s = session(); 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(); let r = s.execute("file.place", &json!({"name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); let id = r["ids"][0].as_u64().unwrap(); assert_eq!(json_of(&saved(&mut s, json!({})))["images"].as_object().unwrap().len(), 1); diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 094f634799..9e20de0ad1 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -90,7 +90,26 @@ fn a_white_background_exports_opaque() { let mut s = new_doc(json!({"width": 20, "height": 20, "backgroundContents": bg})); let r = s.execute("document.export", &json!({"format": "png"})).unwrap(); let png = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); - image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(10, 10).0 + 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(10, 10) + .0 }; assert_eq!(alpha("white"), [255, 255, 255, 255]); assert_eq!(alpha("transparent")[3], 0); @@ -540,9 +559,41 @@ fn edit_print_profile(s: &mut Session, dir: &std::path::Path) { // One embedded image becomes a symbol's art, another stays on the profile's layer. let png = |rgb: [u8; 3]| { let mut out = vec![]; - image::RgbaImage::from_pixel(4, 4, image::Rgba([rgb[0], rgb[1], rgb[2], 255])) - .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(4, 4, image::Rgba([rgb[0], rgb[1], rgb[2], 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| out.extend_from_slice(&__b)) + } + .unwrap(); vectorcraft_format::base64_encode(&out) }; s.execute("file.place", &json!({"name": "red.png", "dataBase64": png([255, 0, 0]), "link": false})).unwrap(); diff --git a/crates/engine/src/tests/pdfraster.rs b/crates/engine/src/tests/pdfraster.rs index 1e0a2ecfde..c4438cf7e2 100644 --- a/crates/engine/src/tests/pdfraster.rs +++ b/crates/engine/src/tests/pdfraster.rs @@ -2,7 +2,6 @@ //! live objects and single fills and strokes are written with images of their shadows, glows and //! blurs (no "left out" warning), and the PDF reads back looking like the canvas. -use std::io::Cursor; use std::sync::Arc; use serde_json::json; @@ -38,7 +37,41 @@ fn with(mut n: Node, fx: Effect) -> Node { fn png(w: u32, h: u32) -> Vec { let img = image::RgbaImage::from_fn(w, h, |x, _| image::Rgba([(x * 255 / w) as u8, 60, 160, 255])); let mut out = Vec::new(); - image::DynamicImage::from(img).write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = image::DynamicImage::from(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 } diff --git a/crates/engine/src/tests/place.rs b/crates/engine/src/tests/place.rs index cade51bca6..b749c31e26 100644 --- a/crates/engine/src/tests/place.rs +++ b/crates/engine/src/tests/place.rs @@ -20,7 +20,41 @@ fn session() -> Session { /// A `w`×`h` PNG of one colour (`rgba`), declaring `ppi` when given. fn png(w: u32, h: u32, rgba: [u8; 4], ppi: Option) -> Vec { let mut out = vec![]; - image::RgbaImage::from_pixel(w, h, image::Rgba(rgba)).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(w, h, image::Rgba(rgba))).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(); match ppi { Some(r) => cmd::fileio::ppi::with_png_resolution(&out, (r, r)), None => out, @@ -482,13 +516,46 @@ fn keeping_an_image_decodes_nothing() { } /// `w`×`h` pixels of noise, which compress little, encoded as `format`. -fn noise(w: u32, h: u32, format: image::ImageFormat) -> Vec { +fn noise(w: u32, h: u32, format: craft_image_codecs::Format) -> Vec { let img = image::RgbImage::from_fn(w, h, |x, y| { let v = x.wrapping_mul(2_654_435_761) ^ y.wrapping_mul(40_503).rotate_left(13); image::Rgb([v as u8, (v >> 8) as u8, (v >> 16) as u8]) }); let mut out = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut out), format).unwrap(); + { + let __dyn: image::DynamicImage = img.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, format, &craft_image_codecs::EncodeOptions::default()).map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out } @@ -497,7 +564,7 @@ fn noise(w: u32, h: u32, format: image::ImageFormat) -> Vec { /// cut short still decodes, with its missing rows empty, and is placed. #[test] fn an_image_whose_pixels_cant_be_read_is_not_placed() { - let mut cut = noise(600, 300, image::ImageFormat::Png); + let mut cut = noise(600, 300, craft_image_codecs::Format::Png); cut.truncate(cut.len() / 2); let mut s = session(); let info = s.execute("file.place.info", &file("cut.png", &cut)).unwrap(); @@ -513,7 +580,7 @@ fn an_image_whose_pixels_cant_be_read_is_not_placed() { assert!(top_children(&s).is_empty(), "{p}: nothing placed"); assert_eq!((s.doc().unwrap().history.undo.len(), s.journal.len()), (undo, journal), "{p}"); } - let mut jpeg = noise(600, 300, image::ImageFormat::Jpeg); + let mut jpeg = noise(600, 300, craft_image_codecs::Format::Jpeg); jpeg.truncate(jpeg.len() / 2); let r = place(&mut s, "cut.jpg", &jpeg, json!({})); assert_eq!(r["format"], "jpg"); @@ -894,7 +961,41 @@ fn placed_art_brings_its_brushes_renaming_on_conflict() { fn a_placed_brush_whose_art_uses_a_renamed_image_is_copied() { let file = |pixel: u8| { let mut png = vec![]; - image::GrayImage::from_pixel(2, 1, image::Luma([pixel])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::GrayImage::from_pixel(2, 1, image::Luma([pixel]))).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 s = session(); s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); s.edit("Brush", |d, _| { @@ -942,7 +1043,41 @@ fn a_placed_brush_whose_art_uses_a_renamed_image_is_copied() { fn info_reports_size_resolution_colour_mode_and_link() { let mut s = session(); let mut gray = vec![]; - image::GrayImage::from_pixel(300, 150, image::Luma([128])).write_to(&mut std::io::Cursor::new(&mut gray), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::GrayImage::from_pixel(300, 150, image::Luma([128]))).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| gray.extend_from_slice(&__b)) + } + .unwrap(); let gray = cmd::fileio::ppi::with_png_resolution(&gray, (300.0, 300.0)); let mut p = file("scan.png", &gray); p["thumbnail"] = json!(16); @@ -950,7 +1085,23 @@ fn info_reports_size_resolution_colour_mode_and_link() { assert_eq!((info["colorMode"].as_str(), info["pixelWidth"].as_u64()), (Some("Grayscale"), Some(300))); assert_eq!(info["ppi"], json!([300.0, 300.0])); assert!(close(info["width"].as_f64().unwrap(), 72.0)); - let thumb = image::load_from_memory(&vectorcraft_format::base64_decode(info["thumbnailBase64"].as_str().unwrap()).unwrap()).unwrap(); + let thumb = craft_image_codecs::decode(&vectorcraft_format::base64_decode(info["thumbnailBase64"].as_str().unwrap()).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!((thumb.width(), thumb.height()), (16, 8)); assert!(top_children(&s).is_empty(), "info places nothing"); // A path is linked by default. @@ -1090,7 +1241,7 @@ fn files_read_for_the_place_cursor_apart_from_the_session_load_it_as_file_place_ /// queue, read with the session or apart from it. #[test] fn the_place_queue_skips_an_image_whose_pixels_cant_be_read() { - let mut cut = noise(600, 300, image::ImageFormat::Png); + let mut cut = noise(600, 300, craft_image_codecs::Format::Png); cut.truncate(cut.len() / 2); let p = json!({"files": [file("a.png", &png(40, 20, [9, 9, 9, 255], None)), file("cut.png", &cut)], "link": false}); let (mut a, mut b) = (session(), session()); @@ -1137,7 +1288,41 @@ fn the_place_queue_draws_a_thumbnail_without_decoding_the_image_again() { // Pixels no other test uses, since every test shares the image store. let img = image::RgbImage::from_fn(320, 160, |x, y| image::Rgb([(x % 251) as u8, 23, (y % 241) as u8])); let mut bytes = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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(); let p = json!({"files": [file("q.png", &bytes)], "link": false, "thumbnail": 64}); let decodes = vectorcraft_render::image_decodes(); let r = session().execute("file.place.queue", &p).unwrap(); diff --git a/crates/engine/src/tests/placed_document.rs b/crates/engine/src/tests/placed_document.rs index 64926b7cfb..8c2d4a7e19 100644 --- a/crates/engine/src/tests/placed_document.rs +++ b/crates/engine/src/tests/placed_document.rs @@ -152,7 +152,26 @@ fn a_placed_document_is_vectors_in_every_output() { assert_eq!(images, 0, "no image in the PDF"); assert!(paths > 0); let png = decode(&s.execute("document.serialize", &json!({"format": "png"})).unwrap()); - let [r, g, b, _] = image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(200, 150).0; + let [r, g, b, _] = 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(200, 150) + .0; assert!(near([r, g, b], RED), "{:?}", [r, g, b]); for format in ["eps", "emf", "dxf"] { let out = s.execute("document.serialize", &json!({"format": format})).unwrap(); @@ -192,7 +211,26 @@ fn the_preview_is_saved_so_the_document_shows_it_without_its_file() { // Output with the file gone: the preview, with a warning. let png = s.execute("document.serialize", &json!({"format": "png"})).unwrap(); assert!(png["warnings"].to_string().contains("1 placed document output as its preview"), "{png}"); - let [r, g, b, _] = image::load_from_memory(&decode(&png)).unwrap().to_rgba8().get_pixel(200, 150).0; + let [r, g, b, _] = craft_image_codecs::decode(&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(200, 150) + .0; assert!(near([r, g, b], RED), "{:?}", [r, g, b]); // Saved for older apps: the art it shows (here its preview), as plain objects. let old: Value = diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 1572004d11..8ea5d9f3b5 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -1157,9 +1157,41 @@ fn pathfinder_takes_swatch_linked_pieces_of_type_in_a_reshaped_group() { fn an_image_s_painted_fill_is_hit_and_measured_as_drawn() { let mut s = session(); let mut png = vec![]; - image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 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 r = run(&mut s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [65, 65]})); let im = NodeId(r["ids"][0].as_u64().unwrap()); run(&mut s, "swatch.new", json!({"name": "Leaf", "color": "#00ff00"})); diff --git a/crates/engine/src/tests/printadvanced.rs b/crates/engine/src/tests/printadvanced.rs index 8faa2f7adf..e183e7dfb2 100644 --- a/crates/engine/src/tests/printadvanced.rs +++ b/crates/engine/src/tests/printadvanced.rs @@ -171,7 +171,24 @@ fn print_as_bitmap_honours_rich_black() { } }); let bytes = &prepared.images[key.as_ref().expect("bitmap image")].bytes; - let img = image::load_from_memory(bytes).unwrap().to_rgba8(); + let img = 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(); img.get_pixel(img.width() / 2, img.height() / 2).0 }; let accurate = centre(&crate::cmd::printadvanced::prepare("file.print", doc(&s), &set, &saved, false).unwrap().unwrap()); diff --git a/crates/engine/src/tests/rasterfilters.rs b/crates/engine/src/tests/rasterfilters.rs index d1075c1207..b46cd1e572 100644 --- a/crates/engine/src/tests/rasterfilters.rs +++ b/crates/engine/src/tests/rasterfilters.rs @@ -287,7 +287,41 @@ fn rings_png() -> Vec { image::Rgba([v as u8, v as u8, 255 - v as u8, 255]) }); let mut png = Vec::new(); - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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(); png } diff --git a/crates/engine/src/tests/rastersettings.rs b/crates/engine/src/tests/rastersettings.rs index 320ecb6317..de09e921df 100644 --- a/crates/engine/src/tests/rastersettings.rs +++ b/crates/engine/src/tests/rastersettings.rs @@ -34,7 +34,24 @@ fn effect_image(doc: &Document) -> image::RgbaImage { let kids = flat.layers[0].children().unwrap(); let NodeKind::Group { children, .. } = &kids[0].kind else { panic!("a shadow becomes a group") }; let NodeKind::Image(im) = &children[0].kind else { panic!("the image goes under the object") }; - image::load_from_memory(&flat.images[&im.key].bytes).unwrap().to_rgba8() + craft_image_codecs::decode(&flat.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() } #[test] @@ -167,7 +184,24 @@ fn the_color_model_and_anti_alias_reach_the_pixels() { let out = s.execute("object.rasterize", &json!({"colorModel": "rgb"})).unwrap(); let d = &s.doc().unwrap().doc; let NodeKind::Image(im) = &d.node(id(&out)).unwrap().kind else { panic!("an image") }; - let img = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8(); + let img = 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!(img.pixels().all(|p| p[3] == 0 || p[3] == 255), "hard edges"); assert!(img.pixels().any(|p| p[3] == 0) && img.pixels().any(|p| p[3] == 255)); } @@ -184,7 +218,24 @@ fn rasterize_takes_the_document_settings_as_defaults() { assert_eq!((out["width"].as_u64(), out["height"].as_u64()), (Some(60), Some(60)), "10 pt around"); let d = &s.doc().unwrap().doc; let NodeKind::Image(im) = &d.node(id(&out)).unwrap().kind else { panic!("an image") }; - let img = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8(); + let img = 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!(img.get_pixel(0, 0).0, [255, 255, 255, 255], "white around the art"); let p = img.get_pixel(30, 30).0; assert!(p[0] == p[1] && p[1] == p[2] && p[0] < 128, "red in grayscale: {p:?}"); @@ -395,7 +446,24 @@ fn object_rasterize_takes_in_everything_an_effect_stack_paints() { let made = id(&s.execute("object.rasterize", &json!({"ppi": 72, "background": "transparent"})).unwrap()); let d = &s.doc().unwrap().doc; let (width, height, xf, png, _) = rasterized(d, d.node(made).unwrap()); - let img = image::load_from_memory(&png).unwrap().to_rgba8(); + 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() + .to_rgba8(); // 41 pt of rectangle and stroke, and 6 pt of blur and 10 pt of white on each side: white from // the first column to the last. assert_eq!((width, xf.translation().x), (73, 34.0)); @@ -503,7 +571,24 @@ fn rasterize_to_cmyk_makes_a_cmyk_image() { let mask = masked.extras().mask.as_deref().expect("an opacity mask").clone(); let d = &s.doc().unwrap().doc; let NodeKind::Image(m) = &mask.art.kind else { panic!("the mask is an image") }; - let alpha = image::load_from_memory(&d.images[&m.key].bytes).unwrap().to_luma8(); + let alpha = 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_luma8(); assert_eq!((alpha.get_pixel(1, 1).0, alpha.get_pixel(25, 25).0), ([0], [255])); assert!(mask.clip); } @@ -530,7 +615,24 @@ fn rasterize_to_grayscale_or_bitmap_makes_a_grayscale_image() { assert!(n.extras().mask.is_none(), "{mode} {model} {background}: no opacity mask"); let NodeKind::Image(im) = &n.kind else { panic!("an image") }; let blob = d.images[&im.key].clone(); - let pixels = image::load_from_memory(&blob.bytes).unwrap().to_luma_alpha8(); + let pixels = 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_luma_alpha8(); assert_eq!(pixels.dimensions(), (50, 50)); let at = |x, y| pixels.get_pixel(x, y).0; s.execute("edit.undo", &json!({})).unwrap(); diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index 8a950fcbb3..4bb0bdf3fe 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -1250,7 +1250,41 @@ fn global_adjust_refuses_params_of_the_wrong_form() { fn halves_image(s: &mut Session, w: u32, h: u32, left: [u8; 4], right: [u8; 4]) -> (NodeId, vectorcraft_geom::Rect) { let img = image::RgbaImage::from_fn(w, h, |x, _| image::Rgba(if x < w / 2 { left } else { right })); let mut png = Vec::new(); - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 r = run(s, "file.place", json!({"name": "halves.png", "dataBase64": vectorcraft_format::base64_encode(&png)})); let id = NodeId(r["ids"][0].as_u64().unwrap()); let b = s.doc().unwrap().doc.node(id).unwrap().visual_bounds().unwrap(); @@ -1375,7 +1409,41 @@ fn theme_picker_reads_symbol_art_and_nested_patterns() { fn theme_picker_reads_the_color_of_a_colorized_image() { let mut s = session(); let mut png = Vec::new(); - image::GrayImage::from_pixel(8, 8, image::Luma([90])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::GrayImage::from_pixel(8, 8, image::Luma([90]))).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 r = run(&mut s, "file.place", json!({"name": "gray.png", "dataBase64": vectorcraft_format::base64_encode(&png)})); let id = NodeId(r["ids"][0].as_u64().unwrap()); let b = s.doc().unwrap().doc.node(id).unwrap().visual_bounds().unwrap(); @@ -1430,7 +1498,41 @@ fn theme_picker_reads_an_image_inside_its_clipping_path() { image::Rgba(if corner { [0, 0, 255, 255] } else { [255, 0, 0, 255] }) }); let mut png = Vec::new(); - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 r = run(&mut s, "file.place", json!({"name": "corners.png", "dataBase64": vectorcraft_format::base64_encode(&png)})); let id = NodeId(r["ids"][0].as_u64().unwrap()); let b = s.doc().unwrap().doc.node(id).unwrap().visual_bounds().unwrap(); diff --git a/crates/engine/src/tests/save.rs b/crates/engine/src/tests/save.rs index 99febca6b2..076e964212 100644 --- a/crates/engine/src/tests/save.rs +++ b/crates/engine/src/tests/save.rs @@ -760,7 +760,23 @@ fn eps_save_bounds_large_page_preview_without_cropping_vector_or_editing_data() let (ps, tiff) = vectorcraft_eps::sections(&bytes).unwrap(); let tiff = tiff.unwrap(); assert!(tiff.len() < 4 * 1024 * 1024 + 64 * 1024, "compatibility preview grew to {} bytes", tiff.len()); - let preview = image::load_from_memory_with_format(tiff, image::ImageFormat::Tiff).unwrap(); + let preview = 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(); assert_eq!((preview.width(), preview.height()), (1024, 1024)); assert!(std::str::from_utf8(ps).unwrap().contains("%%BoundingBox: 0 0 4000 4000")); let native = vectorcraft_format::load(&vectorcraft_eps::native(&bytes).unwrap()).unwrap(); diff --git a/crates/engine/src/tests/select_effects.rs b/crates/engine/src/tests/select_effects.rs index 5ab9fd1bf8..f52ad14481 100644 --- a/crates/engine/src/tests/select_effects.rs +++ b/crates/engine/src/tests/select_effects.rs @@ -168,9 +168,41 @@ fn a_click_on_the_drop_shadow_of_a_symbols_art_does_not_select_the_instance() { fn a_click_on_the_drop_shadow_of_an_image_outside_its_frame_does_not_select_it() { let mut s = session(); let mut png = vec![]; - image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 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 r = run(&mut s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [65, 65]})); let im = NodeId(r["ids"][0].as_u64().unwrap()); // The frame lies from x 50 to 80 and the shadow from 90 to 120. diff --git a/crates/engine/src/tests/symbolbounds.rs b/crates/engine/src/tests/symbolbounds.rs index 5140d5630f..50adeededb 100644 --- a/crates/engine/src/tests/symbolbounds.rs +++ b/crates/engine/src/tests/symbolbounds.rs @@ -506,7 +506,24 @@ fn a_copied_instances_png_is_cropped_to_its_art() { let r = run(&mut s, "clipboard.exportPng", json!({})); assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(40), Some(20))); let png = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); - let img = image::load_from_memory(&png).unwrap().to_rgba8(); + 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() + .to_rgba8(); assert_eq!(img.get_pixel(20, 10).0, [0, 0, 0, 255], "the art fills the picture"); } diff --git a/crates/engine/src/tests/warp_images.rs b/crates/engine/src/tests/warp_images.rs index 9dc781ee16..3645157a2b 100644 --- a/crates/engine/src/tests/warp_images.rs +++ b/crates/engine/src/tests/warp_images.rs @@ -34,7 +34,41 @@ fn quarters(s: &mut Session) -> NodeId { image::Rgba([r, g, b, 255]) }); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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.edit("Place", |d, sel| { d.images.insert("quarters".into(), vectorcraft_doc::ImageBlob::png(png)); let id = d.alloc_id(); @@ -168,7 +202,24 @@ fn a_warped_image_keeps_its_bend_in_png() { let mut s = session(); arc_image(&mut s); let out = s.execute("document.export", &json!({"format": "png"})).unwrap(); - let png = image::load_from_memory(&decoded(&out)).unwrap().to_rgba8(); + let png = craft_image_codecs::decode(&decoded(&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() + .to_rgba8(); // The artboard starts at (0, 0) and the export draws one pixel a point. assert_eq!((png.width(), png.height()), (800, 600)); for &(u, v) in &SAMPLES { @@ -241,7 +292,41 @@ fn expand_appearance_of_a_warped_image_draws_as_the_canvas_did() { fn red_on_clear(s: &mut Session) -> NodeId { let img = image::GrayImage::from_fn(40, 40, |_, y| image::Luma([if y < 20 { 0 } else { 255 }])); let mut png = vec![]; - image::DynamicImage::ImageLuma8(img).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = image::DynamicImage::ImageLuma8(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| png.extend_from_slice(&__b)) + } + .unwrap(); let id = s .edit("Place", |d, sel| { d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(png)); @@ -302,7 +387,41 @@ fn half_clear_arc(s: &mut Session) { fn clear_arc(s: &mut Session, alpha: impl Fn(u32) -> u8) { let img = image::RgbaImage::from_fn(40, 40, |x, _| image::Rgba([255, 0, 0, alpha(x)])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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.edit("Place", |d, sel| { d.images.insert("half".into(), vectorcraft_doc::ImageBlob::png(png)); let id = d.alloc_id(); diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index cf427f8174..ccd20e119c 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -64,7 +64,24 @@ fn one(s: &mut Session, p: Value) -> Vec { } fn pixels(file: &[u8]) -> image::RgbaImage { - image::load_from_memory(file).unwrap().to_rgba8() + craft_image_codecs::decode(file) + .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 distinct(img: &image::RgbaImage) -> usize { diff --git a/crates/engine/tests/affinity_corpus.rs b/crates/engine/tests/affinity_corpus.rs index f92403d086..c1dac68981 100644 --- a/crates/engine/tests/affinity_corpus.rs +++ b/crates/engine/tests/affinity_corpus.rs @@ -81,7 +81,24 @@ fn public_affinity_documents_render_like_their_affinity_thumbnails() { let loaded = vectorcraft_engine::cmd::fileio::load(name, &bytes).unwrap(); assert!(!loaded.preview_only, "{name} opened as its preview: {:?}", loaded.warnings); let d = &loaded.doc; - let thumb = image::load_from_memory(vectorcraft_affinity::preview(&bytes).unwrap().png).unwrap().to_rgba8(); + let thumb = craft_image_codecs::decode(vectorcraft_affinity::preview(&bytes).unwrap().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 embedded thumbnail shows the union of the artboards. Check every board, // including small ones that the previous largest-board-only check omitted. let union = d.artboards.iter().map(|a| a.rect).reduce(|a, b| a.union(b)).unwrap(); @@ -166,7 +183,24 @@ fn affinity3_all_artboards_survive_native_save_and_export() { assert_eq!(vectorcraft_pdf::import(&pdf).unwrap().artboards.len(), 1, "{name} board {index}: PDF reimport"); let psd = vectorcraft_engine::cmd::fileio::encode(doc, "psd", ¶ms).unwrap(); let png = vectorcraft_engine::cmd::fileio::encode(doc, "png", ¶ms).unwrap(); - let png = image::load_from_memory(&png).unwrap().to_rgba8(); + let png = 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(); let (merged, has_alpha) = psd_merged(&psd); assert_eq!(merged.dimensions(), png.dimensions(), "{name} board {index}: PSD image dimensions"); // PSD merged RGB is stored on a white matte for readers that ignore alpha; diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index 8ea057cd12..a7d516f8eb 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -558,7 +558,41 @@ fn the_eyedropper_takes_an_image_pixel_into_the_working_rgb_space() { let mut s = session(); let img = image::RgbaImage::from_raw(1, 1, vec![83, 170, 223, 255]).unwrap(); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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.edit("Place", |d, _| { d.images.insert("px".into(), ImageBlob::png(png)); let l = d.layers[0].id; @@ -653,7 +687,24 @@ fn freeform_rgb_points_mix_in_the_working_rgb_space() { let canvas = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts).pixel(50, 50); let svg = vectorcraft_svg::export_full(&d, &vectorcraft_svg::ExportOptions::default(), None).svg; let data = svg.split("data:image/png;base64,").nth(1).unwrap().split('"').next().unwrap(); - let png = image::load_from_memory(&vectorcraft_testkit::format::base64_decode(data).unwrap()).unwrap().to_rgba8(); + let png = craft_image_codecs::decode(&vectorcraft_testkit::format::base64_decode(data).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() + .to_rgba8(); let written = png.get_pixel(png.width() / 2, png.height() / 2).0; let want = Color::rgb(0.5, 0.15, 0.5).to_rgba8(1.0); let display = f.field(spread_scale(box_)).sample(Point::new(50.5, 50.5)).0.map(|v| (v * 255.0).round() as u8); diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index a4c6c1af40..9ccd36961b 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -1490,7 +1490,41 @@ fn gradient_mesh_from_images_with_junk_params() { use vectorcraft_geom::Affine; let img = image::RgbaImage::from_fn(5, 3, |x, y| image::Rgba([x as u8 * 50, y as u8 * 90, 7, if x == 2 { 0 } else { 255 }])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 params = [ json!({}), json!({"rows": 1, "cols": 1}), diff --git a/crates/engine/tests/group3_reference.rs b/crates/engine/tests/group3_reference.rs new file mode 100644 index 0000000000..e52c411ac6 --- /dev/null +++ b/crates/engine/tests/group3_reference.rs @@ -0,0 +1,239 @@ +//! vectorcraft-doc's Group 3 TIFF reader (`cmyk::group3_tiff_rgba`) reads CCITT data through +//! craft-stream-codecs; this keeps the reader it had on hayro-ccitt as the reference it matches. + +use vectorcraft_doc::cmyk::{Group3Error, group3_tiff_rgba}; +use vectorcraft_testkit::tiff::{Group3, group3}; + +/// What the reference refused a file for, as [`Group3Error`] says it. +#[derive(Debug, PartialEq)] +enum Refused { + TooLarge, + Damaged(craft_stream_codecs::CcittErrorKind), +} + +fn kind_of(e: hayro_ccitt::DecodeError) -> craft_stream_codecs::CcittErrorKind { + use craft_stream_codecs::CcittErrorKind as K; + match e { + hayro_ccitt::DecodeError::UnexpectedEof => K::UnexpectedEof, + hayro_ccitt::DecodeError::Overflow => K::Overflow, + _ => K::InvalidData, + } +} + +/// `group3_tiff_rgba` as it read before craft-stream-codecs. +fn reference(bytes: &[u8]) -> Option> { + use hayro_ccitt::{DecodeError, DecodeSettings, DecoderContext, EncodingMode}; + use tiff::tags::Tag; + if !(bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*")) || vectorcraft_doc::cmyk::oversized_tiff(bytes).is_some() { + return None; + } + let mut d = tiff::decoder::Decoder::new(std::io::Cursor::new(bytes)).ok()?; + let kind = d.colortype().ok()?; + let compression = d.find_tag_unsigned::(Tag::Compression).ok().flatten()?; + let (w, h) = d.dimensions().ok()?; + if kind != tiff::ColorType::Gray(1) || !matches!(compression, 2 | 3) || w == 0 || h == 0 { + return None; + } + // The level of a 0 bit (a white run): white when white is zero (0), black when black is zero (1). + let zero = match d.find_tag_unsigned::(Tag::PhotometricInterpretation).ok().flatten() { + Some(0) => u8::MAX, + Some(1) => 0, + _ => return None, + }; + if u64::from(w) * u64::from(h) > vectorcraft_doc::MAX_RASTER_ALLOC / 4 { + return Some(Err(Refused::TooLarge)); + } + let t4_options = d.find_tag_unsigned::(Tag::Unknown(292)).ok().flatten().unwrap_or(0); + let lsb_first = d.find_tag_unsigned::(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 + }; + // 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 { + let tw = d.find_tag_unsigned::(Tag::TileWidth).ok().flatten().filter(|&v| v > 0)?; + let th = d.find_tag_unsigned::(Tag::TileLength).ok().flatten().filter(|&v| v > 0)?; + (tw, th, Tag::TileOffsets, Tag::TileByteCounts) + } else { + let rows = d.find_tag_unsigned::(Tag::RowsPerStrip).ok().flatten().filter(|&v| v > 0).map_or(h, |r| r.min(h)); + (w, rows, Tag::StripOffsets, Tag::StripByteCounts) + }; + let damaged = |e: DecodeError| Some(Err(Refused::Damaged(kind_of(e)))); + // A tile is held to the allowance the image is held to; a strip is no larger than the image. + if u64::from(cw) * u64::from(ch) > vectorcraft_doc::MAX_RASTER_ALLOC / 4 { + return damaged(DecodeError::Overflow); + } + let offsets = d.find_tag_unsigned_vec::(offsets).ok().flatten().unwrap_or_default(); + let counts = d.find_tag_unsigned_vec::(counts).ok().flatten().unwrap_or_default(); + let across = w.div_ceil(cw); + let chunks = u64::from(across) * u64::from(h.div_ceil(ch)); + if chunks > offsets.len().min(counts.len()) as u64 { + return damaged(DecodeError::UnexpectedEof); + } + let mut gray = vec![zero; usize::try_from(u64::from(w) * u64::from(h)).ok()?]; + let mut budget = bytes.len(); + for (i, (&offset, &count)) in (0..chunks).zip(offsets.iter().zip(&counts)) { + let (x0, y0) = (u32::try_from(i % u64::from(across)).ok()? * cw, u32::try_from(i / u64::from(across)).ok()? * ch); + let Some(start) = usize::try_from(offset).ok().filter(|&s| s <= bytes.len()) else { + return damaged(DecodeError::UnexpectedEof); + }; + let len = usize::try_from(count).unwrap_or(usize::MAX).min(bytes.len() - start).min(budget); + 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, + end_of_line: compression == 3, + rows_are_byte_aligned: compression == 2, + encoding, + invert_black: false, + }; + 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)) { + 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 { + return damaged(DecodeError::UnexpectedEof); + } + } + 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); + } + } + 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; + } +} + +fn read(bytes: &[u8]) -> Option> { + group3_tiff_rgba(bytes).map(|r| { + r.map_err(|e| match e { + Group3Error::TooLarge { .. } => Refused::TooLarge, + Group3Error::Damaged(k) => Refused::Damaged(k), + }) + }) +} + +/// Group 3 TIFFs of every kind the reader takes: Compression 2 and 3, one- and two-dimensional +/// rows, fill bits, each byte's lowest bit first, white or black as zero, strips of a few rows +/// or one, tiles, with and without six EOLs at the end; their rows of many patterns and widths. +fn samples() -> Vec> { + let mut files = Vec::new(); + for (width, height) in [(1usize, 1usize), (7, 3), (40, 6), (64, 17), (131, 9)] { + let rows: Vec> = (0..height).map(|y| (0..width).map(|x| (x * (y + 1) / 3 + y + x / 7) % 4 < 2).collect()).collect(); + for (compression, t4_options) in [(2u16, 0u32), (3, 0), (3, 1), (3, 4), (3, 5)] { + for (photometric, fill_order) in [(0u16, 1u16), (1, 2)] { + for (rows_per_strip, tile) in [(1u32, None), (2, None), (64, None), (64, Some((16u32, 16u32)))] { + if tile.is_some() && compression == 2 { + continue; + } + let rtc = compression == 3 && rows_per_strip != 2; + let g = Group3 { rows: &rows, compression, t4_options, photometric, fill_order, rows_per_strip, tile, rtc }; + files.push(group3(&g)); + } + } + } + } + files +} + +/// Every sample, and every sample cut short or with bytes changed, reads to the same pixels or is +/// refused for the same reason as with the reference; strips or tiles wider than +/// `craft_stream_codecs::MAX_CCITT_COLUMNS` (2^20) are refused as an overflow where the reference +/// gave another reason. +#[test] +fn group3_tiffs_read_as_the_hayro_reader_read_them() { + let files = samples(); + use craft_stream_codecs::CcittErrorKind::Overflow; + let (mut same, mut refused, mut checked, mut wider) = (0, 0, 0, 0); + for (n, file) in files.iter().enumerate() { + let theirs = reference(file); + assert!(theirs.as_ref().is_some_and(|r| r.is_ok()), "sample {n} reads"); + let mut variants = vec![file.clone()]; + for cut in [file.len() - 1, file.len() - 3, file.len() * 3 / 4, file.len() / 2] { + variants.push(file[..cut].to_vec()); + } + for k in 0..24usize { + let mut v = file.clone(); + let at = (k * 2_654_435_761 + n * 97) % v.len(); + v[at] ^= 1 << (k % 8); + variants.push(v); + } + for v in variants { + let (ours, theirs) = (read(&v), reference(&v)); + match (&ours, &theirs) { + (Some(Ok(a)), Some(Ok(b))) => { + assert!(a == b, "sample {n}: other pixels"); + same += 1; + } + _ => { + let (ours, theirs) = (ours.map(|r| r.err()), theirs.map(|r| r.err())); + // A strip or tile wider than craft-stream-codecs reads (MAX_CCITT_COLUMNS) + // is refused as an overflow before decoding; hayro-ccitt ran out of data or + // found a bad code in it instead. + let wide = matches!((&ours, &theirs), (Some(Some(Refused::Damaged(Overflow))), Some(Some(Refused::Damaged(_))))); + assert!(ours == theirs || wide, "sample {n}: {ours:?}, reference {theirs:?}"); + wider += usize::from(ours != theirs); + refused += 1; + } + } + checked += 1; + } + } + assert!( + same > files.len() && refused > files.len() && wider < refused / 10, + "{same} read, {refused} refused ({wider} as wider than read) of {checked}" + ); +} diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 5614aef56a..6630f91a47 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -37,7 +37,41 @@ fn config() -> ProptestConfig { fn affinity_preview_sample() -> Vec { let im = image::RgbaImage::from_pixel(2, 1, image::Rgba([220, 40, 60, 255])); let mut png = Vec::new(); - im.write_to(&mut std::io::Cursor::new(&mut png), 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| png.extend_from_slice(&__b)) + } + .unwrap(); let mut b = vec![0; 72]; b[..4].copy_from_slice(vectorcraft_affinity::MAGIC); b[4..6].copy_from_slice(&12u16.to_le_bytes()); @@ -1759,13 +1793,46 @@ fn raster_samples() -> Vec<(&'static str, Vec)> { let img = image::RgbImage::from_pixel(5, 3, image::Rgb([200, 40, 10])); let mut out = vec![]; for (name, f) in [ - ("a.png", image::ImageFormat::Png), - ("a.jpg", image::ImageFormat::Jpeg), - ("a.tif", image::ImageFormat::Tiff), - ("a.bmp", image::ImageFormat::Bmp), + ("a.png", craft_image_codecs::Format::Png), + ("a.jpg", craft_image_codecs::Format::Jpeg), + ("a.tif", craft_image_codecs::Format::Tiff), + ("a.bmp", craft_image_codecs::Format::Bmp), ] { let mut b = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut b), f).unwrap(); + { + let __dyn: image::DynamicImage = img.clone().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, f, &craft_image_codecs::EncodeOptions::default()).map(|__b| b.extend_from_slice(&__b)) + } + .unwrap(); out.push((name, b)); } out[0].1 = vectorcraft_engine::cmd::fileio::ppi::with_png_resolution(&out[0].1, (300.0, 150.0)); @@ -1794,14 +1861,25 @@ fn raster_samples() -> Vec<(&'static str, Vec)> { psb.extend((0..8u8).flat_map(|v| [0xfe, v * 30])); out.push(("a.psb", psb)); // JPEG XL: an 8-bit RGBA codestream, and a 16-bit gray one in the container. - use zune_core::{bit_depth::BitDepth, colorspace::ColorSpace, options::EncoderOptions}; - let jxl = |space, depth, samples: &[u8]| { - let mut b = vec![]; - zune_jpegxl::JxlSimpleEncoder::new(samples, EncoderOptions::new(5, 3, space, depth)).encode(&mut b).unwrap(); - b - }; - out.push(("a.jxl", jxl(ColorSpace::RGBA, BitDepth::Eight, &(0..60).map(|i| (i * 17) as u8).collect::>()))); - let gray = jxl(ColorSpace::Luma, BitDepth::Sixteen, &(0..30).map(|i| (i * 41) as u8).collect::>()); + use craft_jxl::{EncodeOptions, ImageRef, Layout, Samples}; + let opts = EncodeOptions { lossless: true, ..EncodeOptions::default() }; + let rgba: Vec = (0..60).map(|i| (i * 17) as u8).collect(); + out.push(( + "a.jxl", + craft_jxl::encode( + &ImageRef { width: 5, height: 3, layout: Layout::Rgba, samples: Samples::U8(&rgba) }, + opts, + &craft_jxl::Metadata::default(), + ) + .unwrap(), + )); + let gray_u16: Vec = (0..15).map(|i| u16::from_ne_bytes([(i * 2 * 41) as u8, ((i * 2 + 1) * 41) as u8])).collect(); + let gray = craft_jxl::encode( + &ImageRef { width: 5, height: 3, layout: Layout::Gray, samples: Samples::U16(&gray_u16) }, + opts, + &craft_jxl::Metadata::default(), + ) + .unwrap(); let mut boxed = vec![0, 0, 0, 0x0c, b'J', b'X', b'L', b' ', 0x0d, 0x0a, 0x87, 0x0a]; boxed.extend(20u32.to_be_bytes()); boxed.extend(b"ftypjxl \0\0\0\0jxl "); @@ -2258,7 +2336,41 @@ proptest! { /// and a 32-bit one with an extension area. fn targa_samples() -> Vec<(&'static str, Vec)> { let mut rle = vec![]; - image::RgbImage::from_pixel(5, 3, image::Rgb([200, 40, 10])).write_to(&mut std::io::Cursor::new(&mut rle), image::ImageFormat::Tga).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbImage::from_pixel(5, 3, image::Rgb([200, 40, 10]))).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::Tga, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| rle.extend_from_slice(&__b)) + } + .unwrap(); let mut s = rich_session(); let r = s.execute("document.export", &json!({"format": "tga", "depth": 16, "ppi": 2})).unwrap(); let export = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); @@ -2947,7 +3059,24 @@ fn the_ccitt_images_fixture_reads_both_images() { let mut found = vec![]; d.walk(|n| { if let vectorcraft_doc::NodeKind::Image(im) = &n.kind { - 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(); found.push(px.pixels().map(shade).collect::()); } }); diff --git a/crates/engine/tests/it/affinity_features.rs b/crates/engine/tests/it/affinity_features.rs index 6a0338ee17..98fdbe6b23 100644 --- a/crates/engine/tests/it/affinity_features.rs +++ b/crates/engine/tests/it/affinity_features.rs @@ -670,7 +670,24 @@ fn cmyk_pixel_layers_show_through_the_documents_cmyk_profile() { let loaded = open("photo.af", &cmyk_layer(false, Some(&icc))); let blob = photo(&loaded.doc); assert!(!blob.is_cmyk()); - 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(); let profile = IccProfile::from_bytes(None, &icc).unwrap(); let srgb = cms::icc::builtin_rgb(cms::SRGB).unwrap(); let want = profile.to_rgb_of(&srgb, &[1.0, 0.0, 0.0, 0.0], Intent::RelativeColorimetric, true).unwrap().map(|v| (v * 255.0).round() as i32); @@ -691,7 +708,29 @@ fn cmyk_pixel_layers_without_a_profile_keep_their_inks_or_use_the_working_profil let loaded = open("photo.af", &cmyk_layer(true, None)); let blob = photo(&loaded.doc); assert!(!blob.is_cmyk()); - assert_eq!(image::load_from_memory(&blob.bytes).unwrap().to_rgba8().get_pixel(8, 8).0[3], 0); + 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() + .get_pixel(8, 8) + .0[3], + 0 + ); assert!(loaded.warnings.iter().any(|w| w.contains("CMYK pixel layers with transparency")), "{:?}", loaded.warnings); } diff --git a/crates/engine/tests/it/affinity_local.rs b/crates/engine/tests/it/affinity_local.rs index c0ae237e99..54df4a4612 100644 --- a/crates/engine/tests/it/affinity_local.rs +++ b/crates/engine/tests/it/affinity_local.rs @@ -45,7 +45,24 @@ fn local_affinity_documents_render_like_their_thumbnails() { eprintln!(" {w}"); } let Ok(preview) = vectorcraft_affinity::preview(&bytes) else { continue }; - let thumb = image::load_from_memory(preview.png).unwrap().to_rgba8(); + let thumb = craft_image_codecs::decode(preview.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(); let union = d.artboards.iter().map(|a| a.rect).reduce(|a, b| a.union(b)).unwrap(); let scale = f64::from(thumb.width()) / union.width(); let mut total = 0.0; diff --git a/crates/engine/tests/open_relative_path.rs b/crates/engine/tests/open_relative_path.rs index f0c63a0fb9..a9cccf5bb9 100644 --- a/crates/engine/tests/open_relative_path.rs +++ b/crates/engine/tests/open_relative_path.rs @@ -12,7 +12,41 @@ fn a_relative_path_finds_relative_links() { let dir = std::env::temp_dir().join(format!("vectorcraft-relative-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let mut png = Vec::new(); - image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 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([255, 0, 0, 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(); std::fs::write(dir.join("ext.png"), &png).unwrap(); let svg = r#""#; std::fs::write(dir.join("linked.svg"), svg).unwrap(); diff --git a/crates/engine/tests/plugin_export.rs b/crates/engine/tests/plugin_export.rs index 94618ee84d..cc39566875 100644 --- a/crates/engine/tests/plugin_export.rs +++ b/crates/engine/tests/plugin_export.rs @@ -83,7 +83,41 @@ fn the_exporter_is_given_the_native_file_s_json() { image::Rgba([r, g, b, 255]) }); let mut png = vec![]; - noise.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = noise.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(); assert!(png.len() >= vectorcraft_format::INLINE_MAX, "{} bytes", png.len()); s.execute("file.place", &json!({"name": "noise.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); diff --git a/crates/engine/tests/plugin_import.rs b/crates/engine/tests/plugin_import.rs index f091062308..9bf9b87f0d 100644 --- a/crates/engine/tests/plugin_import.rs +++ b/crates/engine/tests/plugin_import.rs @@ -393,7 +393,41 @@ fn a_built_in_file_past_the_input_limit_still_opens() { echo(&mut s, "test.largepng", r#"["tsp"]"#); let path = dir.join("big.tsp"); let mut png = std::io::Cursor::new(vec![]); - image::RgbaImage::new(2, 2).write_to(&mut png, image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::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::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|__b| png.get_mut().extend_from_slice(&__b)) + } + .unwrap(); std::fs::write(&path, png.get_ref()).unwrap(); std::fs::OpenOptions::new().write(true).open(&path).unwrap().set_len(vectorcraft_plugins::import::MAX_INPUT_BYTES as u64 + 1).unwrap(); let e = s.execute("document.open", &json!({"path": path_of(&path), "importer": "plugin.test.largepng"})).unwrap_err(); diff --git a/crates/eps/Cargo.toml b/crates/eps/Cargo.toml index bd173588aa..9efae37385 100644 --- a/crates/eps/Cargo.toml +++ b/crates/eps/Cargo.toml @@ -30,10 +30,11 @@ craft-pdf = { workspace = true } vectorcraft-render = { workspace = true } kurbo = { workspace = true } image = { workspace = true } +craft-image-codecs = { workspace = true } flate2 = { workspace = true } ruzstd = { workspace = true } # Images read through `CCITTFaxDecode`. -hayro-ccitt = { workspace = true } +craft-stream-codecs = { workspace = true } # Live effects' params, as the art styles that name them give them. serde_json = { workspace = true } # Substring search for PostScript `search`. diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index baf1380e50..f8e39a4048 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -800,7 +800,41 @@ fn unsupported() -> Document { doc.insert(Some(layer), usize::MAX, ring).unwrap(); let mut png = vec![]; let img = image::RgbaImage::from_raw(2, 1, vec![255, 0, 0, 255, 0, 0, 255, 255]).unwrap(); - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 blob = ImageBlob::new("image/png", png); let key = blob.content_key(); doc.images.insert(key.clone(), blob); @@ -1394,7 +1428,41 @@ fn an_adjusted_image_in_a_symbol_is_written_in_its_adjusted_color() { let mut doc = Document::new(200.0, 100.0); let layer = doc.layers[0].id; let mut png = vec![]; - image::RgbaImage::from_pixel(2, 2, image::Rgba([0, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(2, 2, image::Rgba([0, 0, 0, 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 blob = ImageBlob::new("image/png", png); let key = blob.content_key(); doc.images.insert(key.clone(), blob); @@ -1554,7 +1622,41 @@ fn effects_on_a_fill_are_reported_left_out() { #[test] fn images_of_more_pixels_than_the_reader_reads_are_mid_gray() { let mut png = vec![]; - image::GrayImage::new(6000, 6000).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::GrayImage::new(6000, 6000)).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 doc = Document::new(200.0, 100.0); let layer = doc.layers[0].id; let im = image_node(&mut doc, ImageBlob::png(png), (10, 10), Affine::IDENTITY, None); @@ -3156,7 +3258,41 @@ fn a_pattern_swatchs_own_placement_is_reported_left_out() { /// `img` as PNG bytes. fn png_of(img: image::DynamicImage) -> Vec { let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), 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| png.extend_from_slice(&__b)) + } + .unwrap(); png } @@ -3233,7 +3369,28 @@ fn pictures(doc: &Document, nodes: &[Arc], path: &str, out: &mut Vec format!("cmyk {:?}", inks.data), - _ => format!("rgba {:?}", image::load_from_memory(&blob.bytes).unwrap().to_rgba8().into_raw()), + _ => format!( + "rgba {:?}", + 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() + .into_raw() + ), }; let xf: Vec = im.xf.as_coeffs().iter().map(|v| r3(*v)).collect(); let link = im.link.as_ref().map(|l| (l.path.clone(), l.relative.clone())); @@ -3516,7 +3673,24 @@ fn a_smaller_preview_takes_no_color_from_see_through_pixels() { let back = read_back(&doc); let NodeKind::Image(im) = &back.layers[0].children().unwrap()[0].kind else { panic!("not an image") }; assert_eq!(im.width, 256); - let px = image::load_from_memory(&back.image_blob(im).unwrap().bytes).unwrap().to_rgba8(); + let px = craft_image_codecs::decode(&back.image_blob(im).unwrap().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!(px.pixels().all(|p| p.0[0] == 0), "{:?}", px.pixels().take(4).collect::>()); assert!(px.pixels().filter(|p| p.0[3] > 0).count() > 400); } @@ -5032,7 +5206,43 @@ fn beside(doc: &mut Document, kind: Beside, x: f64, state: (f32, BlendMode, bool Beside::Image => { let mut png = vec![]; let img = image::RgbaImage::from_raw(1, 1, vec![255, 0, 0, 255]).unwrap(); - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 blob = ImageBlob::new("image/png", png); let key = blob.content_key(); doc.images.insert(key.clone(), blob); diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index c181fcb9d5..a5e222b12f 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -551,15 +551,20 @@ impl<'a> Reader<'a> { rgba.extend_from_slice(&[px[0], px[1], px[2], a]); } } - let Some(img) = image::RgbaImage::from_raw(w as u32, h as u32, rgba) else { + let Ok(img) = craft_image_codecs::Image::from_raw( + w as u32, + h as u32, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + rgba, + ) else { self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); }; - let mut png = vec![]; - if img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_err() { + let Ok(png) = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) else { self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); - } + }; self.add_raster(ImageBlob::new("image/png", png), None, &m, (w as u32, h as u32), None) } @@ -584,12 +589,13 @@ impl<'a> Reader<'a> { gray.push(v); } } - let mut png = vec![]; - let written = image::GrayImage::from_raw(w, h, gray).map(|img| img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)); - if !matches!(written, Some(Ok(()))) { + let written = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, gray) + .ok() + .and_then(|img| craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()); + let Some(png) = written else { self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); - } + }; self.add_raster(ImageBlob::new("image/png", png), alpha, m, (w, h), Some(paint)) } @@ -677,15 +683,16 @@ impl<'a> Reader<'a> { let blob = if cmyk { Inks::new(ow, oh, pixels).and_then(|i| ImageBlob::cmyk_tiff(&i)) } else { - use image::ImageEncoder as _; - let colour = match (s.channels, inline && opacity.is_some()) { - (1, false) => image::ExtendedColorType::L8, - (1, true) => image::ExtendedColorType::La8, - (_, false) => image::ExtendedColorType::Rgb8, - (_, true) => image::ExtendedColorType::Rgba8, + let layout = match (s.channels, inline && opacity.is_some()) { + (1, false) => craft_image_codecs::ChannelLayout::Gray, + (1, true) => craft_image_codecs::ChannelLayout::GrayA, + (_, false) => craft_image_codecs::ChannelLayout::Rgb, + (_, true) => craft_image_codecs::ChannelLayout::Rgba, }; - let mut png = vec![]; - image::codecs::png::PngEncoder::new(&mut png).write_image(&pixels, ow, oh, colour).ok().map(|()| ImageBlob::new("image/png", png)) + craft_image_codecs::Image::from_raw(ow, oh, layout, craft_image_codecs::SampleType::U8, pixels) + .ok() + .and_then(|img| craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()) + .map(|png| ImageBlob::new("image/png", png)) }; // One that can't be encoded is left to the page's art, as one past the hard limits. let Some(blob) = blob else { @@ -773,8 +780,10 @@ impl<'a> Reader<'a> { if alpha.iter().all(|v| *v == 255) { return None; } - let mut png = Vec::new(); - image::GrayImage::from_raw(w, h, alpha.to_vec())?.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?; + let raw = + craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, alpha.to_vec()) + .ok()?; + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); self.doc.images.entry(key.clone()).or_insert(blob); @@ -1031,8 +1040,9 @@ pub(super) fn preview_png(data: &[u8]) -> Option<(Vec, u32, u32)> { rgba.extend_from_slice(&[straight(r), straight(g), straight(b), a]); } } - let mut png = vec![]; - image::RgbaImage::from_raw(width, height, rgba)?.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?; + let raw = + craft_image_codecs::Image::from_raw(width, height, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).ok()?; + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; Some((png, width, height)) } diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index f133a9ee03..e95e94c3f9 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -2676,7 +2676,27 @@ fn pixels(doc: &Document) -> (image::RgbaImage, kurbo::Affine) { let a = art(doc); let NodeKind::Image(im) = &a[0].kind else { panic!("{:?}", a[0].kind) }; let blob = doc.images.get(&im.key).unwrap(); - (image::load_from_memory(&blob.bytes).unwrap().to_rgba8(), im.xf) + ( + 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(), + im.xf, + ) } /// A 1-bit image's row holds each pixel's channels in turn, one bit each, padded to whole bytes; @@ -3073,7 +3093,24 @@ fn cmyk_images_keep_their_ink_amounts() { assert!(m.clip); let NodeKind::Image(mi) = &m.art.kind else { panic!("{:?}", m.art.kind) }; assert_eq!((mi.width, mi.height, mi.xf), (3, 1, im.xf), "the mask covers the image"); - let gray = image::load_from_memory(&doc.images[&mi.key].bytes).unwrap().to_luma8(); + let gray = craft_image_codecs::decode(&doc.images[&mi.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(); assert_eq!(gray.into_raw(), [255, 128, 0]); // An alpha channel that hides nothing adds no mask. let data = [&inks[..], &[255; 3]].concat(); diff --git a/crates/eps/src/import/data.rs b/crates/eps/src/import/data.rs index 53848af89d..ade850a21e 100644 --- a/crates/eps/src/import/data.rs +++ b/crates/eps/src/import/data.rs @@ -5,7 +5,6 @@ use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; -use hayro_ccitt::{DecodeSettings, Decoder, DecoderContext, EncodingMode}; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::cmyk::{Inks, jpeg_components}; use vectorcraft_doc::{ImageBlob, ImageObject, Node, NodeId, NodeKind, OpacityMask}; diff --git a/crates/eps/src/import/data/filters.rs b/crates/eps/src/import/data/filters.rs index 79dce67ea0..3dc9662bdf 100644 --- a/crates/eps/src/import/data/filters.rs +++ b/crates/eps/src/import/data/filters.rs @@ -1,8 +1,6 @@ use super::ops::MAX_DATA; -use super::{ - DecodeSettings, Decoder, DecoderContext, DictRef, EncodingMode, ImageBlob, Key, Obj, PsError, Rc, RefCell, Res, find, hex_decode, - jpeg_components, ps, ps_err, -}; +use super::{DictRef, ImageBlob, Key, Obj, PsError, Rc, RefCell, Res, find, hex_decode, jpeg_components, ps, ps_err}; +use craft_stream_codecs::CcittParams; /// A file object: the program itself, or data a filter decoded. #[derive(Debug)] @@ -163,36 +161,29 @@ fn dct(raw: &[u8]) -> Res<(Vec, usize, u8)> { /// `Rows`; without it they end after `Rows` rows, or at the end of the data when `Rows` is 0. /// Damaged data ends the rows: those decoded before it are kept, and damage in the first row is an /// `ioerror`. Rows that would take more than `MAX_DATA` bytes are refused. -fn fax(raw: &[u8], settings: DecodeSettings) -> Res<(Vec, usize)> { +fn fax(raw: &[u8], settings: CcittParams) -> Res<(Vec, usize)> { let row = (settings.columns as usize).div_ceil(8).max(1); let most = u32::try_from(MAX_DATA / row).unwrap_or(u32::MAX); - if !settings.end_of_block && settings.rows > most { + if !settings.end_of_block && settings.rows > i64::from(most) { return Err(PsError::Limit("decoded data is too large")); } // Without a row count that ends the data, a row past `most` shows that the data is too large. - let rows = if settings.end_of_block || settings.rows == 0 { most.saturating_add(1) } else { settings.rows }; + let rows = if settings.end_of_block || settings.rows == 0 { most.saturating_add(1) } else { settings.rows as u32 }; + // With `EndOfBlock` the rows end at the end-of-block code, whatever `Rows` says. + let params = if settings.end_of_block { CcittParams { rows: 0, ..settings } } else { settings }; // The decoder reads the RTC of Group 3 two-dimensional data as rows: it gets the data before it. - let rtc = match settings.encoding { - EncodingMode::Group3_2D { .. } if settings.end_of_block => rtc(raw), - _ => None, - }; + let rtc = if settings.k > 0 && settings.end_of_block { rtc(raw) } else { None }; let data = rtc.and_then(|(cut, _)| raw.get(..cut)).unwrap_or(raw); - let mut out = FaxRows::default(); - let read = hayro_ccitt::decode(data, &mut out, &mut DecoderContext::new(DecodeSettings { rows, ..settings })); - if out.rows > most { + let out = craft_stream_codecs::decode_ccitt_raw(data, ¶ms, rows).map_err(|_| PsError::Limit("decoded data is too large"))?; + if out.rows_decoded > most { return Err(PsError::Limit("decoded data is too large")); } - let used = match read { - Ok(used) => used, - Err(_) if out.rows > 0 => { - out.data.truncate(out.rows as usize * row); - // The whole rows decoded again, for how many bytes they took. - let used = hayro_ccitt::decode(data, &mut Dropped, &mut DecoderContext::new(DecodeSettings { rows: out.rows, ..settings })); - used.unwrap_or(data.len()) - } - Err(_) => return io("CCITTFaxDecode"), - }; - Ok((out.data, rtc.map_or(used, |(_, end)| end))) + // Damaged data ends the rows: those decoded before it are kept, and damage in the first row + // is an `ioerror`. + if out.error.is_some() && out.rows_decoded == 0 { + return io("CCITTFaxDecode"); + } + Ok((out.data, rtc.map_or(out.bytes_consumed, |(_, end)| end))) } /// The RTC that ends Group 3 two-dimensional data (six EOLs, each followed by a 1 tag bit, ITU-T @@ -225,50 +216,6 @@ fn rtc(raw: &[u8]) -> Option<(usize, usize)> { None } -/// Rows of 1-bit samples from a CCITT decoder, each padded to a whole byte: 1 is white, or black -/// with `BlackIs1`. -#[derive(Default)] -struct FaxRows { - data: Vec, - /// Samples in the row being decoded. - x: u32, - /// Whole rows decoded. - rows: u32, -} - -impl Decoder for FaxRows { - fn push_pixel(&mut self, white: bool) { - if self.x.is_multiple_of(8) { - self.data.push(0); - } - if white && let Some(b) = self.data.last_mut() { - *b |= 0x80 >> (self.x % 8); - } - self.x = self.x.saturating_add(1); - } - - fn push_pixel_chunk(&mut self, white: bool, chunk_count: u32) { - self.data.extend(std::iter::repeat_n(if white { 0xff } else { 0 }, chunk_count as usize)); - self.x = self.x.saturating_add(chunk_count.saturating_mul(8)); - } - - fn next_line(&mut self) { - self.x = 0; - self.rows = self.rows.saturating_add(1); - } -} - -/// A CCITT decoder that drops what it decodes. -struct Dropped; - -impl Decoder for Dropped { - fn push_pixel(&mut self, _: bool) {} - - fn push_pixel_chunk(&mut self, _: bool, _: u32) {} - - fn next_line(&mut self) {} -} - /// A decoding filter and its parameters. #[derive(Clone, Debug)] pub(crate) struct Filter { @@ -278,7 +225,7 @@ pub(crate) struct Filter { /// `FlateDecode`'s and `LZWDecode`'s `Predictor`: what it undoes. pub(super) predictor: Option, /// `CCITTFaxDecode`'s parameters. - pub(super) fax: Option, + pub(super) fax: Option, } /// A `Predictor` (2: TIFF, 10–15: PNG) with its `Colors`, `BitsPerComponent` and `Columns`. @@ -407,7 +354,7 @@ fn paeth(a: u8, b: u8, c: u8) -> u8 { /// §7.4.6): `K` (below 0 Group 4, 0 Group 3 one-dimensional, above 0 Group 3 mixed), `Columns`, /// `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`, with their defaults where /// `d` leaves them out. `Columns` outside 1 to 65,535 and `Rows` below 0 are a `rangecheck`. -pub(super) fn fax_settings(d: Option<&DictRef>) -> Res { +pub(super) fn fax_settings(d: Option<&DictRef>) -> Res { let get = |k: &str| d.and_then(|d| d.borrow().get(&Key::name(k)).cloned()); let num = |k: &str, default: f64| get(k).and_then(|o| o.as_num()).unwrap_or(default); let flag = |k: &str, default: bool| match get(k) { @@ -418,21 +365,23 @@ pub(super) fn fax_settings(d: Option<&DictRef>) -> Res { if !k.is_finite() || !(1.0..=65_535.0).contains(&columns) || !(0.0..=f64::from(u32::MAX)).contains(&rows) { return ps_err("rangecheck", "CCITTFaxDecode"); } - let encoding = if k < 0.0 { - EncodingMode::Group4 + // Group 4 below 0, one-dimensional Group 3 at 0, mixed Group 3 above (the row's tag bit says + // how it is coded, so any positive `K` reads the same); `as` saturates. + let k = if k < 0.0 { + -1 } else if k == 0.0 { - EncodingMode::Group3_1D + 0 } else { - EncodingMode::Group3_2D { k: k.min(f64::from(u32::MAX)) as u32 } + (k as i64).max(1) }; - Ok(DecodeSettings { - columns: columns as u32, - rows: rows as u32, + Ok(CcittParams { + k, + columns: columns as i64, + rows: rows as i64, end_of_block: flag("EndOfBlock", true), end_of_line: flag("EndOfLine", false), - rows_are_byte_aligned: flag("EncodedByteAlign", false), - encoding, - invert_black: flag("BlackIs1", false), + encoded_byte_align: flag("EncodedByteAlign", false), + black_is_1: flag("BlackIs1", false), }) } diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index 04e5431d30..fef595a924 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -893,12 +893,15 @@ impl Interp<'_> { let mask = self.alpha_mask(&alpha, img.w, img.h, xf); return self.add_image(blob, img.w, img.h, xf, mask); } - let Some(rgba) = image::RgbaImage::from_raw(img.w, img.h, img.rgba) else { return Ok(()) }; - let mut png = vec![]; - if rgba.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_err() { + let Ok(rgba) = + craft_image_codecs::Image::from_raw(img.w, img.h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, img.rgba) + else { + return Ok(()); + }; + let Ok(png) = craft_image_codecs::encode(&rgba, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) else { self.out.warn("an image that couldn't be read was left out"); return Ok(()); - } + }; self.add_image(ImageBlob::new("image/png", png), img.w, img.h, xf, None) } @@ -919,8 +922,10 @@ impl Interp<'_> { if alpha.iter().all(|v| *v == 255) { return None; } - let mut png = Vec::new(); - image::GrayImage::from_raw(w, h, alpha.to_vec())?.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?; + let raw = + craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, alpha.to_vec()) + .ok()?; + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); self.out.doc.images.entry(key.clone()).or_insert(blob); diff --git a/crates/eps/src/import/native.rs b/crates/eps/src/import/native.rs index 3a6347fea9..ac57122bd4 100644 --- a/crates/eps/src/import/native.rs +++ b/crates/eps/src/import/native.rs @@ -168,11 +168,15 @@ mod tests { } let rect = vector.artboards[0].rect; let source = vectorcraft_render::Renderer::new().render_region(&vector, rect, 1.6, true); - let mut png = Vec::new(); - image::RgbaImage::from_raw(source.width, source.height, source.to_straight()) - .unwrap() - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + let raw = craft_image_codecs::Image::from_raw( + source.width, + source.height, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + source.to_straight(), + ) + .unwrap(); + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); let mut page = Document::new(1000.0, 500.0); @@ -236,11 +240,15 @@ mod tests { vector.insert(Some(layer), usize::MAX, n).unwrap(); let rect = vector.artboards[0].rect; let source = vectorcraft_render::Renderer::new().render_region(&vector, rect, 1.0, true); - let mut png = Vec::new(); - image::RgbaImage::from_raw(source.width, source.height, source.to_straight()) - .unwrap() - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + let raw = craft_image_codecs::Image::from_raw( + source.width, + source.height, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + source.to_straight(), + ) + .unwrap(); + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); let mut page = Document::new(width, height); diff --git a/crates/eps/src/import/preview.rs b/crates/eps/src/import/preview.rs index d4b4efb131..74e977e93a 100644 --- a/crates/eps/src/import/preview.rs +++ b/crates/eps/src/import/preview.rs @@ -32,12 +32,11 @@ pub(super) fn preview(bytes: &[u8], ps: &[u8], frame: Rect) -> Option { const MAX_PREVIEW_PIXELS: u64 = 1 << 26; fn tiff_rgba(tiff: &[u8]) -> Option { - let size = image::ImageReader::with_format(std::io::Cursor::new(tiff), image::ImageFormat::Tiff).into_dimensions(); - if size.is_ok_and(|(w, h)| u64::from(w) * u64::from(h) > MAX_PREVIEW_PIXELS) { - return None; - } - match image::load_from_memory_with_format(tiff, image::ImageFormat::Tiff) { - Ok(img) => Some(img.to_rgba8()), + let mut opts = craft_image_codecs::DecodeOptions::default(); + opts.limits.max_pixels = MAX_PREVIEW_PIXELS; + match craft_image_codecs::decode_as_with(craft_image_codecs::Format::Tiff, tiff, &opts) { + Ok(img) => image::RgbaImage::from_raw(img.width(), img.height(), img.to_rgba8()), + Err(craft_image_codecs::CodecError::LimitExceeded(_)) => None, Err(_) => crate::tiff::palette_rgba(tiff), } } @@ -48,8 +47,9 @@ fn image_doc(img: image::RgbaImage, frame: Rect) -> Option { if w == 0 || h == 0 { return None; } - let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?; + let raw = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, img.into_raw()) + .ok()?; + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; let mut doc = Document::new(frame.width(), frame.height()); let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); diff --git a/crates/eps/src/import/tests.rs b/crates/eps/src/import/tests.rs index 4709a3c5bf..5fc5d910a4 100644 --- a/crates/eps/src/import/tests.rs +++ b/crates/eps/src/import/tests.rs @@ -598,7 +598,24 @@ fn images_and_image_masks() { let NodeKind::Image(im) = &o[0].kind else { panic!("{:?} {:?}", o, r.warnings) }; assert_eq!((im.width, im.height), (2, 2)); assert!(near(bounds(&o[0]), Rect::new(10.0, 70.0, 30.0, 90.0)), "{:?}", bounds(&o[0])); - let png = image::load_from_memory(&r.document.images[&im.key].bytes).unwrap().to_rgba8(); + let png = craft_image_codecs::decode(&r.document.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!(png.get_pixel(0, 0).0, [255, 0, 0, 255]); assert_eq!(png.get_pixel(1, 1).0, [255, 255, 255, 255]); // The dictionary form through ASCII85 and run-length filters, grey with a decode array. @@ -608,12 +625,46 @@ fn images_and_image_masks() { << /ImageType 1 /Width 2 /Height 1 /BitsPerComponent 8 /Decode [1 0] /ImageMatrix [2 0 0 1 0 0] /DataSource src >> image\n{rl}" )); let NodeKind::Image(im) = &objects(&r.document)[0].kind else { panic!("{:?}", r.warnings) }; - let png = image::load_from_memory(&r.document.images[&im.key].bytes).unwrap().to_rgba8(); + let png = craft_image_codecs::decode(&r.document.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!((png.get_pixel(0, 0).0, png.get_pixel(1, 0).0), ([255, 255, 255, 255], [0, 0, 0, 255])); // An image mask paints the current colour where its bits say. let r = read("1 0 0 setrgbcolor 8 1 true [8 0 0 1 0 0] imagemask"); let NodeKind::Image(im) = &objects(&r.document)[0].kind else { panic!() }; - let png = image::load_from_memory(&r.document.images[&im.key].bytes).unwrap().to_rgba8(); + let png = craft_image_codecs::decode(&r.document.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!((png.get_pixel(0, 0).0, png.get_pixel(7, 0).0), ([255, 0, 0, 255], [255, 0, 0, 0])); } @@ -784,7 +835,41 @@ fn rich_doc() -> Document { *p = image::Rgba(if x < 4 { [0, 0, 255, 255] } else { [255, 200, 0, 255] }); } let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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(); d.images.insert("pic".into(), ImageBlob::new("image/png", png)); let im = ImageObject { key: "pic".into(), @@ -1177,7 +1262,7 @@ fn run_looking(body: &str, look: fn(&Interp) -> T) -> T { /// (`search_in_a_loop_runs_out_of_the_budget` searches about 3 GB, 14 s on a fast desktop), so the /// limit here only catches a program that never stops. pub(super) fn runs_out_of_budget(body: &str) { - let r = read_within(&format!("0 0 10 10 rectfill {body}"), 120); + let r = read_within(&format!("0 0 10 10 rectfill {body}"), NEVER_ENDS); assert_eq!(objects(&r.document).len(), 1, "{body}: {:?}", r.warnings); assert!(r.warnings.iter().any(|w| w.contains("the program runs too long")), "{body}: {:?}", r.warnings); } @@ -1415,7 +1500,24 @@ fn a_palette_preview_with_alpha_is_placed() { let NodeKind::Image(im) = &o[0].kind else { panic!("{:?}", o[0].kind) }; assert_eq!((im.width, im.height), (20, 10)); assert!(near(bounds(&o[0]), Rect::new(0.0, 0.0, 100.0, 100.0))); - let png = image::load_from_memory(&r.document.images[&im.key].bytes).unwrap().to_rgba8(); + let png = craft_image_codecs::decode(&r.document.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(); for (x, y) in [(0, 0), (1, 0), (2, 0), (19, 9), (7, 4), (3, 6)] { let [r, g, b] = [[255, 0, 0], [0, 128, 0], [0, 0, 255]][((x + y) % 3) as usize]; assert_eq!(png.get_pixel(x, y).0, [r, g, b, (x * 12) as u8], "({x}, {y}) {big} {per}"); diff --git a/crates/eps/src/import/tests_generators.rs b/crates/eps/src/import/tests_generators.rs index eb2d756fd8..270a1a3aa4 100644 --- a/crates/eps/src/import/tests_generators.rs +++ b/crates/eps/src/import/tests_generators.rs @@ -50,7 +50,24 @@ pub(super) fn pixel(d: &Document, x: u32, y: u32) -> [u8; 4] { _ => None, }) .unwrap(); - let img = image::load_from_memory(&d.images[&im].bytes).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&d.images[&im].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(); img.get_pixel(x, y).0 } @@ -197,7 +214,24 @@ end"##, assert_eq!(of_kind(d, "Image").len(), 2); let im = all(d).into_iter().find(|n| matches!(&n.kind, NodeKind::Image(im) if im.width == 2)).unwrap(); let NodeKind::Image(im) = &im.kind else { panic!() }; - let img = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8(); + let img = 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(); // Painted where the mask is 1, transparent where it is 0. assert_eq!([img.get_pixel(0, 0).0, img.get_pixel(1, 0).0], [[255, 0, 0, 255], [0, 255, 0, 0]]); assert_eq!([img.get_pixel(0, 1).0, img.get_pixel(1, 1).0], [[0, 0, 255, 0], [255, 255, 255, 255]]); diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index 193b81a233..6c21c1b7b2 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -181,7 +181,24 @@ fn masked_cmyk_images_keep_their_inks_and_carry_the_mask_as_an_opacity_mask() { assert_eq!(inks(&r).data, [10, 20, 30, 40, 0, 102, 127, 8], "the inks as they were: {program}"); let n = first_image(&r); let mask = n.extras().mask.as_ref().expect("an opacity mask"); - let gray = image::load_from_memory(&blob(&r, &mask.art).bytes).unwrap().to_luma8(); + let gray = craft_image_codecs::decode(&blob(&r, &mask.art).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(); assert_eq!(gray.into_raw(), alpha, "the mask's values: {program}"); assert_eq!(n.geometric_bounds(), mask.art.geometric_bounds(), "the mask covers the image"); } @@ -342,6 +359,7 @@ fn ccitt_fax_data_in_the_program_ends_at_its_end_of_block() { for (k, eol, aligned, params) in [ (-1, false, false, "/K -1 /Columns 70"), (0, true, false, "/Columns 70 /EndOfLine true"), + (0, true, true, "/Columns 70 /EndOfLine true /EncodedByteAlign true"), (2, true, false, "/K 2 /Columns 70 /Rows 7 /EndOfLine true"), (3, true, true, "/K 3 /Columns 70 /EndOfLine true /EncodedByteAlign true"), ] { @@ -553,8 +571,9 @@ fn the_data_of_an_image_too_large_to_read_is_skipped() { /// allocates for them. #[test] fn a_jpeg_with_a_huge_header_is_refused_before_it_is_decoded() { - let mut jpeg = vec![]; - image::codecs::jpeg::JpegEncoder::new(&mut jpeg).encode(&[128; 64], 8, 8, image::ExtendedColorType::L8).unwrap(); + let cimg = craft_image_codecs::Image::from_raw(8, 8, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, vec![128; 64]) + .unwrap(); + let mut jpeg = craft_image_codecs::encode(&cimg, craft_image_codecs::Format::Jpeg, &craft_image_codecs::EncodeOptions::default()).unwrap(); // The frame header (marker, length, precision, height, width) now says 65535 × 65535. let sof = jpeg.windows(2).position(|w| w == [0xFF, 0xC0]).unwrap(); jpeg[sof + 5..sof + 9].fill(0xFF); diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 327dc22f6f..5a12d24dc2 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -620,7 +620,41 @@ fn top_level_placed_file_replacement_keeps_page_image_data() { let mut page = pdf_part(10.0, 86.0); let pixels = image::RgbaImage::from_pixel(4, 4, image::Rgba([0, 255, 255, 255])); let mut png = Vec::new(); - pixels.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = pixels.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 blob = ImageBlob::new("image/png", png); let key = blob.content_key(); let expected = blob.bytes.clone(); @@ -1289,7 +1323,24 @@ fn an_ai_file_with_an_image_past_2_25_pixels_keeps_its_layers() { let png = &d.images[&im.key].bytes; // Bit depth 1, colour type 0 (gray). assert_eq!(png.get(24..26), Some([1, 0].as_slice())); - let gray = image::load_from_memory(png).unwrap().to_luma8(); + let gray = 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_luma8(); assert_eq!((gray.get_pixel(0, 0)[0], gray.get_pixel(1, 0)[0], gray.get_pixel(5999, 5999)[0]), (0, 255, 255)); assert!(warnings.iter().all(|w| !w.contains("image")), "{warnings:?}"); } @@ -1317,7 +1368,24 @@ fn an_ai_image_past_the_target_size_is_reduced_and_keeps_the_layers() { (full.x0 - 50.0).abs() < 1e-9 && (full.x1 - 67.0).abs() < 1e-9 && (full.y0 - 86.0).abs() < 1e-9 && (full.y1 - 99.0).abs() < 1e-9, "{full:?}" ); - let gray = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_luma8(); + let gray = 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(); // Steps of 4: blocks of rows 0–11 are half white rows, the last block row 12 alone; blocks of // columns 0–3 and 8–11 have 3 white columns of 4, and the last block column 16 alone. let rows: Vec> = (0..4).map(|y| (0..5).map(|x| gray.get_pixel(x, y)[0]).collect()).collect(); diff --git a/crates/eps/src/legacy_ai.rs b/crates/eps/src/legacy_ai.rs index 779385b82b..d304ed27df 100644 --- a/crates/eps/src/legacy_ai.rs +++ b/crates/eps/src/legacy_ai.rs @@ -177,13 +177,8 @@ pub struct LegacyAiOutput { pub fn writes_image_mask(doc: &Document, n: &Node) -> bool { let NodeKind::Image(im) = &n.kind else { return false }; // The size from the file's header, before any pixels are decoded. - let fits = |bytes: &[u8]| { - image::ImageReader::new(std::io::Cursor::new(bytes)) - .with_guessed_format() - .ok() - .and_then(|r| r.into_dimensions().ok()) - .is_some_and(|(w, h)| w > 0 && h > 0 && u64::from(w) * u64::from(h) <= MAX_IMAGE_PIXELS) - }; + let fits = + |bytes: &[u8]| vectorcraft_doc::header_size(bytes).is_some_and(|(w, h)| w > 0 && h > 0 && u64::from(w) * u64::from(h) <= MAX_IMAGE_PIXELS); matches!(n.extras().colorize.as_deref(), Some(Paint::Solid { .. })) && !n.extras().mask.as_ref().is_some_and(|m| !m.disabled) && doc diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index 12a11a78f4..b35eb94fc0 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -58,7 +58,41 @@ fn sample() -> Document { doc.insert(Some(front), usize::MAX, ellipse).unwrap(); let mut png = vec![]; let img = image::RgbaImage::from_raw(2, 1, vec![255, 0, 0, 255, 0, 0, 255, 255]).unwrap(); - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 blob = ImageBlob::new("image/png", png); let key = blob.content_key(); doc.images.insert(key.clone(), blob); @@ -507,11 +541,15 @@ fn writes_the_documented_operators() { #[test] fn a_rotated_image_keeps_its_place() { let mut doc = Document::new(200.0, 100.0); - let mut png = vec![]; - image::RgbaImage::from_raw(2, 1, vec![255, 0, 0, 255, 0, 0, 255, 255]) - .unwrap() - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + let img = craft_image_codecs::Image::from_raw( + 2, + 1, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + vec![255, 0, 0, 255, 0, 0, 255, 255], + ) + .unwrap(); + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); doc.images.insert(key.clone(), blob); @@ -545,9 +583,41 @@ fn a_rotated_image_keeps_its_place() { /// A 16 × 16 RGB image of `doc` filling `r`. fn picture(doc: &mut Document, r: Rect) -> Node { let mut png = vec![]; - image::RgbaImage::from_fn(16, 16, |u, v| image::Rgba([(u * 16) as u8, (v * 16) as u8, 128, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_fn(16, 16, |u, v| image::Rgba([(u * 16) as u8, (v * 16) as u8, 128, 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 blob = ImageBlob::new("image/png", png); let key = blob.content_key(); doc.images.insert(key.clone(), blob); @@ -666,9 +736,42 @@ fn the_pieces_of_a_warped_image_are_written_as_the_parts_they_show() { // GUARDS: each of a warped image's 200 pieces was written with all of the image's samples. let mut doc = Document::new(200.0, 160.0); let mut png = vec![]; - image::RgbaImage::from_fn(64, 64, |x, y| image::Rgba([(x * 4) as u8, (y * 4) as u8, ((x * 7 + y * 13) % 256) as u8, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = + (image::RgbaImage::from_fn(64, 64, |x, y| image::Rgba([(x * 4) as u8, (y * 4) as u8, ((x * 7 + y * 13) % 256) 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 blob = ImageBlob::new("image/png", png); let key = blob.content_key(); doc.images.insert(key.clone(), blob); @@ -725,7 +828,41 @@ fn empty_images_get_the_size_note_and_undecodable_ones_the_decode_note() { /// at (`x`, `y`). fn colorized_image(doc: &mut Document, (w, h): (u32, u32), gray: Vec, paint: &Paint, (x, y): (f64, f64)) -> Node { let mut png = vec![]; - image::GrayImage::from_raw(w, h, gray).unwrap().write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::GrayImage::from_raw(w, h, gray).unwrap()).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 blob = ImageBlob::new("image/png", png); let key = blob.content_key(); doc.images.insert(key.clone(), blob); diff --git a/crates/eps/src/legacy_ai/writer.rs b/crates/eps/src/legacy_ai/writer.rs index c8bce40227..0551d1821c 100644 --- a/crates/eps/src/legacy_ai/writer.rs +++ b/crates/eps/src/legacy_ai/writer.rs @@ -1183,7 +1183,17 @@ impl<'a> Writer<'a> { { return img.clone(); } - let img = image::load_from_memory(&blob.bytes).ok().map(Arc::new); + let too_large = |w: u32, h: u32| w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_IMAGE_PIXELS; + let img = if vectorcraft_doc::header_size(&blob.bytes).is_some_and(|(w, h)| too_large(w, h)) { + None + } else { + vectorcraft_doc::decode::decode_within(&blob.bytes, MAX_IMAGE_PIXELS.saturating_mul(8)) + .ok() + .flatten() + .map(|(img, _)| img) + .filter(|img| !too_large(img.width(), img.height())) + } + .map(Arc::new); self.last_image = Some((blob.clone(), img.clone())); self.last_coverage = None; img diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index 17608c7346..5bbb1c9fed 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -1707,11 +1707,18 @@ impl<'a> Scene<'a> { /// Image `blob` as RGBA pixels; `None` (with a warning) when it can't be written. fn decode_image(&mut self, blob: Option<&ImageBlob>) -> Option { - let Some(img) = blob.and_then(|blob| image::load_from_memory(&blob.bytes).ok()) else { + let too_large = |w: u32, h: u32| w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_IMAGE_PIXELS; + if blob.is_some_and(|b| vectorcraft_doc::header_size(&b.bytes).is_some_and(|(w, h)| too_large(w, h))) { + self.warn(LARGE_IMAGE); + return None; + } + let Some(img) = blob.and_then(|blob| { + vectorcraft_doc::decode::decode_within(&blob.bytes, MAX_IMAGE_PIXELS.saturating_mul(8)).ok().flatten().map(|(img, _)| img) + }) else { self.warn(UNDECODED); return None; }; - if u64::from(img.width()) * u64::from(img.height()) > MAX_IMAGE_PIXELS { + if too_large(img.width(), img.height()) { self.warn(LARGE_IMAGE); return None; } diff --git a/crates/eps/src/tiff.rs b/crates/eps/src/tiff.rs index 4ee3b53d5b..e1c3d7431e 100644 --- a/crates/eps/src/tiff.rs +++ b/crates/eps/src/tiff.rs @@ -46,10 +46,15 @@ pub(crate) fn encode(img: &Raster, bw: bool, alpha: bool) -> Result, Str /// `img` as a PNG. pub(crate) fn png(img: &Raster) -> Result, String> { - let rgba = image::RgbaImage::from_raw(img.width, img.height, img.rgba.clone()).ok_or("the thumbnail image is malformed")?; - let mut out = vec![]; - rgba.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).map_err(|e| e.to_string())?; - Ok(out) + let raw = craft_image_codecs::Image::from_raw( + img.width, + img.height, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + img.rgba.clone(), + ) + .map_err(|_| "the thumbnail image is malformed".to_string())?; + craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).map_err(|e| e.to_string()) } /// Most pixels a palette preview may have. diff --git a/crates/mcp/Cargo.toml b/crates/mcp/Cargo.toml index 30cb6aef0a..4a74c6bdfb 100644 --- a/crates/mcp/Cargo.toml +++ b/crates/mcp/Cargo.toml @@ -26,6 +26,7 @@ serde_json = { workspace = true } log = { workspace = true } image = { workspace = true } +craft-image-codecs = { workspace = true } [dev-dependencies] vectorcraft-testkit = { workspace = true } diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index fc4cc6543d..97759ba03a 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -498,11 +498,16 @@ fn scaled_down_pictures_keep_the_color_beside_clear_pixels() { struct Striped; impl Backend for Striped { fn call(&mut self, method: &str, _: Value) -> Result { - let mut png = std::io::Cursor::new(Vec::new()); - image::RgbaImage::from_fn(64, 4, |x, _| if x % 2 == 0 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([0, 0, 0, 0]) }) - .write_to(&mut png, image::ImageFormat::Png) + let mut data = Vec::with_capacity(64 * 4 * 4); + for _ in 0..4 { + for x in 0..64 { + data.extend_from_slice(&if x % 2 == 0 { [200, 30, 30, 255] } else { [0, 0, 0, 0] }); + } + } + let raw = craft_image_codecs::Image::from_raw(64, 4, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, data) .unwrap(); - let png = vectorcraft_format::base64_encode(png.get_ref()); + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); + let png = vectorcraft_format::base64_encode(&png); Ok(match method { "document.inspect" => json!({"artboards": [{"width": 64, "height": 4}]}), _ => json!({"pngBase64": png, "width": 64, "height": 4}), @@ -522,7 +527,8 @@ fn scaled_down_pictures_keep_the_color_beside_clear_pixels() { let r = call(&mut s, id, tool, args); let data = r["content"].as_array().unwrap().iter().find(|c| c["type"] == "image").unwrap_or_else(|| panic!("{tool}: {r}"))["data"].as_str().unwrap(); - let img = image::load_from_memory(&vectorcraft_format::base64_decode(data).unwrap()).unwrap().into_rgba8(); + let decoded = craft_image_codecs::decode(&vectorcraft_format::base64_decode(data).unwrap()).unwrap(); + let img = image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap(); assert_eq!(img.dimensions(), (16, 1), "{tool}"); assert!(img.pixels().all(|p| p.0 == [200, 30, 30, 128]), "{tool}: {:?}", img.get_pixel(0, 0)); } @@ -536,12 +542,16 @@ fn screenshot_and_render_preview_draw_the_trace_view_with_trace_views() { let dir = TempFolder::new("trace-views"); let mut s = server(); let png = dir.file("trace-views.png"); - image::RgbImage::from_fn(100, 100, |x, y| { - let (dx, dy) = (f64::from(x) + 0.5 - 50.0, f64::from(y) + 0.5 - 50.0); - if dx * dx + dy * dy <= 900.0 { image::Rgb([0, 0, 0]) } else { image::Rgb([170, 210, 255]) } - }) - .save(&png) - .unwrap(); + let mut rgb = Vec::with_capacity(100 * 100 * 3); + for y in 0..100 { + for x in 0..100 { + let (dx, dy) = (f64::from(x) + 0.5 - 50.0, f64::from(y) + 0.5 - 50.0); + rgb.extend_from_slice(&if dx * dx + dy * dy <= 900.0 { [0, 0, 0] } else { [170, 210, 255] }); + } + } + let raw = craft_image_codecs::Image::from_raw(100, 100, craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, rgb).unwrap(); + std::fs::write(&png, craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap()) + .unwrap(); let ok = |s: &mut Server, id: u64, name: &str, args: Value| { let r = call(s, id, name, args); assert_eq!(r["isError"], false, "{name}: {r}"); @@ -552,7 +562,8 @@ fn screenshot_and_render_preview_draw_the_trace_view_with_trace_views() { ok(&mut s, 3, "run_command", json!({"command": "imageTrace.make", "params": {"params": {"ignoreWhite": true}}})); let pixels = |r: &Value| { let data = r["content"].as_array().unwrap().iter().find(|c| c["type"] == "image").unwrap()["data"].as_str().unwrap(); - image::load_from_memory(&vectorcraft_format::base64_decode(data).unwrap()).unwrap().to_rgba8() + let decoded = craft_image_codecs::decode(&vectorcraft_format::base64_decode(data).unwrap()).unwrap(); + image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap() }; let dark = |p: &image::Rgba| p[0] < 60 && p[1] < 60 && p[2] < 60; let white = |p: &image::Rgba| p[0] > 245 && p[1] > 245 && p[2] > 245; diff --git a/crates/mcp/src/tests/conventions.rs b/crates/mcp/src/tests/conventions.rs index 3618f9214f..9020370c26 100644 --- a/crates/mcp/src/tests/conventions.rs +++ b/crates/mcp/src/tests/conventions.rs @@ -145,7 +145,7 @@ fn conventions_commands_batch_and_bounded_preview() { let r = call(&mut s, "render_preview", json!({"max_side":64})); assert_eq!(r["isError"], false, "{r}"); let png = vectorcraft_format::base64_decode(r["content"][0]["data"].as_str().unwrap()).unwrap(); - let img = image::load_from_memory(&png).unwrap(); + let img = craft_image_codecs::decode(&png).unwrap(); assert!(img.width() <= 64 && img.height() <= 64); assert_eq!(before, call(&mut s, "doc_inspect", json!({}))); for max in [json!(0), json!(4097), json!("64")] { @@ -157,7 +157,7 @@ fn conventions_commands_batch_and_bounded_preview() { let r = call(&mut s, "render_preview", json!({"max_side":60,"artboard":1})); assert_eq!(r["isError"], false, "{r}"); let png = vectorcraft_format::base64_decode(r["content"][0]["data"].as_str().unwrap()).unwrap(); - let img = image::load_from_memory(&png).unwrap(); + let img = craft_image_codecs::decode(&png).unwrap(); assert_eq!((img.width(), img.height()), (60, 20)); for board in [json!(2), json!(-1), json!("1")] { assert_eq!(call(&mut s, "render_preview", json!({"artboard":board}))["isError"], true, "{board}"); @@ -180,7 +180,10 @@ fn render_preview_and_screenshot_match_a_png_export_on_white() { } let r = call(&mut s, "draw_path", json!({"points":[[10,75],[110,5],[115,30]],"closed":true,"fill":"#30a050"})); assert_eq!(r["isError"], false, "{r}"); - let pixels = |b64: &str| image::load_from_memory(&vectorcraft_format::base64_decode(b64).unwrap()).unwrap().to_rgba8(); + let pixels = |b64: &str| { + let decoded = craft_image_codecs::decode(&vectorcraft_format::base64_decode(b64).unwrap()).unwrap(); + image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap() + }; let export = payload(&call(&mut s, "run_command", json!({"command":"document.export","params":{"format":"png","background":"white"}}))); let export = pixels(export["dataBase64"].as_str().unwrap()); assert_eq!(export.dimensions(), (120, 80)); @@ -276,11 +279,15 @@ impl Backend for Window { /// image down to it and reports the capture's own size; without it the capture comes back as sent. #[test] fn window_captures_take_max_side() { - let mut capture = std::io::Cursor::new(Vec::new()); - image::RgbaImage::from_fn(1200, 800, |x, y| image::Rgba([(x % 256) as u8, (y % 256) as u8, 90, 255])) - .write_to(&mut capture, image::ImageFormat::Png) - .unwrap(); - let capture = capture.into_inner(); + let mut data = Vec::with_capacity(1200 * 800 * 4); + for y in 0..800 { + for x in 0..1200 { + data.extend_from_slice(&[(x % 256) as u8, (y % 256) as u8, 90, 255]); + } + } + let raw = + craft_image_codecs::Image::from_raw(1200, 800, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, data).unwrap(); + let capture = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); let mut s = Server::new(Box::new(Window(capture.clone()))); let image_of = |r: &Value| vectorcraft_format::base64_decode(r["content"][0]["data"].as_str().unwrap()).unwrap(); let info = |r: &Value| -> Value { serde_json::from_str(r["content"][1]["text"].as_str().unwrap()).unwrap() }; @@ -292,7 +299,7 @@ fn window_captures_take_max_side() { args["max_side"] = json!(300); let r = call(&mut s, name, args.clone()); assert_eq!(r["isError"], false, "{name}: {r}"); - let img = image::load_from_memory(&image_of(&r)).unwrap(); + let img = craft_image_codecs::decode(&image_of(&r)).unwrap(); assert_eq!((img.width(), img.height()), (300, 200), "{name}"); let i = info(&r); assert_eq!((i["width"].clone(), i["height"].clone()), (json!(300), json!(200)), "{name}: {i}"); diff --git a/crates/mcp/src/tests/exportas.rs b/crates/mcp/src/tests/exportas.rs index 4e41002bf0..a0220fc38b 100644 --- a/crates/mcp/src/tests/exportas.rs +++ b/crates/mcp/src/tests/exportas.rs @@ -100,7 +100,7 @@ fn raster_export_uses_document_resolution_unless_overridden() { params["format"] = json!("png"); let r = text(&call_tool(&mut h, "export", ¶ms)); let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); - assert_eq!(image::load_from_memory(&bytes).unwrap().to_rgba8().dimensions(), size, "{args}"); + assert_eq!(craft_image_codecs::decode(&bytes).unwrap().dimensions(), size, "{args}"); } } @@ -116,7 +116,8 @@ fn export_with_a_range_writes_one_file_per_artboard() { for (f, board) in files.iter().zip(["Artboard-1", "Artboard-3"]) { let p = f.as_str().unwrap(); assert!(p.ends_with(&format!("icon-{board}.png")), "{p}"); - let img = image::load_from_memory(&std::fs::read(p).unwrap()).unwrap().to_rgba8(); + let decoded = craft_image_codecs::decode(&std::fs::read(p).unwrap()).unwrap(); + let img = image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap(); assert_eq!(img.dimensions(), (100, 60), "144 ppi"); assert!(img.pixels().all(|px| px[3] == 255), "white background"); } diff --git a/crates/mcp/src/tools/dispatch.rs b/crates/mcp/src/tools/dispatch.rs index 8b9db99564..2ee9f01759 100644 --- a/crates/mcp/src/tools/dispatch.rs +++ b/crates/mcp/src/tools/dispatch.rs @@ -465,7 +465,16 @@ fn render_preview(b: &mut dyn Backend, a: &Args) -> Result { // The render was asked for at most 4096 a side. let img = super::handlers::decode_png(&png, 8192).map_err(|e| format!("read preview: {e}"))?; let img = if img.width() > max || img.height() > max { fitted(img, max, max, Resample::Average) } else { img }; - let mut out = std::io::Cursor::new(Vec::new()); - img.write_to(&mut out, image::ImageFormat::Png).map_err(|e| format!("encode preview: {e}"))?; - Ok(image_result(out.get_ref(), json!({"width":img.width(),"height":img.height()}))) + let rgba = img.to_rgba8(); + let raw = craft_image_codecs::Image::from_raw( + rgba.width(), + rgba.height(), + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + rgba.into_raw(), + ) + .map_err(|e| format!("encode preview: {e}"))?; + let out = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map_err(|e| format!("encode preview: {e}"))?; + Ok(image_result(&out, json!({"width":img.width(),"height":img.height()}))) } diff --git a/crates/mcp/src/tools/handlers.rs b/crates/mcp/src/tools/handlers.rs index 5aefa20d31..717c641e19 100644 --- a/crates/mcp/src/tools/handlers.rs +++ b/crates/mcp/src/tools/handlers.rs @@ -499,14 +499,16 @@ const MAX_CAPTURE_SIDE: u32 = 16_384; /// `png` decoded, refused when a side is longer than `side` or the decode needs more than 256 MiB: /// the picture is the app's reply, and its header names the size it is decoded at. -pub(super) fn decode_png(png: &[u8], side: u32) -> Result { - let mut reader = image::ImageReader::with_format(std::io::Cursor::new(png), image::ImageFormat::Png); - let mut limits = image::Limits::default(); - limits.max_image_width = Some(side); - limits.max_image_height = Some(side); - limits.max_alloc = Some(256 << 20); - reader.limits(limits); - reader.decode() +pub(super) fn decode_png(png: &[u8], side: u32) -> Result { + let mut opts = craft_image_codecs::DecodeOptions::default(); + opts.limits.max_width = side; + opts.limits.max_height = side; + opts.limits.max_alloc = 256 << 20; + let img = craft_image_codecs::decode_as_with(craft_image_codecs::Format::Png, png, &opts).map_err(|e| e.to_string())?; + let (w, h) = img.dimensions(); + image::RgbaImage::from_raw(w, h, img.to_rgba8()) + .map(image::DynamicImage::ImageRgba8) + .ok_or_else(|| "decoded PNG buffer size mismatch".to_string()) } /// A window capture with `max_side`: scaled down when its longer side is larger, with its own size @@ -525,9 +527,17 @@ fn fit_capture(png: Vec, max: Option, info: &mut Value) -> Result ToolResult { @@ -546,9 +556,15 @@ mod decode_tests { #[test] fn a_picture_with_a_side_past_the_limit_is_not_decoded() { - let mut png = std::io::Cursor::new(Vec::new()); - image::RgbaImage::new(200, 10).write_to(&mut png, image::ImageFormat::Png).unwrap(); - let png = png.into_inner(); + let img = craft_image_codecs::Image::from_raw( + 200, + 10, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + vec![0; 200 * 10 * 4], + ) + .unwrap(); + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); assert!(decode_png(&png, 100).is_err()); assert_eq!(decode_png(&png, 200).unwrap().width(), 200); } diff --git a/crates/metafile/Cargo.toml b/crates/metafile/Cargo.toml index 9fdf99d732..408e6166a1 100644 --- a/crates/metafile/Cargo.toml +++ b/crates/metafile/Cargo.toml @@ -18,6 +18,7 @@ vectorcraft-text = { workspace = true } craft-metafile = { workspace = true } kurbo = { workspace = true } image = { workspace = true } +craft-image-codecs = { workspace = true } [dev-dependencies] # The tests lay type out in the bundled fonts (the workspace leaves turning them on to the engine). diff --git a/crates/metafile/src/dib.rs b/crates/metafile/src/dib.rs index a1f1df8cc3..b104304d7f 100644 --- a/crates/metafile/src/dib.rs +++ b/crates/metafile/src/dib.rs @@ -1,8 +1,6 @@ //! Device-independent bitmaps (DIBs), the pixels inside image records: written bottom-up as 24-bit //! (opaque, composited over white) or 32-bit premultiplied BGRA (AlphaBlend's source). -use std::io::Cursor; - use vectorcraft_doc::resample::{Resample, resized}; /// Most pixels along a side of an image the writers store (larger ones are scaled down). @@ -54,10 +52,9 @@ impl Rgba { /// As PNG bytes. pub fn to_png(&self) -> Result, String> { - let img = image::RgbaImage::from_raw(self.width, self.height, self.pixels.clone()).ok_or("the image's pixels don't match its size")?; - let mut png = vec![]; - img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| e.to_string())?; - Ok(png) + let img = craft_image_codecs::Image::from_u8(self.width, self.height, craft_image_codecs::ChannelLayout::Rgba, self.pixels.clone()) + .map_err(|_| "the image's pixels don't match its size")?; + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).map_err(|e| e.to_string()) } } diff --git a/crates/metafile/src/import/pict.rs b/crates/metafile/src/import/pict.rs index f6abbc6b83..a1e5a674e0 100644 --- a/crates/metafile/src/import/pict.rs +++ b/crates/metafile/src/import/pict.rs @@ -20,7 +20,6 @@ //! nothing VectorCraft reads are skipped; a picture cut short keeps what came before. use std::collections::HashMap; -use std::io::Cursor; use vectorcraft_geom::{Affine, BezPath, FillRule, Point, Rect, Shape, Vec2, shapes}; @@ -1097,14 +1096,18 @@ impl Pict { /// A JPEG stream's pixels, taken from the file's pixel budget. fn jpeg(&mut self, data: &[u8]) -> Result { - let reader = || image::ImageReader::with_format(Cursor::new(data), image::ImageFormat::Jpeg); - let (w, h) = reader().into_dimensions().map_err(|_| BAD_IMAGE)?; - if w > dib::MAX_READ_SIDE || h > dib::MAX_READ_SIDE || u64::from(w) * u64::from(h) > dib::MAX_READ_PIXELS { - return Err(TOO_MANY_PIXELS); - } + let mut opts = craft_image_codecs::DecodeOptions::default(); + opts.limits.max_width = dib::MAX_READ_SIDE; + opts.limits.max_height = dib::MAX_READ_SIDE; + opts.limits.max_pixels = dib::MAX_READ_PIXELS.min(self.p.pixels_left); + let img = match craft_image_codecs::decode_as_with(craft_image_codecs::Format::Jpeg, data, &opts) { + Ok(img) => img, + Err(craft_image_codecs::CodecError::LimitExceeded(_)) => return Err(TOO_MANY_PIXELS), + Err(_) => return Err(BAD_IMAGE), + }; + let (w, h) = img.dimensions(); dib::charge(w, h, &mut self.p.pixels_left).map_err(|_| TOO_MANY_PIXELS)?; - let img = reader().decode().map_err(|_| BAD_IMAGE)?.to_rgba8(); - Ok(Rgba { width: img.width(), height: img.height(), pixels: img.into_raw() }) + Ok(Rgba { width: w, height: h, pixels: img.to_rgba8() }) } } diff --git a/crates/metafile/src/scene.rs b/crates/metafile/src/scene.rs index 6a6fd0b61f..3e7f2024d5 100644 --- a/crates/metafile/src/scene.rs +++ b/crates/metafile/src/scene.rs @@ -490,8 +490,9 @@ impl<'a> Scene<'a> { } let blob = self.doc.image_blob(im).filter(|b| !b.bytes.is_empty()); let img = blob - .and_then(|b| image::load_from_memory(&b.bytes).ok()) - .map(|i| Rgba::fitted(i.to_rgba8())) + .and_then(|b| craft_image_codecs::decode(&b.bytes).ok()) + .and_then(|i| image::RgbaImage::from_raw(i.width(), i.height(), i.to_rgba8())) + .map(Rgba::fitted) .filter(|i| i.width > 0 && i.height > 0) .map(Arc::new); if img.is_none() { diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs index ceb65d6fe2..2314ccb637 100644 --- a/crates/metafile/src/tests.rs +++ b/crates/metafile/src/tests.rs @@ -43,10 +43,15 @@ pub(crate) fn blue() -> Paint { /// A `w` × `h` PNG of `rgba`. pub(crate) fn png(w: u32, h: u32, rgba: [u8; 4]) -> Vec { - let img = image::RgbaImage::from_pixel(w, h, image::Rgba(rgba)); - let mut out = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); - out + let img = craft_image_codecs::Image::from_raw( + w, + h, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + rgba.repeat((w * h) as usize), + ) + .unwrap(); + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() } /// CRC-32 of a PNG chunk. @@ -64,8 +69,12 @@ pub(crate) fn crc32(data: &[u8]) -> u32 { /// A 1 × 1 PNG whose IHDR claims `w` × `h` (and whose CRC matches): its size reads from the header, /// but its pixel data no longer matches, so decoding it fails. pub(crate) fn png_claiming(w: u32, h: u32) -> Vec { - let mut png = vec![]; - image::GrayImage::new(1, 1).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let mut png = craft_image_codecs::encode( + &craft_image_codecs::Image::from_raw(1, 1, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, vec![0]).unwrap(), + craft_image_codecs::Format::Png, + &craft_image_codecs::EncodeOptions::default(), + ) + .unwrap(); png[16..20].copy_from_slice(&w.to_be_bytes()); png[20..24].copy_from_slice(&h.to_be_bytes()); let crc = crc32(&png[12..29]); diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index 622a800414..d8f4e8cce0 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -139,7 +139,8 @@ fn freeform_points_that_share_a_model_are_written_as_their_mix() { _ => None, }) .unwrap(); - let px = image::load_from_memory(&back.document.images[&im.key].bytes).unwrap().to_rgba8(); + let decoded = craft_image_codecs::decode(&back.document.images[&im.key].bytes).unwrap(); + let px = image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap(); px.get_pixel(px.width() / 2, px.height() / 2).0 }; let near = |got: [u8; 4], want: [u8; 4]| got.iter().zip(want).all(|(g, w)| g.abs_diff(w) <= 6); @@ -181,7 +182,8 @@ fn dashes_gradients_and_images_round_trip_through_emf() { assert_eq!(im.height, 2); let placed = im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, 4.0, 2.0)); assert!(near(placed, Rect::new(100.0, 10.0, 120.0, 20.0), 0.05), "{placed:?}"); - let px = image::load_from_memory(&back.document.images[&im.key].bytes).unwrap().to_rgba8(); + let decoded = craft_image_codecs::decode(&back.document.images[&im.key].bytes).unwrap(); + let px = image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap(); assert_eq!(px.get_pixel(0, 0).0, [0, 200, 0, 255]); } diff --git a/crates/metafile/src/tests/pict.rs b/crates/metafile/src/tests/pict.rs index 055e88c95b..0d8b48c939 100644 --- a/crates/metafile/src/tests/pict.rs +++ b/crates/metafile/src/tests/pict.rs @@ -87,7 +87,8 @@ fn images(d: &Document) -> Vec<(Node, image::RgbaImage)> { .into_iter() .filter_map(|n| match &n.kind { NodeKind::Image(im) => { - let png = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8(); + let decoded = craft_image_codecs::decode(&d.images[&im.key].bytes).unwrap(); + let png = image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap(); Some((n.clone(), png)) } _ => None, @@ -374,10 +375,15 @@ fn quicktime(ctype: &[u8; 4], matrix: [f64; 6], w: i16, h: i16, data: &[u8]) -> } fn red_jpeg() -> Vec { - let img = image::RgbImage::from_pixel(4, 2, image::Rgb([255, 0, 0])); - let mut out = std::io::Cursor::new(vec![]); - img.write_to(&mut out, image::ImageFormat::Jpeg).unwrap(); - out.into_inner() + let img = craft_image_codecs::Image::from_raw( + 4, + 2, + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U8, + [255u8, 0, 0].repeat(8), + ) + .unwrap(); + craft_image_codecs::encode(&img, craft_image_codecs::Format::Jpeg, &craft_image_codecs::EncodeOptions::default()).unwrap() } #[test] diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index d59243eb75..817d334fb8 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -24,14 +24,15 @@ kurbo = { workspace = true } thiserror = { workspace = true } flate2 = { workspace = true, features = ["zlib-rs"] } image = { workspace = true } -# CMYK JPEGs (the image crate writes RGB and grey ones only). +craft-image-codecs = { workspace = true } +# CMYK JPEGs (src/images.rs; the image crate writes RGB and grey ones only). jpeg-encoder = { workspace = true } craft-pdf = { workspace = true } +craft-stream-codecs = { workspace = true } log = { workspace = true } chrono = { workspace = true } smallvec = "1" siphasher = "1" -weezl = "0.2" serde = { workspace = true } # The XMP packet that File Info is read from (file_info.rs). craft-xml = { workspace = true } diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs index 4ba361d29b..66d49a3bc4 100644 --- a/crates/pdf/src/export.rs +++ b/crates/pdf/src/export.rs @@ -164,19 +164,22 @@ mod tests { #[test] fn a_16_bit_png_at_8_bits_keeps_its_color_type_and_icc_profile() { - use image::{ImageDecoder, ImageEncoder}; + use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image as CodecImage, SampleType}; let icc = vectorcraft_color::cms::icc_bytes(vectorcraft_color::cms::GRAY).unwrap().to_vec(); - let gray = image::DynamicImage::ImageLuma16(image::ImageBuffer::from_fn(4, 2, |x, y| image::Luma([x as u16 * 20000 + y as u16]))); - let mut png = vec![]; - let mut encoder = image::codecs::png::PngEncoder::new(&mut png); - encoder.set_icc_profile(icc.clone()).unwrap(); - gray.write_with_encoder(encoder).unwrap(); + let u16_samples: Vec = (0..2).flat_map(|y| (0..4).map(move |x| x as u16 * 20000 + y as u16)).collect(); + let raw_u16: Vec = u16_samples.iter().flat_map(|v| v.to_ne_bytes()).collect(); + let mut src = CodecImage::from_raw(4, 2, ChannelLayout::Gray, SampleType::U16, raw_u16).unwrap(); + src.icc = Some(icc.clone()); + let png = craft_image_codecs::encode(&src, Format::Png, &EncodeOptions::default()).unwrap(); assert!(png_16_bit(&png)); let out = png_8_bit(&png).unwrap(); assert!(!png_16_bit(&out)); - let mut decoder = image::codecs::png::PngDecoder::new(std::io::Cursor::new(out.as_slice())).unwrap(); - assert_eq!(decoder.icc_profile().unwrap(), Some(icc)); - assert_eq!(decoder.color_type(), image::ColorType::L8); - assert_eq!(image::DynamicImage::from_decoder(decoder).unwrap().to_luma8(), gray.to_luma8()); + let decoded = craft_image_codecs::decode_as_with(Format::Png, &out, &craft_image_codecs::DecodeOptions::default()).unwrap(); + assert_eq!(decoded.icc, Some(icc)); + assert_eq!(decoded.layout(), ChannelLayout::Gray); + assert_eq!(decoded.sample_type(), SampleType::U8); + // Rounded to the nearest 8-bit level, as the 8-bit copy is made. + let want: Vec = u16_samples.into_iter().map(|v| ((u32::from(v) * 255 + 32_767) / 65_535) as u8).collect(); + assert_eq!(decoded.data(), want); } } diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index c2650138b9..e6e34ae429 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -748,8 +748,15 @@ impl<'p> Builder<'p> { self.opaque.insert(mkey); return None; }; - let mut png = Vec::new(); - image::GrayImage::from_raw(a.width, a.height, a.data)?.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?; + let raw = craft_image_codecs::Image::from_raw( + a.width, + a.height, + craft_image_codecs::ChannelLayout::Gray, + craft_image_codecs::SampleType::U8, + a.data, + ) + .ok()?; + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; let blob = ImageBlob::new("image/png", png); let k = blob.content_key(); self.images.insert(k.clone(), blob); diff --git a/crates/pdf/src/import/state.rs b/crates/pdf/src/import/state.rs index 7deb2bd73b..1eeb8a5539 100644 --- a/crates/pdf/src/import/state.rs +++ b/crates/pdf/src/import/state.rs @@ -336,17 +336,13 @@ pub(super) fn bounds(nodes: &[Arc]) -> Option { } pub(super) fn rgba_png(rgba: Vec, w: u32, h: u32) -> Option> { - let img = image::RgbaImage::from_raw(w, h, rgba)?; - let mut out = Vec::new(); - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).ok()?; - Some(out) + let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).ok()?; + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() } pub(super) fn gray_png(gray: Vec, w: u32, h: u32) -> Option> { - let img = image::GrayImage::from_raw(w, h, gray)?; - let mut out = Vec::new(); - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).ok()?; - Some(out) + let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, gray).ok()?; + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() } pub(super) fn resize_alpha(a: &LumaData, w: u32, h: u32) -> Vec { diff --git a/crates/pdf/src/streams.rs b/crates/pdf/src/streams.rs index 8fb57198fe..3f99b8b82a 100644 --- a/crates/pdf/src/streams.rs +++ b/crates/pdf/src/streams.rs @@ -71,23 +71,14 @@ fn inflate(data: &[u8], max: usize) -> Option> { read(Box::new(flate2::read::ZlibDecoder::new(data))).or_else(|| read(Box::new(flate2::read::DeflateDecoder::new(data)))) } -/// `data` decoded from LZW, up to one byte past `max`. `early`: the code length grows one code +/// `data` decoded from LZW, up to `max`. `early`: the code length grows one code /// early (`EarlyChange`, 1 by default). fn lzw(data: &[u8], early: bool, max: usize) -> Option> { - use weezl::{BitOrder, LzwStatus, decode::Decoder}; - let mut decoder = if early { Decoder::with_tiff_size_switch(BitOrder::Msb, 8) } else { Decoder::new(BitOrder::Msb, 8) }; - let (mut out, mut chunk, mut input) = (vec![], vec![0; 1 << 16], data); - while out.len() <= max { - let r = decoder.decode_bytes(input, &mut chunk); - input = input.get(r.consumed_in..).unwrap_or_default(); - out.extend_from_slice(chunk.get(..r.consumed_out).unwrap_or_default()); - match r.status { - Ok(LzwStatus::Ok) => {} - Ok(LzwStatus::Done | LzwStatus::NoProgress) => break, - Err(_) => return (out.len() > max).then_some(out), - } + match craft_stream_codecs::lzw::decode(data, early, max) { + Ok(out) => Some(out), + Err(f) if matches!(f.error, craft_stream_codecs::CodecError::LimitExceeded(_)) => Some(vec![0u8; max.saturating_add(1)]), + Err(_) => None, } - Some(out) } /// `data` decoded from run-length encoding, up to one byte past `max`. diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index b49a033a23..2337cc8dee 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -834,7 +834,41 @@ fn tiny_png() -> Vec { *p = image::Rgba([if x < 2 { 255 } else { 0 }, 0, 0, 255]); } let mut out = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 } @@ -859,7 +893,24 @@ fn image_roundtrip() { assert_eq!((im.width, im.height), (4, 2)); assert!(close(l[0].geometric_bounds().unwrap(), Rect::new(20.0, 30.0, 60.0, 50.0), 0.01), "{:?}", l[0].geometric_bounds()); let blob = &out.images[&im.key]; - let decoded = image::load_from_memory(&blob.bytes).unwrap().to_rgba8(); + let decoded = 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!(decoded.get_pixel(0, 0).0, [255, 0, 0, 255]); assert_eq!(decoded.get_pixel(3, 0).0, [0, 0, 0, 255]); } @@ -891,9 +942,42 @@ fn a_pixelated_image_asks_viewers_not_to_smooth_it() { /// A 4 × 2 red image encoded as `format`, cut short `keep` bytes past the first `tag` in it: its /// header reads, and its pixel data can't be decoded. -fn cut_image(format: image::ImageFormat, tag: &[u8], keep: usize) -> Vec { +fn cut_image(format: craft_image_codecs::Format, tag: &[u8], keep: usize) -> Vec { let mut out = vec![]; - image::RgbaImage::from_pixel(4, 2, image::Rgba([255, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut out), format).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(4, 2, image::Rgba([255, 0, 0, 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, format, &craft_image_codecs::EncodeOptions::default()).map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); let at = out.windows(tag.len()).position(|w| w == tag).expect("tag"); out.truncate(at + tag.len() + keep); out @@ -908,10 +992,10 @@ fn an_image_whose_pixels_cant_be_decoded_is_left_out_with_one_note() { let mut d = doc(200.0, 300.0); let blobs = [ ("good", ImageBlob::new("image/png", tiny_png())), - ("png", ImageBlob::new("image/png", cut_image(image::ImageFormat::Png, b"IDAT", 4))), - ("png2", ImageBlob::new("image/png", cut_image(image::ImageFormat::Png, b"IDAT", 6))), - ("gif", ImageBlob::new("image/gif", cut_image(image::ImageFormat::Gif, b"GIF89a", 7))), - ("webp", ImageBlob::new("image/webp", cut_image(image::ImageFormat::WebP, b"VP8L", 9))), + ("png", ImageBlob::new("image/png", cut_image(craft_image_codecs::Format::Png, b"IDAT", 4))), + ("png2", ImageBlob::new("image/png", cut_image(craft_image_codecs::Format::Png, b"IDAT", 6))), + ("gif", ImageBlob::new("image/gif", cut_image(craft_image_codecs::Format::Gif, b"GIF89a", 7))), + ("webp", ImageBlob::new("image/webp", cut_image(craft_image_codecs::Format::WebP, b"VP8L", 9))), ]; for (i, (key, blob)) in blobs.into_iter().enumerate() { d.images.insert(key.into(), blob); diff --git a/crates/pdf/src/tests/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index 57ccef1c6d..deb98b1fea 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -17,9 +17,9 @@ use crate::*; /// `inks` (four bytes a pixel) as a CMYK JPEG: Adobe's inverted samples, with its marker. fn cmyk_jpeg(inks: &[u8], w: u16, h: u16) -> Vec { - let mut out = Vec::new(); - jpeg_encoder::Encoder::new(&mut out, 100).encode(inks, w, h, jpeg_encoder::ColorType::Cmyk).unwrap(); - out + let img = craft_image_codecs::Image::from_u8(u32::from(w), u32::from(h), craft_image_codecs::ChannelLayout::Cmyk, inks.to_vec()).unwrap(); + let opts = craft_image_codecs::EncodeOptions { jpeg_quality: 100, embed_icc: false, embed_metadata: false, ..Default::default() }; + craft_image_codecs::encode(&img, craft_image_codecs::Format::Jpeg, &opts).unwrap() } fn flat(inks: [u8; 4], n: usize) -> Vec { @@ -275,7 +275,24 @@ fn masked_cmyk_images_keep_their_inks_and_carry_the_mask_as_an_opacity_mask() { assert!(close(&blob.cmyk().unwrap().data, want, 0), "the inks as they were"); let (mblob, mw, mh) = mask.expect("an opacity mask"); assert_eq!((mw, mh), (2, 2)); - let grey = image::load_from_memory(&mblob.bytes).unwrap().to_luma8(); + let grey = craft_image_codecs::decode(&mblob.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(); assert_eq!(grey.into_raw(), alpha, "the mask's values"); } // The mask art covers the image exactly. @@ -439,7 +456,26 @@ fn the_output_settings_convert_cmyk_images_and_compression_recompresses_them_in_ let (w, blob, _) = first(json!({"output": {"conversion": "destination", "destination": SRGB}})); assert_eq!(w.space, "DeviceRGB"); let shown = source.cmyk_to_srgb(ink.map(|v| v as f32 / 255.0), false).map(|v| (v * 255.0).round() as u8); - let px = image::load_from_memory(&blob.bytes).unwrap().to_rgb8().get_pixel(0, 0).0; + 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_rgb8() + .get_pixel(0, 0) + .0; assert!(close(&px, &shown, 3), "{px:?} vs {shown:?}"); // JPEG compression: a CMYK JPEG (Adobe's inverted samples, undone by the Decode array). let (w, blob, warnings) = first(json!({"compression": {"color": {"compression": "jpeg", "quality": "maximum"}}})); @@ -482,11 +518,10 @@ fn cmyk_profile(edit: impl FnOnce(&mut Vec)) -> Vec { /// `inks` (four bytes a pixel) as a CMYK JPEG carrying `icc` in its `ICC_PROFILE` segments. fn cmyk_jpeg_with(inks: &[u8], w: u16, h: u16, icc: &[u8]) -> Vec { - let mut out = Vec::new(); - let mut e = jpeg_encoder::Encoder::new(&mut out, 100); - e.add_icc_profile(icc).unwrap(); - e.encode(inks, w, h, jpeg_encoder::ColorType::Cmyk).unwrap(); - out + let mut img = craft_image_codecs::Image::from_u8(u32::from(w), u32::from(h), craft_image_codecs::ChannelLayout::Cmyk, inks.to_vec()).unwrap(); + img.icc = Some(icc.to_vec()); + let opts = craft_image_codecs::EncodeOptions { jpeg_quality: 100, embed_icc: true, embed_metadata: false, ..Default::default() }; + craft_image_codecs::encode(&img, craft_image_codecs::Format::Jpeg, &opts).unwrap() } /// A CMYK TIFF of `w` × `h` pixels of `ink` carrying `icc` as its tag 34675 (written as Open @@ -908,7 +943,41 @@ fn export_smasks(d: &Document) -> (Vec, Vec>>) { fn png(img: impl Into) -> Vec { let mut out = Vec::new(); - img.into().write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 } @@ -1185,7 +1254,24 @@ fn freeform_gradients_of_lab_points_are_written_as_their_lab_mix() { let out = export_with_report(&d, &opts(json!({}))).unwrap(); assert_eq!(written(&out.bytes)[0].space, "DeviceRGB"); let back = import(&out.bytes).unwrap(); - let px = image::load_from_memory(&all_images(&back)[0].bytes).unwrap().to_rgba8(); + let px = craft_image_codecs::decode(&all_images(&back)[0].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(); let got = px.get_pixel(px.width() / 2, px.height() / 2).0; let want = Color::lab(60.0, 0.0, 0.0).to_rgba8(1.0); assert!(close(&got, &want, 6), "{got:?} vs {want:?}"); diff --git a/crates/pdf/src/tests/colorize.rs b/crates/pdf/src/tests/colorize.rs index 207c9fc595..004f8f04ec 100644 --- a/crates/pdf/src/tests/colorize.rs +++ b/crates/pdf/src/tests/colorize.rs @@ -19,7 +19,41 @@ fn doc(mode: ColorMode, colorize: Option) -> Document { d.swatches.push(Swatch { name: "Ink".into(), paint: Paint::solid(Color::cmyk(0.0, 1.0, 1.0, 0.0)), global: true, spot: true }); let gray = image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap(); let mut png = vec![]; - gray.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = gray.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(); d.images.insert("pic".into(), ImageBlob::png(png)); let im = ImageObject { key: "pic".into(), width: 2, height: 1, xf: Affine::scale(20.0), link: None, placement: Default::default(), pixels: None }; let mut n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); @@ -110,7 +144,41 @@ fn colorized_images_are_downsampled() { let mut d = Document::new(100.0, 100.0); let gray = image::GrayImage::from_fn(600, 600, |x, y| image::Luma([((x + y) % 200) as u8])); let mut png = vec![]; - gray.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = gray.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(); d.images.insert("pic".into(), ImageBlob::png(png)); // One inch wide: 600 ppi. let im = ImageObject { @@ -141,7 +209,41 @@ fn a_colorized_warped_image_is_written_once_for_all_its_pieces() { let mut d = Document::new(100.0, 100.0); let gray = image::GrayImage::from_fn(600, 600, |x, y| image::Luma([((x + y) % 200) as u8])); let mut png = vec![]; - gray.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = gray.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(); d.images.insert("pic".into(), ImageBlob::png(png)); let im = ImageObject { key: "pic".into(), @@ -208,11 +310,10 @@ fn separations_print_a_color_masked_image_as_it_shows() { let spot = Paint::Solid { color: Color::cmyk(0.0, 1.0, 1.0, 0.0), swatch: Some("Ink".into()), tint: 1.0 }; let mut d = doc(ColorMode::Cmyk, Some(spot)); // The black pixel hidden. - let mut png = vec![]; - image::GrayAlphaImage::from_raw(2, 1, vec![0, 0, 255, 255]) - .unwrap() - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + let img = + craft_image_codecs::Image::from_raw(2, 1, craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, vec![0, 0, 255, 255]) + .unwrap(); + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); d.images.insert("shown".into(), ImageBlob::png(png)); let id = d.layers[0].children().unwrap()[0].id; d.node_mut(id).unwrap().extras_mut().color_mask = Some(Box::new(vectorcraft_doc::color_mask::ColorMask { @@ -243,11 +344,10 @@ fn separations_colorize_masked_pixels_whose_own_pixels_are_a_preview() { let mut d = doc(ColorMode::Cmyk, Some(spot)); let preview = Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap()); d.images.insert("pic".into(), ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) }); - let mut png = vec![]; - image::GrayAlphaImage::from_raw(2, 1, vec![0, 0, 255, 255]) - .unwrap() - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + let img = + craft_image_codecs::Image::from_raw(2, 1, craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, vec![0, 0, 255, 255]) + .unwrap(); + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); d.images.insert("shown".into(), ImageBlob::png(png)); let id = d.layers[0].children().unwrap()[0].id; d.node_mut(id).unwrap().extras_mut().color_mask = Some(Box::new(vectorcraft_doc::color_mask::ColorMask { @@ -342,7 +442,23 @@ fn imported_images(d: &Document) -> Vec<(Option, Vec)> { l.walk(&mut |n| { if let NodeKind::Image(im) = &n.kind { let blob = d.images.get(&im.key).unwrap(); - let gray = image::load_from_memory(&blob.bytes).unwrap(); + let gray = 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(); assert_eq!(gray.color(), image::ColorType::L8, "a grayscale image"); out.push((n.extras().colorize.as_deref().cloned(), gray.into_luma8().into_raw())); } @@ -506,8 +622,9 @@ fn a_separation_image_drawn_twice_is_colorized_twice() { /// A one-component JPEG in a Separation space is read through its decoder. #[test] fn a_separation_jpeg_opens_colorized_by_its_ink() { - let mut jpeg = vec![]; - jpeg_encoder::Encoder::new(&mut jpeg, 100).encode(&[0, 0, 255, 255, 0, 0, 255, 255], 8, 1, jpeg_encoder::ColorType::Luma).unwrap(); + let img = craft_image_codecs::Image::from_u8(8, 1, craft_image_codecs::ChannelLayout::Gray, vec![0, 0, 255, 255, 0, 0, 255, 255]).unwrap(); + let opts = craft_image_codecs::EncodeOptions { jpeg_quality: 100, embed_icc: false, embed_metadata: false, ..Default::default() }; + let jpeg = craft_image_codecs::encode(&img, craft_image_codecs::Format::Jpeg, &opts).unwrap(); let hex: String = jpeg.iter().map(|b| format!("{b:02X}")).collect(); let d = separation_page(SPOT_RED, 8, 8, "/Filter [/ASCIIHexDecode /DCTDecode]", &hex, &[]); let images = imported_images(&d); diff --git a/crates/pdf/src/tests/import_fidelity.rs b/crates/pdf/src/tests/import_fidelity.rs index abb15552da..251cc925bf 100644 --- a/crates/pdf/src/tests/import_fidelity.rs +++ b/crates/pdf/src/tests/import_fidelity.rs @@ -112,7 +112,24 @@ fn mask_image_pixels(s: &str) -> [[u8; 4]; 2] { } }); let [key] = keys.as_slice() else { panic!("one image in the mask art: {keys:?}") }; - let px = image::load_from_memory(&d.images[key].bytes).unwrap().to_rgba8(); + let px = craft_image_codecs::decode(&d.images[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(); [px.get_pixel(0, 0).0, px.get_pixel(1, 0).0] } diff --git a/crates/pdf/src/tests/output.rs b/crates/pdf/src/tests/output.rs index e0f00dc0e7..71461ae1f8 100644 --- a/crates/pdf/src/tests/output.rs +++ b/crates/pdf/src/tests/output.rs @@ -1,7 +1,6 @@ //! Save PDF › Output: colours converted to the destination (or their numbers preserved), ICC //! profiles tagging them, images converted too, and the output intent and Trapped entries. -use std::io::Cursor; use std::sync::Arc; use craft_pdf::syntax::Pdf; @@ -429,11 +428,9 @@ fn tagged_cmyk_documents_blend_in_the_cmyk_profile_space() { /// A 4 × 4 PNG of one colour. fn png(rgb: [u8; 3]) -> Vec { - let mut out = Vec::new(); - image::DynamicImage::from(image::RgbImage::from_pixel(4, 4, image::Rgb(rgb))) - .write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png) + let img = craft_image_codecs::Image::from_raw(4, 4, craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, rgb.repeat(16)) .unwrap(); - out + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() } fn image_doc(bytes: Vec) -> Document { @@ -451,7 +448,26 @@ fn image_doc(bytes: Vec) -> Document { fn first_pixel(bytes: &[u8]) -> [u8; 3] { let back = import(bytes).unwrap(); let blob = back.images.values().next().unwrap(); - image::load_from_memory(&blob.bytes).unwrap().to_rgb8().get_pixel(0, 0).0 + 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_rgb8() + .get_pixel(0, 0) + .0 } #[test] diff --git a/crates/pdf/src/tests/pdfx.rs b/crates/pdf/src/tests/pdfx.rs index ec22eb0186..2003a6b7c6 100644 --- a/crates/pdf/src/tests/pdfx.rs +++ b/crates/pdf/src/tests/pdfx.rs @@ -113,7 +113,41 @@ fn pdfx_1a_files_have_no_rgb() { let png = { let img = image::RgbaImage::from_pixel(4, 4, image::Rgba([10, 200, 30, 255])); let mut out = std::io::Cursor::new(vec![]); - img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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.get_mut().extend_from_slice(&__b)) + } + .unwrap(); out.into_inner() }; d.images.insert("img".into(), ImageBlob::new("image/png", png)); diff --git a/crates/pdf/src/tests/webview.rs b/crates/pdf/src/tests/webview.rs index 6fc50d0d54..9c0a3e8752 100644 --- a/crates/pdf/src/tests/webview.rs +++ b/crates/pdf/src/tests/webview.rs @@ -3,9 +3,9 @@ //! linearisation checker does), also when encrypted; with both off the export is unchanged. use std::collections::{HashMap, HashSet}; -use std::io::{Cursor, Read}; +use std::io::Read; -use image::{DynamicImage, ImageFormat}; +use image::DynamicImage; use serde_json::json; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, Artboard, Document, ImageBlob, ImageObject, Node, NodeKind}; @@ -35,9 +35,41 @@ fn doc(n: usize, image: bool, on_first: bool) -> Document { }); } let mut png = vec![]; - DynamicImage::from(image::RgbImage::from_fn(8, 8, |x, y| image::Rgb([(x * 30) as u8, (y * 30) as u8, 90]))) - .write_to(&mut Cursor::new(&mut png), ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = DynamicImage::from(image::RgbImage::from_fn(8, 8, |x, y| image::Rgb([(x * 30) as u8, (y * 30) as u8, 90]))); + 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(); d.images.insert("img".into(), ImageBlob::new("image/png", png)); let layer = d.default_layer().unwrap(); for i in 0..n { diff --git a/crates/plugins/Cargo.toml b/crates/plugins/Cargo.toml index ef21a57ef4..28b972d679 100644 --- a/crates/plugins/Cargo.toml +++ b/crates/plugins/Cargo.toml @@ -16,7 +16,7 @@ log = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } # The pixels of a small image a filter asks to read, as RGBA in base64. -image = { workspace = true } +craft-image-codecs = { workspace = true } craft-vectorcraft-format = { workspace = true } # The SHA-256 of a module, which the install prompt shows and a grant records. sha2 = { version = "0.10", default-features = false } diff --git a/crates/plugins/src/objects.rs b/crates/plugins/src/objects.rs index 192ed24a96..08689b7235 100644 --- a/crates/plugins/src/objects.rs +++ b/crates/plugins/src/objects.rs @@ -459,9 +459,8 @@ fn color_mode(b: &ImageBlob) -> &'static str { if b.gray_source().is_some() { return "gray"; } - let readable = - image::ImageReader::new(std::io::Cursor::new(b.bytes.as_slice())).with_guessed_format().ok().and_then(|r| r.into_dimensions().ok()); - if readable.is_some() { "rgb" } else { "unknown" } + let readable = vectorcraft_doc::header_size(&b.bytes).is_some() || b.header_size().is_some(); + if readable { "rgb" } else { "unknown" } } #[cfg(test)] @@ -481,8 +480,7 @@ fn rgba_pixels(b: &ImageBlob, w: u32, h: u32, max: usize, charged: &mut usize) - return None; } let cmyk = b.is_cmyk(); - let reader = || image::ImageReader::new(std::io::Cursor::new(b.bytes.as_slice())).with_guessed_format().ok(); - let size = if cmyk { b.header_size()? } else { reader()?.into_dimensions().ok()? }; + let size = if cmyk { b.header_size()? } else { vectorcraft_doc::header_size(&b.bytes).or_else(|| b.header_size())? }; if size != (w, h) { return None; } @@ -492,13 +490,11 @@ fn rgba_pixels(b: &ImageBlob, w: u32, h: u32, max: usize, charged: &mut usize) - if cmyk { return cmyk_rgba(b, w, h); } - let mut r = reader()?; - let mut limits = image::Limits::default(); + let mut opts = craft_image_codecs::DecodeOptions::default(); // The decoder's own buffers besides the RGBA it gives. - limits.max_alloc = Some(64 << 20); - r.limits(limits); - let img = r.decode().ok()?.into_rgba8(); - (img.dimensions() == (w, h)).then(|| img.into_raw()) + opts.limits.max_alloc = 64 << 20; + let img = craft_image_codecs::decode_with(&b.bytes, &opts).ok()?; + (img.dimensions() == (w, h)).then(|| img.to_rgba8()) } /// The inks → XYZ table of [`cmyk_rgba`] and the color settings it was built with. diff --git a/crates/plugins/src/objects/tests.rs b/crates/plugins/src/objects/tests.rs index 5fb48cf396..99e3088840 100644 --- a/crates/plugins/src/objects/tests.rs +++ b/crates/plugins/src/objects/tests.rs @@ -450,10 +450,14 @@ fn bad_stroke_styles_and_effect_records_are_refused() { /// A `w` × `h` PNG whose pixels vary with their column, half transparent. fn png(w: u32, h: u32) -> Vec { - let img = image::RgbaImage::from_fn(w, h, |x, y| image::Rgba([(x * 100) as u8, (y * 7) as u8, 30, 128])); - let mut out = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); - out + let mut data = Vec::with_capacity((w * h * 4) as usize); + for y in 0..h { + for x in 0..w { + data.extend_from_slice(&[(x * 100) as u8, (y * 7) as u8, 30, 128]); + } + } + let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, data).unwrap(); + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() } /// An image object `w` × `h` pixels showing blob `key`, linked to `link`. @@ -590,8 +594,12 @@ fn declared_embedded_and_linked_images_have_distinct_metadata_and_pixel_omission let id = d.insert(Some(layer), usize::MAX, n).unwrap(); assert_eq!(encode_read_only(&d, d.node(id).unwrap()).unwrap()["pixelsOmitted"], json!(true), "too large to count"); // Gray pixels, and data that isn't an image. - let mut gray = vec![]; - image::GrayImage::from_pixel(2, 2, image::Luma([90])).write_to(&mut std::io::Cursor::new(&mut gray), image::ImageFormat::Png).unwrap(); + let gray = craft_image_codecs::encode( + &craft_image_codecs::Image::from_raw(2, 2, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, vec![90; 4]).unwrap(), + craft_image_codecs::Format::Png, + &craft_image_codecs::EncodeOptions::default(), + ) + .unwrap(); for (blob, mode) in [(ImageBlob::png(gray), "gray"), (ImageBlob::png(b"not an image".to_vec()), "unknown")] { d.images.insert("x".into(), blob); let n = image_node(&mut d, "x", (2, 2), None); diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index ecdaa60273..61569cc79e 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -19,12 +19,11 @@ vello_cpu = { workspace = true } # Filter types (Gaussian blur, drop shadow) are not re-exported by vello_cpu 0.2. vello_common = { version = "0.2", default-features = false } image = { workspace = true } +craft-gif = { workspace = true } craft-image-codecs = { workspace = true } -flate2 = { workspace = true } jpeg-encoder = { workspace = true } -gif = { workspace = true } -# TIFF LZW compression (MIT OR Apache-2.0; already used by the image crate's TIFF reader). -weezl = "0.2" +craft-stream-codecs = { workspace = true } +flate2 = { workspace = true } log = { workspace = true } # Combining marks inside a lam-alef cluster (MIT OR Apache-2.0; already used by vectorcraft-text). unicode-general-category = "1" @@ -38,6 +37,8 @@ vello_cpu = { workspace = true, features = ["multithreading"] } winsafe = { version = "0.0.29", default-features = false, features = ["kernel"] } [dev-dependencies] +# The TIFF LZW writer before craft-stream-codecs, the reference encode/tests_tiff.rs compares it with. +weezl = "0.2" vectorcraft-testkit = { workspace = true } # A variable font built in code (no font file is committed). vectorcraft-text = { workspace = true, features = ["test-fonts"] } @@ -45,7 +46,7 @@ vectorcraft-text = { workspace = true, features = ["test-fonts"] } vectorcraft-plugins = { workspace = true } wat = { workspace = true } # Decoders the export tests read their files back with. -image = { workspace = true, features = ["tga"] } +image = { workspace = true } craft-tiff = { workspace = true } craft-psd = { workspace = true } proptest = { workspace = true } diff --git a/crates/render/src/blobs.rs b/crates/render/src/blobs.rs index ab5d831a0b..4378494d32 100644 --- a/crates/render/src/blobs.rs +++ b/crates/render/src/blobs.rs @@ -42,13 +42,7 @@ pub(crate) fn blob_pixmap(blob: &vectorcraft_doc::ImageBlob, touch: bool) -> Opt // Decoded outside the lock: other renderers carry on meanwhile. The inks and the pixels // shown from them are admitted together, as other images are, before either is made: // without room the image is read as other images are (which reduces it). - let room = || { - image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice())) - .with_guessed_format() - .ok() - .and_then(|r| r.into_dimensions().ok()) - .is_some_and(|(w, h)| paint::within_allowance(w, h.saturating_mul(2))) - }; + let room = || blob.header_size().is_some_and(|(w, h)| paint::within_allowance(w, h.saturating_mul(2))); let pm = match lut.filter(|_| room()).and_then(|lut| ink::cmyk_pixmap(blob, &lut)) { Some(pm) => pm, None => match paint::decode_pixmap_or_why(&blob.bytes) { diff --git a/crates/render/src/encode.rs b/crates/render/src/encode.rs index decff12a65..891c325c75 100644 --- a/crates/render/src/encode.rs +++ b/crates/render/src/encode.rs @@ -186,11 +186,16 @@ pub fn on_white(p: &[u8; 4]) -> [u8; 3] { /// Lossless WebP. pub(crate) fn webp(img: &Rendered) -> Result, String> { - let mut buf = Vec::new(); - let enc = image::codecs::webp::WebPEncoder::new_lossless(&mut buf); - image::ImageEncoder::write_image(enc, &img.to_straight(), img.width, img.height, image::ExtendedColorType::Rgba8) - .map_err(|e| format!("WebP encoding failed: {e}"))?; - Ok(buf) + let src = craft_image_codecs::Image::from_raw( + img.width, + img.height, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + img.to_straight(), + ) + .map_err(|e| format!("WebP encoding failed: {e}"))?; + let opts = craft_image_codecs::EncodeOptions { webp_lossless: true, ..craft_image_codecs::EncodeOptions::default() }; + craft_image_codecs::encode(&src, craft_image_codecs::Format::WebP, &opts).map_err(|e| format!("WebP encoding failed: {e}")) } /// Bounds of the art an export draws: visible objects off template layers (guides left out), diff --git a/crates/render/src/encode/gif.rs b/crates/render/src/encode/gif.rs index 3d9760895c..4ca0e92a45 100644 --- a/crates/render/src/encode/gif.rs +++ b/crates/render/src/encode/gif.rs @@ -1,33 +1,21 @@ //! GIF export: a palette image ([`super::quantize`]) as a one-frame GIF89a with its transparent //! entry, optionally interlaced (rows in four passes, so the image builds up while it loads). -use std::borrow::Cow; - use super::quantize::Indexed; /// Encode `img` as a GIF file. pub fn encode(img: &Indexed, interlaced: bool) -> Result, String> { - let fail = |e: gif::EncodingError| format!("GIF encoding failed: {e}"); - let (Ok(w), Ok(h)) = (u16::try_from(img.width), u16::try_from(img.height)) else { + if img.width > u32::from(u16::MAX) || img.height > u32::from(u16::MAX) { return Err(format!("{} × {} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution", img.width, img.height)); - }; - if w == 0 || h == 0 || img.indices.len() != w as usize * h as usize || img.palette.is_empty() || img.palette.len() > 256 { + } + if img.width == 0 + || img.height == 0 + || img.indices.len() != img.width as usize * img.height as usize + || img.palette.is_empty() + || img.palette.len() > 256 + { return Err("GIF encoding failed: the palette image is malformed".into()); } - let buffer = if interlaced { Cow::Owned(interlace(&img.indices, w as usize)) } else { Cow::Borrowed(img.indices.as_slice()) }; - let mut enc = gif::Encoder::new(Vec::new(), w, h, &img.palette.concat()).map_err(fail)?; - let frame = gif::Frame { width: w, height: h, buffer, transparent: img.transparent, interlaced, ..gif::Frame::default() }; - enc.write_frame(&frame).map_err(fail)?; - enc.into_inner().map_err(fail) -} - -/// The rows of a `width`-wide image in GIF's interlaced order: every 8th row from 0, every 8th -/// from 4, every 4th from 2, then every 2nd from 1. -fn interlace(px: &[u8], width: usize) -> Vec { - let rows: Vec<&[u8]> = px.chunks(width.max(1)).collect(); - [(0, 8), (4, 8), (2, 4), (1, 2)] - .into_iter() - .flat_map(|(start, step)| rows.iter().skip(start).step_by(step)) - .flat_map(|r| r.iter().copied()) - .collect() + craft_gif::write::encode_indexed(img.width, img.height, &img.palette, &img.indices, img.transparent, interlaced) + .map_err(|e| format!("GIF encoding failed: {e}")) } diff --git a/crates/render/src/encode/tests.rs b/crates/render/src/encode/tests.rs index 0a8227b75f..92c257d2dd 100644 --- a/crates/render/src/encode/tests.rs +++ b/crates/render/src/encode/tests.rs @@ -32,7 +32,25 @@ fn noise(w: u32, h: u32, opaque: bool) -> Vec { } fn decode(png: &[u8]) -> Vec { - image::load_from_memory_with_format(png, image::ImageFormat::Png).expect("decodes").to_rgba8().into_raw() + 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()), + } + }) + .expect("decodes") + .to_rgba8() + .into_raw() } #[test] @@ -73,7 +91,27 @@ fn png_refuses_a_buffer_of_the_wrong_size() { #[test] fn gray_and_bilevel_images_store_gray() { let header = |file: &[u8]| (file[24], file[25]); - let gray = |file: &[u8]| image::load_from_memory(file).unwrap().to_luma_alpha8().into_raw(); + let gray = |file: &[u8]| { + craft_image_codecs::decode(file) + .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() + .into_raw() + }; // 3 × 2, premultiplied: black, red, light grey; white, mid grey, almost black. let mut img = Rendered { width: 3, @@ -116,7 +154,24 @@ fn circle_doc() -> Document { fn export(d: &Document, format: RasterFormat, o: &RasterExportOptions) -> image::RgbaImage { let bytes = Renderer::new().export_region(d, d.artboards[0].rect, format, o).unwrap(); - 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() } #[test] @@ -175,7 +230,24 @@ fn translucent_edges_over_opaque_art_stay_opaque() { (&d, RasterExportOptions { ppi: 72.0 * 0.3515625, ..Default::default() }), ] { let png = Renderer::new().export_region(doc, doc.artboards[0].rect, RasterFormat::Png, &o).unwrap(); - let img = image::load_from_memory(&png).unwrap().to_rgba8(); + 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() + .to_rgba8(); let below: Vec<_> = img.pixels().filter(|p| p[3] < 255).collect(); assert!(below.is_empty(), "ppi {}: {} pixels below alpha 255, e.g. {:?}", o.ppi, below.len(), below.first()); assert_eq!(png[25], 2, "IHDR colour type: RGB"); diff --git a/crates/render/src/encode/tests_bmp.rs b/crates/render/src/encode/tests_bmp.rs index 659c00d147..f458c1999b 100644 --- a/crates/render/src/encode/tests_bmp.rs +++ b/crates/render/src/encode/tests_bmp.rs @@ -23,8 +23,25 @@ pub(super) fn art(w: u32, h: u32) -> Vec { px } -pub(super) fn decode(file: &[u8], format: image::ImageFormat) -> image::RgbaImage { - image::load_from_memory_with_format(file, format).expect("decodes").to_rgba8() +pub(super) fn decode(file: &[u8], format: craft_image_codecs::Format) -> image::RgbaImage { + craft_image_codecs::decode_as(format, file) + .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()), + } + }) + .expect("decodes") + .to_rgba8() } fn bmp(px: &[u8], w: u32, h: u32, o: &BmpOptions) -> Vec { @@ -41,7 +58,7 @@ fn every_depth_writes_its_bit_count_and_decodes() { assert_eq!(u32_at(&file, 2) as usize, file.len(), "file size"); assert_eq!(u16_at(&file, 28), u16::from(depth), "bit count"); assert_eq!(u32_at(&file, 38), pixels_per_metre(150.0), "resolution"); - let img = decode(&file, image::ImageFormat::Bmp); + let img = decode(&file, craft_image_codecs::Format::Bmp); assert_eq!(img.dimensions(), (w, h)); let got = img.get_pixel(5, 3).0; let want = on_white(px[(3 * w as usize + 5) * 4..][..4].try_into().unwrap()); @@ -71,13 +88,13 @@ fn rle8_and_rle4_decode_like_uncompressed() { assert_eq!(u32_at(&rle, 30), if depth == 8 { 1 } else { 2 }, "BI_RLE8 / BI_RLE4"); assert_eq!(u32_at(&rle, 34) as usize, rle.len() - u32_at(&rle, 10) as usize, "the compressed size"); assert!(rle.len() < plain.len(), "{} vs {}", rle.len(), plain.len()); - assert_eq!(decode(&rle, image::ImageFormat::Bmp), decode(&plain, image::ImageFormat::Bmp), "depth {depth}"); + assert_eq!(decode(&rle, craft_image_codecs::Format::Bmp), decode(&plain, craft_image_codecs::Format::Bmp), "depth {depth}"); } // Rows of many different pixels go in absolute mode. let noisy: Vec = (0..40u32 * 4).flat_map(|i| [(i * 37 % 256) as u8, (i * 91 % 256) as u8, (i * 13 % 256) as u8, 255]).collect(); let plain = bmp(&noisy, 40, 4, &BmpOptions { depth: 8, ..Default::default() }); let rle = bmp(&noisy, 40, 4, &BmpOptions { depth: 8, rle: true, ..Default::default() }); - assert_eq!(decode(&rle, image::ImageFormat::Bmp), decode(&plain, image::ImageFormat::Bmp)); + assert_eq!(decode(&rle, craft_image_codecs::Format::Bmp), decode(&plain, craft_image_codecs::Format::Bmp)); } #[test] @@ -91,7 +108,7 @@ fn flipped_rows_have_a_negative_height() { let offset = u32_at(&down, 10) as usize; // Top-down: the first row stored is the image's first (its transparent pixel, on white). assert_eq!(&down[offset..offset + 3], &[255, 255, 255]); - assert_eq!(decode(&up, image::ImageFormat::Bmp), decode(&down, image::ImageFormat::Bmp)); + assert_eq!(decode(&up, craft_image_codecs::Format::Bmp), decode(&down, craft_image_codecs::Format::Bmp)); } #[test] @@ -106,7 +123,7 @@ fn os2_bitmaps_have_a_core_header() { let entries = if depth <= 8 { 1 << depth } else { 0 }; assert_eq!(u32_at(&file, 10), 14 + 12 + entries * 3); let windows = bmp(&px, w, h, &BmpOptions { depth, ..Default::default() }); - assert_eq!(decode(&file, image::ImageFormat::Bmp), decode(&windows, image::ImageFormat::Bmp), "depth {depth}"); + assert_eq!(decode(&file, craft_image_codecs::Format::Bmp), decode(&windows, craft_image_codecs::Format::Bmp), "depth {depth}"); } } @@ -115,7 +132,7 @@ fn greys_and_impossible_combinations() { let (w, h) = (8, 2); let px = art(w, h); for depth in [8, 24] { - let img = decode(&bmp(&px, w, h, &BmpOptions { depth, gray: true, ..Default::default() }), image::ImageFormat::Bmp); + let img = decode(&bmp(&px, w, h, &BmpOptions { depth, gray: true, ..Default::default() }), craft_image_codecs::Format::Bmp); assert!(img.pixels().all(|p| p[0] == p[1] && p[1] == p[2]), "depth {depth}: greys"); } let bad = [ diff --git a/crates/render/src/encode/tests_jpeg.rs b/crates/render/src/encode/tests_jpeg.rs index 2bba70330e..413781de13 100644 --- a/crates/render/src/encode/tests_jpeg.rs +++ b/crates/render/src/encode/tests_jpeg.rs @@ -108,7 +108,23 @@ fn methods_write_baseline_or_progressive_frames() { assert_eq!(frame(&p3).0, 0xC2, "SOF2"); assert!(sos(&p3) > 1 && sos(&p5) > sos(&p3), "more scans: {} {}", sos(&p3), sos(&p5)); for f in [&base, &p3, &p5] { - let back = image::load_from_memory(f).unwrap(); + let back = craft_image_codecs::decode(f) + .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!((back.width(), back.height()), (40, 30)); } } @@ -184,7 +200,24 @@ fn cmyk_exports_keep_the_inks_of_cmyk_colours() { assert!(red[1] > 200 && red[2] > 200 && red[0] < 40, "RGB red separates to magenta and yellow: {red:?}"); let file = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::Jpeg, &o).unwrap(); assert_eq!(frame(&file).1, 4, "4 components"); - let back = image::load_from_memory(&file).unwrap().to_rgb8(); + let back = craft_image_codecs::decode(&file) + .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(); assert!(back.get_pixel(3, 5).0.iter().all(|v| *v < 60), "black reads back dark: {:?}", back.get_pixel(3, 5)); let r = back.get_pixel(15, 5).0; assert!(r[0] > 180 && r[1] < 90, "red reads back red: {r:?}"); @@ -196,7 +229,24 @@ fn gray_exports_keep_the_lightness() { let o = RasterExportOptions { jpeg: JpegOptions { color_model: ColorModel::Gray, ..Default::default() }, ..Default::default() }; let file = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::Jpeg, &o).unwrap(); assert_eq!(frame(&file).1, 1); - let back = image::load_from_memory(&file).unwrap().to_luma8(); + let back = craft_image_codecs::decode(&file) + .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(); let red = back.get_pixel(15, 5)[0]; // sRGB red's relative luminance 0.2126, encoded: about 127. assert!((115..=140).contains(&red), "{red}"); diff --git a/crates/render/src/encode/tests_palette.rs b/crates/render/src/encode/tests_palette.rs index f06217f397..836b5fcf09 100644 --- a/crates/render/src/encode/tests_palette.rs +++ b/crates/render/src/encode/tests_palette.rs @@ -141,7 +141,24 @@ fn transparent_pixels_get_their_own_entry() { let file = encode_indexed(&ix, &PngOptions::default()).unwrap(); assert_eq!(chunk(&file, b"tRNS").unwrap(), [0]); - let back = image::load_from_memory(&file).unwrap().to_rgba8(); + let back = craft_image_codecs::decode(&file) + .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!(back.get_pixel(0, 0).0, [255, 0, 0, 255]); assert_eq!(back.get_pixel(1, 0)[3], 0); } @@ -154,7 +171,24 @@ fn png8_decodes_at_every_bit_depth_and_interlaced() { for interlaced in [false, true] { let file = encode_indexed(&ix, &PngOptions { ppi: Some(144.0), interlaced }).unwrap(); assert_eq!((file[24], file[25], file[28]), (depth, 3, u8::from(interlaced))); - let back = image::load_from_memory(&file).unwrap().to_rgb8(); + let back = craft_image_codecs::decode(&file) + .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(); let want: Vec = colours(&ix).into_iter().flatten().collect(); assert_eq!(back.into_raw(), want, "{colors} colours, interlaced {interlaced}"); assert!(chunk(&file, b"pHYs").is_some()); @@ -169,7 +203,24 @@ fn gif_decodes() { for interlaced in [false, true] { let file = gif::encode(&ix, interlaced).unwrap(); assert_eq!(&file[..6], b"GIF89a"); - let back = image::load_from_memory_with_format(&file, image::ImageFormat::Gif).unwrap().to_rgba8(); + let back = craft_image_codecs::decode_as(craft_image_codecs::Format::Gif, &file) + .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!(back.dimensions(), (21, 17)); for (i, p) in back.pixels().enumerate() { match ix.indices[i] { diff --git a/crates/render/src/encode/tests_tga.rs b/crates/render/src/encode/tests_tga.rs index 3f720443aa..2851a25873 100644 --- a/crates/render/src/encode/tests_tga.rs +++ b/crates/render/src/encode/tests_tga.rs @@ -14,7 +14,7 @@ fn targa_depths_alpha_and_footer() { assert_eq!((u16_at(&file, 12), u16_at(&file, 14)), (7, 3)); assert_eq!(file.len(), 18 + (w * h) as usize * usize::from(depth / 8) + 26); assert!(file.ends_with(b"TRUEVISION-XFILE.\0")); - let img = decode(&file, image::ImageFormat::Tga); + let img = decode(&file, craft_image_codecs::Format::Tga); assert_eq!(img.dimensions(), (w, h)); let want = on_white(px[(2 * w as usize + 3) * 4..][..4].try_into().unwrap()); let got = img.get_pixel(3, 2).0; diff --git a/crates/render/src/encode/tests_tiff.rs b/crates/render/src/encode/tests_tiff.rs index e10739e67a..392e4ed6d2 100644 --- a/crates/render/src/encode/tests_tiff.rs +++ b/crates/render/src/encode/tests_tiff.rs @@ -202,3 +202,33 @@ fn packbits_round_trips() { assert_eq!(out, data); } } + +/// TIFF's LZW strips through craft-stream-codecs (#778) read back as the strip they were made of +/// with weezl, the writer before them, and take no more bytes than weezl's: the same bytes until +/// the code table first fills, after which the two clear it at different codes. +#[test] +fn lzw_strips_read_back_as_weezl_reads_them() { + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut noise = |n: usize, spread: u64| { + (0..n) + .map(|_| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % spread) as u8 + }) + .collect::>() + }; + let strips = + [vec![], vec![7], vec![0; 70_000], noise(8_192, 256), noise(65_536, 4), noise(200_000, 256), (0..=255).cycle().take(30_000).collect()]; + for strip in &strips { + let weezl = weezl::encode::Encoder::with_tiff_size_switch(weezl::BitOrder::Msb, 8).encode(strip).unwrap(); + let craft = craft_stream_codecs::lzw::encode(strip, true); + let back = weezl::decode::Decoder::with_tiff_size_switch(weezl::BitOrder::Msb, 8).decode(&craft).unwrap(); + assert!(back == *strip, "{} bytes read back", strip.len()); + assert!(craft.len() <= weezl.len(), "{} bytes: {} against {}", strip.len(), craft.len(), weezl.len()); + // Up to the first table reset (4,093 codes of at most 12 bits) the codes are the same. + let same = craft.iter().zip(&weezl).take_while(|(a, b)| a == b).count(); + assert!(same >= weezl.len().min(4_300), "{} bytes: the same for {same}", strip.len()); + } +} diff --git a/crates/render/src/encode/tests_web.rs b/crates/render/src/encode/tests_web.rs index e0e60037fe..10063a5da4 100644 --- a/crates/render/src/encode/tests_web.rs +++ b/crates/render/src/encode/tests_web.rs @@ -95,15 +95,75 @@ fn comments_are_valid_files() { let ix = quantize(&image(5, 4, |x, _| [x as u8 * 40, 0, 0]), 5, 4, &PaletteOptions::default()); let file = gif_comment(gif::encode(&ix, false).unwrap(), &"Copyright: Someone ".repeat(20)); assert!(file.windows(2).any(|w| w == [0x21, 0xFE])); - assert_eq!(image::load_from_memory(&file).unwrap().width(), 5); + assert_eq!( + craft_image_codecs::decode(&file) + .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(), + 5 + ); let px = vec![200u8; 5 * 4 * 3]; let jpg = jpeg::encode(&px, 5, 4, 80, Some(72.0), &jpeg::JpegOptions::default()).unwrap(); let with = jpeg_comment(jpg.clone(), "Copyright: Someone"); assert_eq!(with.len(), jpg.len() + 4 + 18); assert!(with.windows(2).any(|w| w == [0xFF, 0xFE])); - assert_eq!(image::load_from_memory(&with).unwrap().height(), 4); + assert_eq!( + craft_image_codecs::decode(&with) + .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() + .height(), + 4 + ); assert_eq!(jpeg_comment(vec![1, 2, 3], "x"), vec![1, 2, 3], "not a JPEG"); let png = png::with_srgb(png::encode(&[0, 0, 0, 255], 1, 1, &png::PngOptions::default()).unwrap()); assert!(png.windows(4).any(|w| w == b"sRGB")); - assert_eq!(image::load_from_memory(&png).unwrap().width(), 1); + 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(), + 1 + ); } diff --git a/crates/render/src/encode/tiff.rs b/crates/render/src/encode/tiff.rs index da8577c9b8..6a01f78109 100644 --- a/crates/render/src/encode/tiff.rs +++ b/crates/render/src/encode/tiff.rs @@ -192,12 +192,7 @@ pub fn write(img: &Image, l: &Layout) -> Result, String> { offsets.push(strips.len()); match l.compression { Compression::None => strips.extend_from_slice(strip), - Compression::Lzw => { - let lzw = weezl::encode::Encoder::with_tiff_size_switch(weezl::BitOrder::Msb, 8) - .encode(strip) - .map_err(|e| format!("TIFF encoding failed: {e}"))?; - strips.extend(lzw); - } + Compression::Lzw => strips.extend(craft_stream_codecs::lzw::encode(strip, true)), Compression::PackBits => strip.chunks(row).for_each(|r| packbits(r, &mut strips)), } // Strips start on a word boundary. diff --git a/crates/render/src/options.rs b/crates/render/src/options.rs index 7a9a9b81f2..2b540f0125 100644 --- a/crates/render/src/options.rs +++ b/crates/render/src/options.rs @@ -350,11 +350,16 @@ impl Rendered { /// Encode as PNG without metadata (thumbnails, screenshots, embedded rasters; exports use /// [`encode`]). pub fn to_png(&self) -> Result, String> { - let mut buf = Vec::new(); - let img = image::RgbaImage::from_raw(self.width, self.height, self.to_straight()) - .ok_or("PNG encoding failed: pixel buffer doesn't match the image size")?; - img.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png).map_err(|e| format!("PNG encoding failed: {e}"))?; - Ok(buf) + let img = craft_image_codecs::Image::from_raw( + self.width, + self.height, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + self.to_straight(), + ) + .map_err(|e| format!("PNG encoding failed: {e}"))?; + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map_err(|e| format!("PNG encoding failed: {e}")) } /// Each pixel's grey level and alpha: the Rec. 709 luma of its straight colour, with `bilevel` /// black below 128 and white from there up. A clear pixel is white: no ink where a fill diff --git a/crates/render/src/paint.rs b/crates/render/src/paint.rs index 8650ae7886..c4c68a596c 100644 --- a/crates/render/src/paint.rs +++ b/crates/render/src/paint.rs @@ -157,30 +157,72 @@ pub fn image_decodes() -> u64 { /// [`decode_in_room`]'s image or error. #[cfg(test)] -pub(crate) fn decode_within_allowance(bytes: &[u8]) -> image::ImageResult { +pub(crate) fn decode_within_allowance(bytes: &[u8]) -> Result { decode_in_room(bytes).map_err(|(e, _)| e) } +/// Why [`decode_in_room`] gave no image. +#[derive(Debug)] +pub(crate) enum DecodeError { + /// The image takes more than the decode allowance, or than the room the images being painted + /// leave: it may be read at [`reduced_size`]. + Limit(String), + /// Its pixels can't be read. + Unreadable(String), +} + +impl std::fmt::Display for DecodeError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + DecodeError::Limit(why) => write!(f, "the image is too large to decode: {why}"), + DecodeError::Unreadable(why) => write!(f, "the image's pixels can't be read: {why}"), + } + } +} + +/// The formats the renderer draws, told from their bytes: those the image crate read for it +/// before craft-image-codecs did (#778). TGA has no signature to tell it by and was never drawn. +fn drawn_format(bytes: &[u8]) -> Option { + use craft_image_codecs::Format as F; + craft_image_codecs::detect(bytes).filter(|f| matches!(f, F::Png | F::Jpeg | F::Gif | F::WebP | F::Tiff | F::Bmp)) +} + +/// `bytes` decoded as `format` within `allowance` bytes: the pixels as stored, not turned upright, +/// as the image crate gave them. +fn decode_as(format: craft_image_codecs::Format, bytes: &[u8], allowance: u64) -> Result { + vectorcraft_doc::decode::decode_image(format, bytes, allowance).map(|(img, _)| img) +} + /// `bytes` decoded within [`MAX_DECODE_ALLOC`], counted as RGBA: the image's size is read from its /// header first, and an image of more than that as RGBA gets a limit error before anything is /// decoded (#1717). A failure comes with why the image gave no pixels ([`room_for`]). -fn decode_in_room(bytes: &[u8]) -> Result { +fn decode_in_room(bytes: &[u8]) -> Result { let allowance = allowance(); - let unreadable = |e| (e, Undecoded::Unreadable); - let reader = || -> image::ImageResult<_> { - let mut r = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format()?; - let mut limits = image::Limits::default(); - limits.max_alloc = Some(allowance); - r.limits(limits); - Ok(r) + let unreadable = |e: String| (DecodeError::Unreadable(e), Undecoded::Unreadable); + let format = drawn_format(bytes).ok_or_else(|| unreadable("not an image the renderer draws".into()))?; + let (w, h) = match vectorcraft_doc::header_size(bytes) { + Some(size) => size, + None => { + return Err(match craft_image_codecs::probe_size(bytes) { + Err(craft_image_codecs::CodecError::LimitExceeded(e)) => (DecodeError::Limit(e), Undecoded::Unreadable), + Err(e) => unreadable(e.to_string()), + Ok(_) => unreadable("the image's size can't be read".into()), + }); + } }; - let (w, h) = reader().and_then(|r| r.into_dimensions()).map_err(unreadable)?; - let bytes = (u64::from(w) * u64::from(h)).saturating_mul(4); + let rgba = (u64::from(w) * u64::from(h)).saturating_mul(4); let pinned = crate::images::store().pinned_bytes() as u64; - if let Err(why) = room_for(bytes, pinned) { - return Err((image::ImageError::Limits(image::error::LimitError::from_kind(image::error::LimitErrorKind::InsufficientMemory)), why)); + if let Err(why) = room_for(rgba, pinned) { + return Err((DecodeError::Limit(format!("{w} × {h} pixels take {rgba} bytes as RGBA")), why)); } - reader().and_then(|r| r.decode()).map_err(unreadable) + // Within the allowance as RGBA and as decoded, a limit the decoder meets is a file that can't + // hold the pixels its header declares: they can't be read. + let samples_fit = vectorcraft_doc::decode::decoded_layout(bytes, format) + .is_some_and(|(_, _, per_pixel)| (u64::from(w) * u64::from(h)).saturating_mul(per_pixel) <= allowance); + decode_as(format, bytes, allowance).map_err(|e| match e { + craft_image_codecs::CodecError::LimitExceeded(m) if !samples_fit => (DecodeError::Limit(m), Undecoded::Unreadable), + e => unreadable(e.to_string()), + }) } /// Whether an image of `rgba` bytes may be decoded while the images being painted hold `pinned` @@ -240,40 +282,33 @@ struct Reduction { /// [`reduced_size`]'s reading of `bytes` within `allowance`. fn reduction(bytes: &[u8], allowance: u64) -> Option { - use image::ImageDecoder as _; - let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?; - let format = reader.format()?; - if !matches!(format, image::ImageFormat::Png | image::ImageFormat::Jpeg | image::ImageFormat::Gif | image::ImageFormat::WebP) { - return None; - } - let mut limits = image::Limits::default(); - limits.max_alloc = Some(allowance); - reader.limits(limits); - let d = reader.into_decoder().ok()?; - let (w, h) = d.dimensions(); + use craft_image_codecs::Format as F; + let format = drawn_format(bytes).filter(|f| matches!(f, F::Png | F::Jpeg | F::Gif | F::WebP))?; + let (w, h, per_pixel) = vectorcraft_doc::decode::decoded_layout(bytes, format)?; let pixels = u64::from(w) * u64::from(h); + let total_bytes = pixels.saturating_mul(per_pixel); // An image of more pixels than the allowance has bytes (four times what it holds as RGBA) is // not read. - if pixels == 0 || pixels > allowance || (pixels.saturating_mul(4) <= allowance && d.total_bytes() <= allowance) { + if pixels == 0 || pixels > allowance || (pixels.saturating_mul(4) <= allowance && total_bytes <= allowance) { return None; } let to = fitted_dims(w, h, allowance)?; // A PNG that isn't interlaced or animated (and upright in pre-pixel EXIF) is read a row at a time when the reader's buffers fit the allowance. - let row_scratch = if format == image::ImageFormat::Png { + let row_scratch = if format == F::Png { let streamed = craft_image_codecs::PngDecodeRows::new_streaming(bytes, &png_streaming_limits(allowance)) .ok() .filter(|dec| dec.streamable()) .and_then(|dec| png_row_scratch(&dec.header())); - streamed.or_else(|| png_row_scratch_from_header(bytes, w, h, d.total_bytes())).filter(|&s| s <= allowance) + streamed.or_else(|| png_row_scratch_from_header(bytes, w, h, total_bytes)).filter(|&s| s <= allowance) } else { None }; let rows = row_scratch.is_some(); let scratch = row_scratch.unwrap_or_else(|| { - let band = u64::from(BAND) * u64::from(w) * (u64::from(d.color_type().bytes_per_pixel()) + 4); - d.total_bytes().saturating_add(band) + let band = u64::from(BAND) * u64::from(w) * (per_pixel + 4); + total_bytes.saturating_add(band) }); - (rows || d.total_bytes() <= allowance).then_some(Reduction { size: (w, h), to, rows, scratch }) + (rows || total_bytes <= allowance).then_some(Reduction { size: (w, h), to, rows, scratch }) } /// Streaming retains rows, not the declared full image. Preserve the renderer's source-pixel @@ -439,11 +474,7 @@ fn shrunk_with_png_limits(bytes: &[u8], r: &Reduction, png_limits: &craft_image_ .ok()?; } } else { - let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?; - let mut limits = image::Limits::default(); - limits.max_alloc = Some(allowance()); - reader.limits(limits); - let img = reader.decode().ok()?; + let img = decode_as(drawn_format(bytes)?, bytes, allowance()).ok()?; let (w, h) = (img.width(), img.height()); for y in (0..h).step_by(BAND as usize) { let band = img.crop_imm(0, y, w, BAND.min(h - y)).to_rgba8(); @@ -563,7 +594,7 @@ fn decode_or_reduction(bytes: &[u8]) -> Result Ok(img), - Err((image::ImageError::Limits(_), Undecoded::Unreadable)) => Err(reduction(bytes, allowance()).ok_or(Undecoded::Unreadable)), + Err((DecodeError::Limit(_), Undecoded::Unreadable)) => Err(reduction(bytes, allowance()).ok_or(Undecoded::Unreadable)), Err((_, why)) => Err(Err(why)), } } @@ -730,6 +761,78 @@ mod tests { assert!(red_at_its_coverage(&reduced)); } + /// The renderer's decoding through craft-image-codecs gives the pixels the image crate gave it + /// (#778): the same layout and samples for PNGs of each color type and depth, GIF, WebP, TIFF and + /// BMP, and JPEG samples within two steps (the two decoders' IDCTs round differently). The EXIF + /// orientation is left to the caller, as before. + #[test] + fn decoded_pixels_are_those_the_image_crate_gave() { + use image::{DynamicImage as D, ImageFormat as F}; + let rgba = image::RgbaImage::from_fn(13, 7, |x, y| image::Rgba([(x * 19) as u8, (y * 37) as u8, ((x + y) * 11) as u8, (x * y * 5) as u8])); + let rgba16 = image::ImageBuffer::, _>::from_fn(13, 7, |x, y| { + image::Rgba([(x * 4_999) as u16, (y * 9_001) as u16, 300, 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.clone()).to_luma_alpha8()), + D::ImageRgba16(rgba16.clone()), + D::ImageRgb16(D::ImageRgba16(rgba16.clone()).to_rgb16()), + D::ImageLuma16(D::ImageRgba16(rgba16.clone()).to_luma16()), + D::ImageLumaA16(D::ImageRgba16(rgba16).to_luma_alpha16()), + ]; + let encoded = |img: &D, f: F| { + let mut out = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut out), f).ok().map(|()| out) + }; + let mut files: Vec<(String, Vec)> = Vec::new(); + for img in &images { + for f in [F::Png, F::Tiff, F::Bmp, F::Gif, F::WebP, F::Jpeg] { + if let Some(bytes) = encoded(img, f) { + files.push((format!("{f:?} {:?}", img.color()), bytes)); + } + } + } + // A palette PNG with a transparent entry and a 1-bit gray PNG, as other writers make them. + let png = |w: u32, h: u32, depth: u8, color: u8, extra: &[&[u8]], rows: &[u8]| { + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + std::io::Write::write_all(&mut z, rows).unwrap(); + let idat = [&b"IDAT"[..], &z.finish().unwrap()].concat(); + let ihdr = [&b"IHDR"[..], &w.to_be_bytes(), &h.to_be_bytes(), &[depth, color, 0, 0, 0]].concat(); + let mut out = b"\x89PNG\r\n\x1a\n".to_vec(); + for chunk in [&ihdr[..]].into_iter().chain(extra.iter().copied()).chain([&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 + }; + let plte: &[u8] = b"PLTE\xff\0\0\0\xff\0\0\0\xff"; + files.push(("indexed PNG".into(), png(4, 2, 8, 3, &[plte, b"tRNS\xff\0"], &[0, 0, 1, 2, 1, 0, 2, 1, 0, 0]))); + files.push(("indexed PNG, opaque".into(), png(4, 2, 8, 3, &[plte], &[0, 0, 1, 2, 1, 0, 2, 1, 0, 0]))); + files.push(("1-bit PNG".into(), png(10, 2, 1, 0, &[], &[0, 0b1010_1100, 0b0100_0000, 0, 0b0011_1111, 0b1100_0000]))); + assert!(files.len() > 20, "{}", files.len()); + for (what, bytes) in &files { + let want = image::load_from_memory(bytes).unwrap(); + let got = decode_in_room(bytes).map_err(|(e, _)| e).unwrap(); + let jpeg = what.starts_with("Jpeg"); + if !jpeg { + assert_eq!(got.color(), want.color(), "{what}"); + } + let (g, w) = (got.to_rgba16(), want.to_rgba16()); + assert_eq!(g.dimensions(), w.dimensions(), "{what}"); + let tolerance = if jpeg { 2 * 257 } else { 0 }; + let worst = g.as_raw().iter().zip(w.as_raw()).map(|(a, b)| a.abs_diff(*b)).max().unwrap_or(0); + assert!(worst <= tolerance, "{what}: samples {worst} apart"); + // Read past the allowance at reduced size, the same image is read whole first. + let whole = shrunk(bytes, &Reduction { size: w.dimensions(), to: w.dimensions(), rows: false, scratch: 0 }).unwrap(); + assert_eq!((u32::from(whole.width()), u32::from(whole.height())), w.dimensions(), "{what}"); + } + } + /// Opaque red beside clear black, every other column of a `w` × 1 image. fn striped(w: u32) -> image::RgbaImage { image::RgbaImage::from_fn(w, 1, |x, _| if x % 2 == 0 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([0, 0, 0, 0]) }) diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index b562e85865..a25738c5ba 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -1686,16 +1686,18 @@ fn tiff_header(w: u32, h: u32) -> Vec { #[test] fn an_image_too_large_as_rgba_is_not_decoded() { let over = paint::decode_within_allowance(&png_header(23_171, 23_170)); - assert!(matches!(over, Err(image::ImageError::Limits(_))), "{over:?}"); + assert!(matches!(over, Err(paint::DecodeError::Limit(_))), "{over:?}"); + assert!(over.unwrap_err().to_string().starts_with("the image is too large to decode: ")); let failed = decode_failures(); assert!(paint::decode_pixmap(&png_header(23_171, 23_170)).is_none()); assert!(decode_failures() > failed); // Within the allowance: decoded, and its missing rows can't be read. let within = paint::decode_within_allowance(&png_header(23_170, 23_170)); - assert!(matches!(within, Err(image::ImageError::Decoding(_))), "{within:?}"); + assert!(matches!(within, Err(paint::DecodeError::Unreadable(_))), "{within:?}"); + assert!(within.unwrap_err().to_string().starts_with("the image's pixels can't be read: ")); // A header whose size as RGBA does not fit in 64 bits gets the same limit error. let huge = paint::decode_within_allowance(&tiff_header(1 << 31, 1 << 31)); - assert!(matches!(huge, Err(image::ImageError::Limits(_))), "{huge:?}"); + assert!(matches!(huge, Err(paint::DecodeError::Limit(_))), "{huge:?}"); } /// A PNG of `w` × `h` noisy pixels cut off halfway through its bytes: its header reads, and its diff --git a/crates/render/src/tests/adjust.rs b/crates/render/src/tests/adjust.rs index c50bdc39f4..3820551ce7 100644 --- a/crates/render/src/tests/adjust.rs +++ b/crates/render/src/tests/adjust.rs @@ -47,7 +47,41 @@ fn red_square(x: f64, y: f64) -> Node { fn red_image() -> (String, ImageBlob) { let img = image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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(); ("red".into(), ImageBlob::new("image/png", png)) } diff --git a/crates/render/src/tests/changed.rs b/crates/render/src/tests/changed.rs index 27c299c49c..07251df938 100644 --- a/crates/render/src/tests/changed.rs +++ b/crates/render/src/tests/changed.rs @@ -547,7 +547,41 @@ fn traced(view: &str) -> (Document, NodeId, NodeId, NodeId) { let mut d = Document::new(W as f64, H as f64); let mut png = vec![]; let red = image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255])); - red.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = red.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(); d.images.insert("red".into(), vectorcraft_doc::ImageBlob::new("image/png", png)); let source = red_image(&mut d, 10.0); let a = rect(&mut d, Rect::new(60.0, 10.0, 70.0, 20.0), Color::rgb(0.0, 0.5, 0.0)); diff --git a/crates/render/src/tests/cmykblend.rs b/crates/render/src/tests/cmykblend.rs index 2235320021..56f02a80a0 100644 --- a/crates/render/src/tests/cmykblend.rs +++ b/crates/render/src/tests/cmykblend.rs @@ -211,7 +211,41 @@ fn placed_images_are_separated_not_blackened() { let mut d = doc(ColorMode::Cmyk, None, CYAN, Blend::Normal, 0.5); let img = image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 255])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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(); d.images.insert("red".into(), ImageBlob::new("image/png", png)); let n = Node::new( d.alloc_id(), @@ -255,7 +289,41 @@ fn rich_black_shows_black_ink_alone_as_rgb_black() { let mut d = Document::new_with_mode(20.0, 20.0, ColorMode::Cmyk); let img = image::RgbaImage::from_pixel(20, 20, image::Rgba([255, 0, 0, 255])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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(); d.images.insert("red".into(), ImageBlob::new("image/png", png)); let im = ImageObject { key: "red".into(), width: 20, height: 20, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; let n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); diff --git a/crates/render/src/tests/colorize.rs b/crates/render/src/tests/colorize.rs index 8a8891c7da..38f3b6dca5 100644 --- a/crates/render/src/tests/colorize.rs +++ b/crates/render/src/tests/colorize.rs @@ -28,7 +28,41 @@ fn bilevel_tiff() -> Vec { fn gray_png() -> Vec { let img = image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap(); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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(); png } @@ -81,7 +115,41 @@ fn gray_and_1_bit_images_draw_in_their_spot_color_with_white_transparent() { fn shrunk_copies_are_kept_per_color() { let black = image::GrayImage::from_raw(64, 64, vec![0; 64 * 64]).unwrap(); let mut png = vec![]; - black.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = black.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 blob = ImageBlob::new("image/png", png); let d = doc_of(blob.clone(), Some(Paint::solid(Color::rgb(0.0, 0.0, 1.0))), (64, 64), 1.0); let plain = doc_of(blob, None, (64, 64), 1.0); @@ -102,7 +170,41 @@ fn shrunk_copies_are_kept_per_color() { fn kept_images_only_draw_the_colorized_pixels() { let black = image::GrayImage::from_raw(48, 48, vec![0; 48 * 48]).unwrap(); let mut png = vec![]; - black.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = black.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 d = doc_of(ImageBlob::new("image/png", png), Some(Paint::solid(Color::rgb(0.0, 0.0, 1.0))), (48, 48), 1.0); let view = Affine::scale(0.25); let mut r = Renderer::new(); @@ -135,7 +237,41 @@ fn ink_planes_keep_the_colors_own_inks() { fn colorize_dims_with_the_grays() { let gray = image::GrayImage::from_raw(2, 1, vec![128, 255]).unwrap(); let mut png = vec![]; - gray.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = gray.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 d = doc(ImageBlob::new("image/png", png), Some(Paint::solid(Color::rgb(0.0, 0.0, 1.0)))); let px = Renderer::new().render(&d, 40, 20, Affine::IDENTITY, &RenderOptions { smooth_images: false, ..Default::default() }).pixel(10, 10); // Half blue over the green band. @@ -346,7 +482,41 @@ fn image_and_fills(mode: vectorcraft_doc::ColorMode, blob: ImageBlob, (width, he fn rgb_png(width: u32, height: u32, pixels: &[[u8; 3]]) -> Vec { let img = image::RgbImage::from_raw(width, height, pixels.concat()).unwrap(); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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(); png } diff --git a/crates/render/src/tests/container.rs b/crates/render/src/tests/container.rs index dfc8dca91c..30266547af 100644 --- a/crates/render/src/tests/container.rs +++ b/crates/render/src/tests/container.rs @@ -155,7 +155,41 @@ fn group_geometry_effects_move_the_members_as_one_piece() { fn group_geometry_effects_move_and_copy_images_too() { let mut d = Document::new(100.0, 100.0); let mut png = Vec::new(); - image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 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([255, 0, 0, 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(); d.images.insert("red".into(), ImageBlob::new("image/png", png)); let b = rect(&mut d, Rect::new(0.0, 0.0, 20.0, 20.0), solid(0.0, 0.0, 1.0)); let im = ImageObject { diff --git a/crates/render/src/tests/layeropts.rs b/crates/render/src/tests/layeropts.rs index bfa7910f15..6e327c143f 100644 --- a/crates/render/src/tests/layeropts.rs +++ b/crates/render/src/tests/layeropts.rs @@ -12,7 +12,41 @@ fn doc(layer: impl FnOnce(&mut NodeKind)) -> Document { let mut d = Document::new(100.0, 100.0); let img = image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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(); d.images.insert("red".into(), ImageBlob::new("image/png", png)); let l = d.layers[0].id; let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); diff --git a/crates/render/src/tests/memory.rs b/crates/render/src/tests/memory.rs index a9226da834..2cdc41df3c 100644 --- a/crates/render/src/tests/memory.rs +++ b/crates/render/src/tests/memory.rs @@ -18,7 +18,41 @@ fn png(w: u32, h: u32, seed: u8) -> Vec { image::Rgba([v ^ seed, v.wrapping_mul(3), seed, 255]) }); let mut out = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 } @@ -2536,7 +2570,41 @@ fn a_reduced_image_on_the_ink_planes_shows_its_average() { let _fonts = fonts_steady(); let lines = image::RgbaImage::from_fn(64, 64, |x, _| image::Rgba(if x % 2 == 0 { [0, 0, 0, 255] } else { [255; 4] })); let mut bytes = vec![]; - lines.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = lines.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(); let mut d = cmyk_doc_with("lines", ImageBlob::new("image/png", bytes), 64, 64); // Transparency beside the image: the document blends in CMYK, drawing on its ink planes. let shape = vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 0.0, 110.0, 10.0)); @@ -2560,7 +2628,41 @@ fn a_reduced_image_on_the_ink_planes_shows_its_average() { fn varied_png(w: u32, h: u32, seed: u8) -> Vec { let img = image::RgbaImage::from_fn(w, h, |x, y| image::Rgba([(x * 5 + y) as u8, (x / 3 + y * 7) as u8, (x ^ y) as u8 ^ seed, 255])); let mut out = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 } diff --git a/crates/render/src/tests/meshwarp.rs b/crates/render/src/tests/meshwarp.rs index d4e5a98499..3316ba70bb 100644 --- a/crates/render/src/tests/meshwarp.rs +++ b/crates/render/src/tests/meshwarp.rs @@ -10,7 +10,41 @@ use vectorcraft_geom::Point; fn png(alpha: u8) -> Vec { let img = image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, alpha])); let mut out = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 } diff --git a/crates/render/src/tests/objectfx.rs b/crates/render/src/tests/objectfx.rs index de07dc08b3..13fc9c0cbf 100644 --- a/crates/render/src/tests/objectfx.rs +++ b/crates/render/src/tests/objectfx.rs @@ -306,7 +306,41 @@ fn image_doc(effects: Vec) -> Document { let mut d = Document::new(100.0, 100.0); let img = image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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(); d.images.insert("red".into(), ImageBlob::new("image/png", png)); let mut n = Node::new( NodeId(0), @@ -786,7 +820,41 @@ fn an_images_outline_object_stroke_follows_new_pixels_under_the_same_key() { image::Rgba([255, 0, 0, if r <= 8.0 { 255 } else { 0 }]) }); let mut png = vec![]; - disc.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = disc.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(); d.images.insert("red".into(), ImageBlob::new("image/png", png)); let img = r.render(&d, 100, 100, Affine::IDENTITY, &opts); assert_eq!((lum(img.pixel(19, 35)), lum(img.pixel(26, 35))), (WHITE, 0)); diff --git a/crates/render/src/tests/placed_document.rs b/crates/render/src/tests/placed_document.rs index 3a65b1abe0..c2790d8185 100644 --- a/crates/render/src/tests/placed_document.rs +++ b/crates/render/src/tests/placed_document.rs @@ -374,7 +374,41 @@ fn a_placed_document_kept_as_its_preview_draws_the_preview() { // Only the preview (a 20×10 green PNG) is there, and the file can't be read here. let img = image::RgbaImage::from_pixel(20, 10, image::Rgba([0, 200, 0, 255])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 blob = ImageBlob::new("image/png", png); blob.proxy = Some(blob.bytes.clone()); d.images.insert("preview-1".into(), blob); diff --git a/crates/render/src/tests/setup.rs b/crates/render/src/tests/setup.rs index e80e807e4a..ffaccf832f 100644 --- a/crates/render/src/tests/setup.rs +++ b/crates/render/src/tests/setup.rs @@ -7,7 +7,41 @@ use crate::*; fn doc_with_red_image() -> Document { let mut d = Document::new(40.0, 40.0); let mut png = Vec::new(); - image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 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([255, 0, 0, 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(); d.images.insert("red".into(), ImageBlob::new("image/png", png)); let (id, layer) = (d.alloc_id(), d.layers[0].id); let im = ImageObject { key: "red".into(), width: 40, height: 40, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; diff --git a/crates/render/src/tests/viewraster.rs b/crates/render/src/tests/viewraster.rs index 47fd4d9461..7d7399e608 100644 --- a/crates/render/src/tests/viewraster.rs +++ b/crates/render/src/tests/viewraster.rs @@ -115,7 +115,41 @@ fn rasters_cropped_to_the_view_follow_a_pan_and_a_zoom() { fn large_image(effects: &[(&str, serde_json::Value)]) -> Document { let img = image::RgbaImage::from_fn(300, 200, |x, y| image::Rgba([(x * 7) as u8, (y * 13) as u8, ((x + y) * 3) as u8, 255])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 d = Document::new(6000.0, 4000.0); d.images.insert("viewraster-pan".into(), ImageBlob::new("image/png", png)); let im = ImageObject { diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index e7d869e6f6..3ebda15d43 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -20,6 +20,7 @@ vectorcraft-brush = { workspace = true } vectorcraft-text = { workspace = true } vectorcraft-pathops = { workspace = true } kurbo = { workspace = true } +# Image elements still go through usvg's image href resolution (src/import/files.rs, src/import/budget.rs). usvg = { workspace = true } thiserror = { workspace = true } serde = { workspace = true } @@ -28,6 +29,7 @@ serde_json = { workspace = true } # SVGZ (gzip, pure-Rust backend: builds for wasm). flate2 = { workspace = true } image = { workspace = true } +craft-image-codecs = { workspace = true } # Image data URLs decoded as usvg decodes them, within a byte limit (MIT OR Apache-2.0; already used by usvg). data-url = "0.3.2" # Colour / transform / length parsing for the fallback (MIT OR Apache-2.0; already used by usvg). @@ -41,9 +43,6 @@ unicode-bidi = "0.3.18" skrifa = { workspace = true } # A variable font built in code (no font file is committed). vectorcraft-text = { workspace = true, features = ["test-fonts"] } -resvg = { version = "0.45", default-features = false, features = ["raster-images"] } -# usvg as a reference viewer that lays text out in a font (text_layout.rs). -usvg = { workspace = true, features = ["text"] } +craft-svg = { workspace = true, features = ["tree-render", "tree-text"] } vectorcraft-testkit = { workspace = true } proptest = { workspace = true } -image = { workspace = true } diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index 4c1f8f0ec2..e3acc9f032 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -1,5 +1,6 @@ //! The SVG writer. +use craft_svg::tree::usvg; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::fmt::Write as _; use std::sync::Arc; @@ -20,6 +21,8 @@ use crate::{ xml_escape, }; +use craft_svg::write::SvgWriter; + use crate::css::{self, Props, blend_css, css_string, font_descriptor}; mod nodes; @@ -155,30 +158,36 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: opts.encoding }; let nl = if opts.minify { "" } else { "\n" }; - let mut out = String::new(); + let mut svg = SvgWriter::fragment(); // A file in neither UTF-8 nor UTF-16 must name its encoding. if !opts.minify || encoding == Encoding::Latin1 { - out.push_str(&format!("{nl}", encoding.xml_name())); + svg.decl(encoding.xml_name(), nl); } if opts.styling == Styling::StyleEntities && !w.classes.is_empty() { - out.push_str("", w.indent(1), i + 1, entity_value(c))); - } - out.push_str(&format!("{nl}]>{nl}")); + let entities = w + .classes + .iter() + .enumerate() + .map(|(i, c)| format!("{}", w.indent(1), i + 1, entity_value(c))) + .collect::>() + .join(nl); + svg.doctype_internal("svg", &entities, nl); } let (ww, hh) = (w.num(rect.width()), w.num(rect.height())); - out.push_str("{nl}")); + root.attr("viewBox", format_args!("0 0 {ww} {hh}")).open(); + let mut out = svg.as_str().to_string(); + out.push_str(nl); let css = opts.styling == Styling::InternalCss && !w.classes.is_empty(); let fonts = w.font_faces(); if !w.defs.is_empty() || css || !fonts.is_empty() { diff --git a/crates/svg/src/export/paint.rs b/crates/svg/src/export/paint.rs index f52a701867..234783d029 100644 --- a/crates/svg/src/export/paint.rs +++ b/crates/svg/src/export/paint.rs @@ -13,10 +13,16 @@ fn web_image(b: &ImageBlob) -> std::borrow::Cow<'_, ImageBlob> { if matches!(b.mime.as_str(), "image/png" | "image/jpeg" | "image/jpg" | "image/gif" | "image/webp" | "image/svg+xml") { return Cow::Borrowed(b); } - let png = image::load_from_memory(&b.bytes).ok().and_then(|img| { - let mut out = Vec::new(); - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).ok()?; - Some(out) + let png = craft_image_codecs::decode(&b.bytes).ok().and_then(|img| { + let raw = craft_image_codecs::Image::from_raw( + img.width(), + img.height(), + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + img.to_rgba8(), + ) + .ok()?; + craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() }); png.map_or(Cow::Borrowed(b), |png| Cow::Owned(ImageBlob::png(png))) } @@ -97,15 +103,16 @@ impl Writer<'_> { for alpha in coverage { rgba.extend_from_slice(&if self.tiny() { [rgb[0], rgb[1], rgb[2], alpha] } else { [255, 255, 255, alpha] }); } - let Some(pixels) = image::RgbaImage::from_raw(width, height, rgba) else { + let Ok(pixels) = + craft_image_codecs::Image::from_raw(width, height, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba) + else { self.warn(UNDECODED); return; }; - let mut png = Vec::new(); - if pixels.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_err() { + let Ok(png) = craft_image_codecs::encode(&pixels, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) else { self.warn(UNDECODED); return; - } + }; let href = self.blob_href(&ImageBlob::png(png)); self.colorized_hrefs.insert(key.clone(), href.clone()); href @@ -537,11 +544,18 @@ impl Writer<'_> { let (cols, rows) = (along(cover.width()), along(cover.height())); (g.pixels(b, cover, cols, rows, fill, &Color::to_rgb).flatten().collect(), cols, rows) }; - let mut png = Vec::new(); - let Some(img) = image::RgbaImage::from_raw(u32::from(cols), u32::from(rows), rgba) else { return }; - if img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_err() { + let Ok(img) = craft_image_codecs::Image::from_raw( + u32::from(cols), + u32::from(rows), + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + rgba, + ) else { return; - } + }; + let Ok(png) = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) else { + return; + }; self.warn(if freeform { "freeform gradients are written as images clipped to their shapes" } else if conic { diff --git a/crates/svg/src/glyph.rs b/crates/svg/src/glyph.rs index 22697f58a3..2f0ccf6528 100644 --- a/crates/svg/src/glyph.rs +++ b/crates/svg/src/glyph.rs @@ -6,7 +6,7 @@ use std::ops::Range; use std::sync::Arc; use std::sync::atomic::AtomicU64; -use usvg::roxmltree; +use craft_svg::tree::usvg::roxmltree; use vectorcraft_doc::color::Color; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; use vectorcraft_geom::Affine; diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index 287569b859..6348b6e141 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -1,11 +1,12 @@ //! usvg tree → document conversion. +use craft_svg::tree::usvg; use std::borrow::Cow; use std::collections::{HashMap, HashSet}; use std::str::FromStr; use std::sync::Arc; -use usvg::roxmltree; +use craft_svg::tree::usvg::roxmltree; use vectorcraft_color::{BlendMode, Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint}; use vectorcraft_doc::{ Appearance, AppearanceItem, Dash, Document, FillLayer, ForeignAttribute, ImageBlob, ImageObject, LayerColor, LineCap, LineJoin, MAX_SVG_SCRIPTS, diff --git a/crates/svg/src/import/convert.rs b/crates/svg/src/import/convert.rs index 8bdadb0318..676708a09d 100644 --- a/crates/svg/src/import/convert.rs +++ b/crates/svg/src/import/convert.rs @@ -1,4 +1,5 @@ use super::{Affine, Arc, BezPath, BlendMode, Color, FillRule, GradientStop, HashMap, Node, PathData, Point, XNode, roxmltree}; +use craft_svg::tree::usvg; use vectorcraft_geom::path::{Anchor, AnchorKind, SubPath}; use vectorcraft_geom::shapes::KAPPA; @@ -105,7 +106,7 @@ pub(super) fn only_clips(g: &usvg::Group) -> bool { } pub(super) fn blend(b: usvg::BlendMode) -> BlendMode { - use usvg::BlendMode as B; + use craft_svg::tree::usvg::BlendMode as B; match b { B::Normal => BlendMode::Normal, B::Multiply => BlendMode::Multiply, @@ -127,7 +128,7 @@ pub(super) fn blend(b: usvg::BlendMode) -> BlendMode { } pub(super) fn bezpath(p: &usvg::tiny_skia_path::Path, m: Affine) -> BezPath { - use usvg::tiny_skia_path::PathSegment as S; + use craft_svg::tree::usvg::tiny_skia_path::PathSegment as S; let pt = |p: usvg::tiny_skia_path::Point| m * Point::new(p.x as f64, p.y as f64); let mut bp = BezPath::new(); for s in p.segments() { @@ -147,7 +148,7 @@ pub(super) fn bezpath(p: &usvg::tiny_skia_path::Path, m: Affine) -> BezPath { /// smooth anchors on the axes in the same order, each quarter a cubic with handles [`KAPPA`] of the /// radii long, the ellipse export writes as ``. `None` when `p` is not such an outline. pub(super) fn drawn_ellipse(p: &usvg::tiny_skia_path::Path) -> Option { - use usvg::tiny_skia_path::PathSegment as S; + use craft_svg::tree::usvg::tiny_skia_path::PathSegment as S; let mut ends = vec![]; let mut closed = false; for s in p.segments() { diff --git a/crates/svg/src/import/css.rs b/crates/svg/src/import/css.rs index 7bf440cc73..de823a49db 100644 --- a/crates/svg/src/import/css.rs +++ b/crates/svg/src/import/css.rs @@ -11,7 +11,7 @@ use std::cell::RefCell; use std::collections::{HashMap, HashSet}; use std::rc::Rc; -use usvg::roxmltree; +use craft_svg::tree::usvg::roxmltree; pub(super) type XNode<'a, 'i> = roxmltree::Node<'a, 'i>; diff --git a/crates/svg/src/import/css_transform.rs b/crates/svg/src/import/css_transform.rs index 235d237453..dc59b28426 100644 --- a/crates/svg/src/import/css_transform.rs +++ b/crates/svg/src/import/css_transform.rs @@ -11,7 +11,7 @@ use std::f64::consts::PI; use std::ops::Range; -use usvg::roxmltree; +use craft_svg::tree::usvg::roxmltree; use super::css::XNode; diff --git a/crates/svg/src/import/depth.rs b/crates/svg/src/import/depth.rs index 0586deaf6f..d6b6eb7e20 100644 --- a/crates/svg/src/import/depth.rs +++ b/crates/svg/src/import/depth.rs @@ -16,7 +16,7 @@ use std::borrow::Cow; use std::collections::HashMap; use std::collections::hash_map::Entry; -use usvg::roxmltree; +use craft_svg::tree::usvg::roxmltree; use super::css::{Styles, XNode, parse_decls}; diff --git a/crates/svg/src/import/files.rs b/crates/svg/src/import/files.rs index 8b612f78c1..631bed3d0c 100644 --- a/crates/svg/src/import/files.rs +++ b/crates/svg/src/import/files.rs @@ -939,25 +939,17 @@ fn png_takes_icc(img: &image::DynamicImage, icc: &[u8]) -> bool { /// can read (a TIFF's read by [`vectorcraft_doc::cmyk::tiff_icc_profile`]); `None` when they /// can't be. fn decoded(bytes: &[u8], format: image::ImageFormat) -> Option<(image::DynamicImage, Option>)> { - use image::ImageDecoder as _; let max = vectorcraft_doc::MAX_RASTER_ALLOC; - let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?; - if reader.format().is_none() { - reader.set_format(format); - } - let mut limits = image::Limits::default(); - limits.max_alloc = Some(max); - reader.limits(limits); - let tiff = reader.format() == Some(image::ImageFormat::Tiff); - let mut decoder = reader.into_decoder().ok()?; - let (w, h) = decoder.dimensions(); - if decoder.total_bytes() > max || u64::from(w) * u64::from(h) * 4 > max { + let kind = craft_image_codecs::detect(bytes).or_else(|| format.extensions_str().iter().find_map(|e| craft_image_codecs::from_extension(e)))?; + let (w, h, per_pixel) = vectorcraft_doc::decode::decoded_layout(bytes, kind)?; + let pixels = u64::from(w) * u64::from(h); + if pixels.saturating_mul(per_pixel) > max || pixels * 4 > max { return None; } - // 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 icc = if tiff { vectorcraft_doc::cmyk::tiff_icc_profile(bytes) } else { decoder.icc_profile().ok().flatten() }; - Some((image::DynamicImage::from_decoder(decoder).ok()?, icc)) + let (img, icc) = vectorcraft_doc::decode::decode_image(kind, bytes, max).ok()?; + // A TIFF's profile is read by the TIFF reader, as before. + let icc = if kind == craft_image_codecs::Format::Tiff { vectorcraft_doc::cmyk::tiff_icc_profile(bytes) } else { icc }; + Some((img, icc)) } /// The pixels of TIFF `bytes`, as stored, read as Open and Place read them: a TIFF with extra @@ -1507,4 +1499,45 @@ mod tests { )] ); } + + /// SVG import's 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::, _>::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 std::io::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, _) = super::decoded(&bytes, f).unwrap_or_else(|| panic!("{what}")); + 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:?}"); + checked += 1; + } + } + assert!(checked >= 20, "{checked}"); + } } diff --git a/crates/svg/src/import/fx.rs b/crates/svg/src/import/fx.rs index 08e2dfeb9a..ba7e9152c4 100644 --- a/crates/svg/src/import/fx.rs +++ b/crates/svg/src/import/fx.rs @@ -7,12 +7,15 @@ //! blurred with a fixed amount subtracted from its colors by `feComponentTransfer` (Darkness), and what //! our export writes, so export → import keeps the effects. +use craft_svg::tree::usvg; use std::collections::HashMap; use std::sync::Arc; +use craft_svg::tree::usvg::filter::{ + ColorInterpolation, ColorMatrixKind, CompositeOperator, Filter, Input, Kind, MorphologyOperator, TransferFunction, +}; +use craft_svg::tree::usvg::roxmltree; use serde_json::json; -use usvg::filter::{ColorInterpolation, ColorMatrixKind, CompositeOperator, Filter, Input, Kind, MorphologyOperator, TransferFunction}; -use usvg::roxmltree; use vectorcraft_color::Color; use vectorcraft_doc::Effect; use vectorcraft_geom::{Affine, Vec2}; diff --git a/crates/svg/src/import/importer.rs b/crates/svg/src/import/importer.rs index ebafbb1346..9badabc601 100644 --- a/crates/svg/src/import/importer.rs +++ b/crates/svg/src/import/importer.rs @@ -7,6 +7,7 @@ use super::{ StrokeLayer, Vec2, fnv1a, fx, shapes, text, vector_effect, }; use crate::SvgError; +use craft_svg::tree::usvg; use kurbo::BezPath; use vectorcraft_color::GradientSpread; @@ -778,11 +779,7 @@ impl Importer { usvg::ImageKind::SVG(tree) => return self.svg_image(tree, acc), }; let size = i.size(); - let (pw, ph) = image::ImageReader::new(std::io::Cursor::new(&bytes[..])) - .with_guessed_format() - .ok() - .and_then(|r| r.into_dimensions().ok()) - .unwrap_or((size.width().round().max(1.0) as u32, size.height().round().max(1.0) as u32)); + let (pw, ph) = vectorcraft_doc::header_size(bytes).unwrap_or((size.width().round().max(1.0) as u32, size.height().round().max(1.0) as u32)); // A turned CMYK image is stored as the CMYK TIFF of its inks, the size of the PNG usvg got. let cmyk = self.files.stored(i.kind()); let (bytes, mime) = match &cmyk { diff --git a/crates/svg/src/import/layers.rs b/crates/svg/src/import/layers.rs index a6d6a46b30..20082bdeea 100644 --- a/crates/svg/src/import/layers.rs +++ b/crates/svg/src/import/layers.rs @@ -1,6 +1,7 @@ use super::convert::made_up; use super::importer::{CSS_PX_PER_IN, PT_PER_IN}; use super::{Affine, Arc, FromStr, HashSet, Node, NodeId, NodeKind, Rect, Unit, XNode, roxmltree}; +use craft_svg::tree::usvg; /// What marks a nested `` as a sublayer rather than a group: our export writes it on the layers /// it writes inside layers. (Inkscape's `inkscape:groupmode="layer"` counts too.) @@ -94,7 +95,7 @@ impl RootUnits { /// `'id' (feA, feB)` for each filter: its id and the primitives it uses, for warnings. pub(super) fn filter_names(filters: &[Arc]) -> String { - use usvg::filter::Kind as K; + use craft_svg::tree::usvg::filter::Kind as K; let names: Vec = filters .iter() .map(|f| { diff --git a/crates/svg/src/import/linear_rgb.rs b/crates/svg/src/import/linear_rgb.rs index 8286e0a94b..5ed17a3f46 100644 --- a/crates/svg/src/import/linear_rgb.rs +++ b/crates/svg/src/import/linear_rgb.rs @@ -3,6 +3,7 @@ //! linear light, which a document gradient (mixed in display RGB) shows through extra stops. use super::{Color, GradientStop, HashMap, HashSet, css, roxmltree}; +use craft_svg::tree::usvg; use vectorcraft_color::cms::lab::{linear_to_srgb, srgb_to_linear}; /// How far (display RGB, 0..1) the straight line between neighbouring baked stops may stray from diff --git a/crates/svg/src/import/symbol_units.rs b/crates/svg/src/import/symbol_units.rs index b038b20ff3..78bb34ee19 100644 --- a/crates/svg/src/import/symbol_units.rs +++ b/crates/svg/src/import/symbol_units.rs @@ -9,7 +9,7 @@ use std::ops::Range; use std::str::FromStr; -use usvg::roxmltree; +use craft_svg::tree::usvg::roxmltree; /// The elements whose geometry attributes are rewritten. const SHAPES: &[&str] = &["rect", "circle", "ellipse", "line", "image", "use", "text"]; diff --git a/crates/svg/src/import/text.rs b/crates/svg/src/import/text.rs index d783c04319..f814ea65a9 100644 --- a/crates/svg/src/import/text.rs +++ b/crates/svg/src/import/text.rs @@ -27,6 +27,7 @@ //! moves into its sizes ([`size_scale`], [`fold_scale`]), and the rest (a stretch, skew, //! rotation or reflection) stays its transform. +use craft_svg::tree::usvg; use std::borrow::Cow; use std::cell::RefCell; use std::collections::HashMap; @@ -35,7 +36,7 @@ use std::ops::{Range, RangeInclusive}; use std::rc::Rc; use std::str::FromStr; -use usvg::roxmltree; +use craft_svg::tree::usvg::roxmltree; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{CharStyle, Dash, Justify, LineCap, LineJoin, ParaDirection, ParaStyle, StrokeLayer, TextKind, TextObject, TextRun}; use vectorcraft_geom::kurbo::ParamCurveArclen; diff --git a/crates/svg/src/import/vector_effect.rs b/crates/svg/src/import/vector_effect.rs index 4a80a2fa08..f98a24977c 100644 --- a/crates/svg/src/import/vector_effect.rs +++ b/crates/svg/src/import/vector_effect.rs @@ -6,7 +6,7 @@ use std::collections::HashSet; -use usvg::roxmltree; +use craft_svg::tree::usvg::roxmltree; use vectorcraft_doc::TextObject; use vectorcraft_geom::Affine; diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index 6600f3010a..c48257b34c 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -101,6 +101,7 @@ //! rotation and style names). #![forbid(unsafe_code)] +use craft_svg::tree::usvg; mod css; mod entities; mod export; diff --git a/crates/svg/tests/classes.rs b/crates/svg/tests/classes.rs index b3ae4622e4..d1b1c19af5 100644 --- a/crates/svg/tests/classes.rs +++ b/crates/svg/tests/classes.rs @@ -1,6 +1,6 @@ //! CSS classes on imported elements come back on export, beside the generated `cls-N` classes. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -use usvg::roxmltree; +use craft_svg::tree::usvg::roxmltree; use vectorcraft_svg::{ExportOptions, Profile, Styling, export, import}; const SRC: &str = r#""#; diff --git a/crates/svg/tests/it/basic_shapes.rs b/crates/svg/tests/it/basic_shapes.rs index 25d13cb31c..bf7623c989 100644 --- a/crates/svg/tests/it/basic_shapes.rs +++ b/crates/svg/tests/it/basic_shapes.rs @@ -3,6 +3,7 @@ //! rectangles and ellipses whose dashes would start elsewhere, stays ``; the picture and the //! reimported geometry don't change. +use craft_svg::tree::draw::resvg; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Dash, Document, FillLayer, Node, StrokeLayer}; use vectorcraft_geom::{Affine, PathData, Point, Rect, SubPath, shapes}; diff --git a/crates/svg/tests/it/blend_export.rs b/crates/svg/tests/it/blend_export.rs index ec947041b0..01246393de 100644 --- a/crates/svg/tests/it/blend_export.rs +++ b/crates/svg/tests/it/blend_export.rs @@ -1,7 +1,8 @@ //! Blend modes and opacity masks in SVG export look as on the canvas: every mode follows the //! reference formulas when resvg draws the file, and masks take luminance the canvas's way. -use usvg::roxmltree; +use craft_svg::tree::draw::resvg; +use craft_svg::tree::usvg::roxmltree; use vectorcraft_color::blend::blend_rgb; use vectorcraft_color::{BlendMode, Color, Paint}; use vectorcraft_doc::{Appearance, CharStyle, Document, Node, NodeKind, OpacityMask, TextObject}; diff --git a/crates/svg/tests/it/colorized_images.rs b/crates/svg/tests/it/colorized_images.rs index d3590977f2..8a6f0623bb 100644 --- a/crates/svg/tests/it/colorized_images.rs +++ b/crates/svg/tests/it/colorized_images.rs @@ -1,5 +1,6 @@ //! Colorized gray and bilevel image export, checked as pixels as well as markup. +use craft_svg::tree::draw::resvg; use vectorcraft_color::{Color, Paint, Swatch}; use vectorcraft_doc::{Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind}; use vectorcraft_geom::Affine; @@ -23,6 +24,7 @@ fn bilevel() -> Vec { } fn png(img: image::DynamicImage) -> Vec { + // Through the image crate, so a gray image stays gray (colorizing reads gray images only). let mut out = Vec::new(); img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); out @@ -131,7 +133,8 @@ fn bilevel_process_and_spot_use_coverage_in_embed_link_and_tiny() { assert_eq!(linked.linked.len(), 1); let file = &linked.linked[0]; assert!(linked.svg.contains(&file.name)); - let rgba = image::load_from_memory(&file.bytes).unwrap().to_rgba8(); + let decoded = craft_image_codecs::decode(&file.bytes).unwrap(); + let rgba = image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap(); assert_eq!((rgba.get_pixel(0, 0).0[3], rgba.get_pixel(1, 0).0[3]), (255, 0)); let inlined = linked.svg.replace(&file.name, &format!("data:image/png;base64,{}", base64_encode(&file.bytes))); assert_eq!(rendered(&inlined), rendered(&embedded.svg)); diff --git a/crates/svg/tests/it/dash_align.rs b/crates/svg/tests/it/dash_align.rs index 2885d37446..ced8beeee7 100644 --- a/crates/svg/tests/it/dash_align.rs +++ b/crates/svg/tests/it/dash_align.rs @@ -1,6 +1,7 @@ //! Dashes fitted to corners export as the canvas's filled outlines (a dash array can't fit them); //! exact dashes stay a `stroke-dasharray`. Checked by rendering the exported SVG with resvg. +use craft_svg::tree::draw::resvg; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Dash, Document, Node, StrokeLayer}; use vectorcraft_geom::{Rect, shapes}; diff --git a/crates/svg/tests/it/data_attributes.rs b/crates/svg/tests/it/data_attributes.rs index f8151ed7da..60edf3dd60 100644 --- a/crates/svg/tests/it/data_attributes.rs +++ b/crates/svg/tests/it/data_attributes.rs @@ -1,7 +1,7 @@ //! Synthetic XML 1.0/SVG round trips: https://www.w3.org/TR/xml/#AVNormalize //! https://www.w3.org/TR/xml/#NT-NameChar https://www.w3.org/TR/xml/#charsets +use craft_svg::tree::usvg::roxmltree; use std::collections::HashSet; -use usvg::roxmltree; use vectorcraft_doc::{Document, Node}; use vectorcraft_svg::{Encoding, ExportOptions, ObjectIds, Output, Styling, export, export_full, import}; diff --git a/crates/svg/tests/it/encoding_profile_fonts.rs b/crates/svg/tests/it/encoding_profile_fonts.rs index 5468953aa4..eb0176ff10 100644 --- a/crates/svg/tests/it/encoding_profile_fonts.rs +++ b/crates/svg/tests/it/encoding_profile_fonts.rs @@ -2,6 +2,7 @@ //! back, entity styling parses in usvg, SVG Tiny 1.2 has no filters, masks, symbols or style //! sheets, and embedded fonts hold only the glyphs used where their licence allows it. +use craft_svg::tree::usvg; use std::sync::Arc; use serde_json::json; diff --git a/crates/svg/tests/it/foreign_attributes.rs b/crates/svg/tests/it/foreign_attributes.rs index da949e09a2..ba9131979d 100644 --- a/crates/svg/tests/it/foreign_attributes.rs +++ b/crates/svg/tests/it/foreign_attributes.rs @@ -1,7 +1,7 @@ //! Attributes in other applications' XML namespaces (https://www.w3.org/TR/xml-names/) survive a //! round trip through VectorCraft: kept on import, written back on export with their namespaces //! declared on the root. -use usvg::roxmltree; +use craft_svg::tree::usvg::roxmltree; use vectorcraft_doc::{Document, ForeignAttribute, Node, NodeKind}; use vectorcraft_svg::{ExportOptions, MAX_FOREIGN, MAX_FOREIGN_VALUE, export, export_full, import, import_with_report}; diff --git a/crates/svg/tests/it/image_orientation.rs b/crates/svg/tests/it/image_orientation.rs index e824337857..2ec99065b5 100644 --- a/crates/svg/tests/it/image_orientation.rs +++ b/crates/svg/tests/it/image_orientation.rs @@ -49,9 +49,14 @@ fn folder(name: &str) -> PathBuf { /// A 16 × 8 JPEG, red on the left half, with an EXIF segment giving Orientation `orientation` /// when there is one. fn jpeg(orientation: Option) -> Vec { - let rgb = image::RgbImage::from_fn(16, 8, |x, _| if x < 8 { image::Rgb([220, 0, 0]) } else { image::Rgb([255, 255, 255]) }); - let mut jpg = Vec::new(); - image::DynamicImage::ImageRgb8(rgb).write_to(&mut std::io::Cursor::new(&mut jpg), image::ImageFormat::Jpeg).unwrap(); + let mut rgb = Vec::with_capacity(16 * 8 * 3); + for _ in 0..8 { + for x in 0..16 { + rgb.extend_from_slice(&if x < 8 { [220, 0, 0] } else { [255, 255, 255] }); + } + } + let raw = craft_image_codecs::Image::from_raw(16, 8, craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, rgb).unwrap(); + let jpg = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Jpeg, &craft_image_codecs::EncodeOptions::default()).unwrap(); let Some(orientation) = orientation else { return jpg }; let o = orientation.to_le_bytes(); let exif: Vec = @@ -151,7 +156,9 @@ fn near(a: Rect, b: Rect) -> bool { /// The stored pixels of `im`, as RGB. fn pixels(d: &Document, im: &ImageObject) -> image::RgbImage { - image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgb8() + let decoded = craft_image_codecs::decode(&d.images[&im.key].bytes).unwrap(); + let rgba = image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap(); + image::DynamicImage::ImageRgba8(rgba).into_rgb8() } fn red(p: &image::Rgb) -> bool { @@ -215,7 +222,9 @@ fn a_turned_tiff_imports_upright() { let what = &href[..href.len().min(20)]; assert_eq!((im.width, im.height), (2, 4), "{what}: turned a quarter"); assert!(near(placed(&im), Rect::new(0.0, 0.0, 20.0, 40.0)), "{what}: {:?}", placed(&im)); - let px = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_luma8(); + let decoded = craft_image_codecs::decode(&d.images[&im.key].bytes).unwrap(); + let px = + image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap()).into_luma8(); assert_eq!((px.get_pixel(0, 0)[0], px.get_pixel(1, 1)[0], px.get_pixel(0, 3)[0]), (0, 0, 255), "{what}: the left half is on top"); } } @@ -250,7 +259,8 @@ fn a_gray_tiff_with_alpha_imports_turned_or_not() { let href = format!("data:image/tiff;base64,{}", base64_encode(&tiff(4, 2, 2, &data, orientation))); let (d, im) = import_one(&format!(r#""#), None); assert_eq!((im.width, im.height), size, "orientation {orientation}"); - let px = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8(); + let decoded = craft_image_codecs::decode(&d.images[&im.key].bytes).unwrap(); + let px = image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap(); assert_eq!(px.get_pixel(black_at.0, black_at.1).0, [0, 0, 0, 255], "orientation {orientation}: black"); assert_eq!(px.get_pixel(clear_at.0, clear_at.1)[3], 0, "orientation {orientation}: clear"); } diff --git a/crates/svg/tests/it/import_details.rs b/crates/svg/tests/it/import_details.rs index 239ce7e07a..25c5152de9 100644 --- a/crates/svg/tests/it/import_details.rs +++ b/crates/svg/tests/it/import_details.rs @@ -2,6 +2,7 @@ //! and a warning when missing), SVG images as vector art, nested clips, undisplayed objects as //! hidden objects, and reflected or repeated gradients. +use craft_svg::tree::draw::resvg; use std::path::{Path, PathBuf}; use vectorcraft_doc::{Document, ImageObject, LinkInfo, Node, NodeKind}; @@ -44,11 +45,15 @@ fn resvg_render(svg: &str, w: u32, h: u32) -> Image { } fn png(w: u32, h: u32) -> Vec { - let mut out = vec![]; - image::RgbaImage::from_pixel(w, h, image::Rgba([10, 200, 30, 255])) - .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png) - .unwrap(); - out + let img = craft_image_codecs::Image::from_raw( + w, + h, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + [10u8, 200, 30, 255].repeat((w * h) as usize), + ) + .unwrap(); + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() } /// A fresh folder for one test's files. diff --git a/crates/svg/tests/it/import_live.rs b/crates/svg/tests/it/import_live.rs index 5e1757ae8b..948b23e2e2 100644 --- a/crates/svg/tests/it/import_live.rs +++ b/crates/svg/tests/it/import_live.rs @@ -2,6 +2,7 @@ //! with `` a symbol and its instances, blurs and drop-shadow chains live effects; and //! export → import keeps them. +use craft_svg::tree::draw::resvg; use std::sync::Arc; use serde_json::json; diff --git a/crates/svg/tests/it/interactivity.rs b/crates/svg/tests/it/interactivity.rs index 66b98959b1..17f5e3b671 100644 --- a/crates/svg/tests/it/interactivity.rs +++ b/crates/svg/tests/it/interactivity.rs @@ -4,8 +4,8 @@ use std::sync::Mutex; +use craft_svg::tree::usvg::roxmltree; use proptest::prelude::*; -use usvg::roxmltree; use vectorcraft_doc::{Document, Node}; use vectorcraft_svg::{Encoding, ExportOptions, ImportOptions, Profile, export, export_full, import, import_with}; diff --git a/crates/svg/tests/it/mask_options.rs b/crates/svg/tests/it/mask_options.rs index 16c021391e..69ff8a2d71 100644 --- a/crates/svg/tests/it/mask_options.rs +++ b/crates/svg/tests/it/mask_options.rs @@ -2,6 +2,7 @@ //! defaults in `data-vectorcraft-mask`, and import restores them and the original mask art (without //! the backdrop rectangle and inverting filter that draw the options in SVG). +use craft_svg::tree::draw::resvg; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, Document, Node, OpacityMask}; use vectorcraft_geom::{Rect, shapes}; diff --git a/crates/svg/tests/it/mesh_export.rs b/crates/svg/tests/it/mesh_export.rs index 60c5dcbb08..78f30f50c9 100644 --- a/crates/svg/tests/it/mesh_export.rs +++ b/crates/svg/tests/it/mesh_export.rs @@ -2,6 +2,7 @@ //! pieces, each patch cut finely enough that neighbouring pieces differ by about one 8-bit //! colour step at most, and no finer: a patch of one colour is one piece, not 64 alike. +use craft_svg::tree::draw::resvg; use vectorcraft_color::Color; use vectorcraft_doc::live::{GradientMesh, MeshAppearance}; use vectorcraft_doc::{Document, Node, NodeKind}; diff --git a/crates/svg/tests/it/raster_paints.rs b/crates/svg/tests/it/raster_paints.rs index a6bd69fc5a..b350490f30 100644 --- a/crates/svg/tests/it/raster_paints.rs +++ b/crates/svg/tests/it/raster_paints.rs @@ -38,7 +38,8 @@ fn doc_with(mut n: Node) -> Document { /// The data of the one embedded PNG. fn png_of(svg: &str) -> image::RgbaImage { let data = svg.split("data:image/png;base64,").nth(1).expect("an embedded PNG").split('"').next().unwrap(); - image::load_from_memory(&base64_decode(data).unwrap()).unwrap().to_rgba8() + let decoded = craft_image_codecs::decode(&base64_decode(data).unwrap()).unwrap(); + image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap() } #[test] diff --git a/crates/svg/tests/it/roundtrip.rs b/crates/svg/tests/it/roundtrip.rs index 0846d694f2..ce28085b8b 100644 --- a/crates/svg/tests/it/roundtrip.rs +++ b/crates/svg/tests/it/roundtrip.rs @@ -331,9 +331,15 @@ fn hidden_and_guides_omitted() { #[test] fn image_roundtrip() { - let mut png = Vec::new(); - let img = image::RgbaImage::from_pixel(4, 2, image::Rgba([255, 0, 0, 255])); - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let img = craft_image_codecs::Image::from_raw( + 4, + 2, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + [255u8, 0, 0, 255].repeat(8), + ) + .unwrap(); + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); let mut d = Document::new(200.0, 200.0); let id = d.alloc_id(); let n = Node::new( diff --git a/crates/svg/tests/it/spread.rs b/crates/svg/tests/it/spread.rs index 9a7cc0739d..f434d7daba 100644 --- a/crates/svg/tests/it/spread.rs +++ b/crates/svg/tests/it/spread.rs @@ -3,6 +3,7 @@ //! draws the file as the canvas draws the gradient; SVG import reads `spreadMethod` as the //! gradient's spread; CSS writes repeating gradients. +use craft_svg::tree::draw::resvg; use vectorcraft_color::{Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientSpread, GradientStop, Paint}; use vectorcraft_doc::{Appearance, Document, Node, NodeKind}; use vectorcraft_geom::{Point, Rect, Vec2, shapes}; diff --git a/crates/svg/tests/it/stroke_export.rs b/crates/svg/tests/it/stroke_export.rs index 47a5d592b2..60834c6734 100644 --- a/crates/svg/tests/it/stroke_export.rs +++ b/crates/svg/tests/it/stroke_export.rs @@ -2,6 +2,7 @@ //! written as the canvas's filled outlines or art, aligned strokes are clipped or masked, and open //! paths stroke centred. Checked by rendering the exported SVG with resvg. +use craft_svg::tree::draw::resvg; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Arrowhead, Dash, Document, LineCap, LineJoin, Node, StrokeAlign, StrokeLayer, WidthProfile}; use vectorcraft_geom::{PathData, Point, SubPath, shapes}; diff --git a/crates/svg/tests/it/symbols_layers.rs b/crates/svg/tests/it/symbols_layers.rs index ff594e7ce9..b30d367858 100644 --- a/crates/svg/tests/it/symbols_layers.rs +++ b/crates/svg/tests/it/symbols_layers.rs @@ -4,6 +4,7 @@ //! sublayers keep their names and nesting (a one-layer file's from its root element), and the //! editing data notices edits made elsewhere. +use craft_svg::tree::draw::resvg; use std::sync::Arc; use vectorcraft_color::{Color, Paint}; diff --git a/crates/svg/tests/it/text_layout.rs b/crates/svg/tests/it/text_layout.rs index 734d2f293c..2858161321 100644 --- a/crates/svg/tests/it/text_layout.rs +++ b/crates/svg/tests/it/text_layout.rs @@ -2,6 +2,7 @@ //! its leading, baseline shift, scaling and kerning, and a renderer with the same font draws the //! export where the canvas draws the text. +use craft_svg::tree::usvg; use std::sync::Arc; use vectorcraft_color::{Color, Paint}; @@ -834,7 +835,7 @@ fn viewer_outlines(svg: &str) -> Vec { let m = Affine::new([m.sx as f64, m.ky as f64, m.kx as f64, m.sy as f64, m.tx as f64, m.ty as f64]); let mut bp = BezPath::new(); for s in p.data().segments() { - use usvg::tiny_skia_path::PathSegment as S; + use craft_svg::tree::usvg::tiny_skia_path::PathSegment as S; let pt = |q: usvg::tiny_skia_path::Point| m * Point::new(q.x as f64, q.y as f64); match s { S::MoveTo(a) => bp.move_to(pt(a)), diff --git a/crates/svg/tests/it/warp_pieces.rs b/crates/svg/tests/it/warp_pieces.rs index 4d61baee14..437bab8a65 100644 --- a/crates/svg/tests/it/warp_pieces.rs +++ b/crates/svg/tests/it/warp_pieces.rs @@ -1,6 +1,7 @@ //! The pieces a raster mesh warp cuts an image into overlap their neighbors: in SVG a partly //! transparent image keeps its own alpha where they do, and the pieces share one copy of the image. +use craft_svg::tree::draw::resvg; use vectorcraft_doc::live::mesh_warp_image; use vectorcraft_doc::{Document, ImageBlob, ImageObject, Node, NodeKind}; use vectorcraft_geom::{Affine, Point}; @@ -14,9 +15,9 @@ fn warped(f: &dyn Fn(Point) -> Point, masked: bool) -> Document { /// [`warped`] with every pixel `rgba`, after `tweak` adjusts the image object. fn warped_pixels(f: &dyn Fn(Point) -> Point, masked: bool, rgba: [u8; 4], tweak: impl FnOnce(&mut Node)) -> Document { - let img = image::RgbaImage::from_pixel(4, 4, image::Rgba(rgba)); - let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let img = craft_image_codecs::Image::from_raw(4, 4, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba.repeat(16)) + .unwrap(); + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); let mut d = Document::new(100.0, 100.0); d.images.insert("pic".into(), ImageBlob::png(png)); let im = ImageObject { @@ -77,9 +78,14 @@ fn a_half_transparent_image_is_half_transparent_where_its_warp_pieces_overlap() /// transparent pixels, and the right half stays half transparent. #[test] fn opaque_pixels_stay_opaque_where_warp_pieces_overlap() { - let img = image::RgbaImage::from_fn(16, 16, |x, _| image::Rgba([255, 0, 0, if x < 8 { 255 } else { 128 }])); - let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let mut data = Vec::with_capacity(16 * 16 * 4); + for _ in 0..16 { + for x in 0..16 { + data.extend_from_slice(&[255, 0, 0, if x < 8 { 255 } else { 128 }]); + } + } + let img = craft_image_codecs::Image::from_raw(16, 16, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, data).unwrap(); + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); for masked in [false, true] { let mut d = Document::new(100.0, 100.0); d.images.insert("pic".into(), ImageBlob::png(png.clone())); diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index cc627bb7e1..ea59a9f53a 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -20,6 +20,6 @@ vectorcraft-svg = { workspace = true } kurbo = { workspace = true } serde_json = { workspace = true } proptest = { workspace = true } -image = { workspace = true } +craft-image-codecs = { workspace = true } # A Group 4 encoder and the T.4 run codes, to write CCITT Group 3 TIFFs (`tiff::group3`). fax = "0.2" diff --git a/crates/testkit/src/raster.rs b/crates/testkit/src/raster.rs index 1dbd9743a0..39ed0ce933 100644 --- a/crates/testkit/src/raster.rs +++ b/crates/testkit/src/raster.rs @@ -18,8 +18,8 @@ impl Image { } /// Decode a PNG. pub fn from_png(bytes: &[u8]) -> Result { - let img = image::load_from_memory_with_format(bytes, image::ImageFormat::Png).map_err(|e| e.to_string())?.to_rgba8(); - Ok(Self { width: img.width(), height: img.height(), rgba: img.into_raw() }) + let img = craft_image_codecs::decode_as(craft_image_codecs::Format::Png, bytes).map_err(|e| e.to_string())?; + Ok(Self { width: img.width(), height: img.height(), rgba: img.to_rgba8() }) } pub fn pixel(&self, x: u32, y: u32) -> [u8; 4] { let i = ((y * self.width + x) * 4) as usize; @@ -41,8 +41,15 @@ impl Image { } /// Save as PNG (for debugging failed comparisons). pub fn save_png(&self, path: &std::path::Path) { - if let Some(img) = image::RgbaImage::from_raw(self.width, self.height, self.rgba.clone()) { - let _ = img.save(path); + if let Ok(img) = craft_image_codecs::Image::from_raw( + self.width, + self.height, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + self.rgba.clone(), + ) && let Ok(png) = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + { + let _ = std::fs::write(path, png); } } /// Luminance over white, 0..255 as f64, per pixel. diff --git a/crates/tools/Cargo.toml b/crates/tools/Cargo.toml index 269b7365d1..ed275a0361 100644 --- a/crates/tools/Cargo.toml +++ b/crates/tools/Cargo.toml @@ -21,7 +21,7 @@ serde = { workspace = true } serde_json = { workspace = true } [dev-dependencies] -image = { workspace = true } +craft-image-codecs = { workspace = true } # The tests lay type out in the bundled fonts (the workspace leaves turning them on to the engine). vectorcraft-text = { workspace = true, features = ["test-fonts", "bundled-fonts"] } # How many times a path is flattened. diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index 8d6788bbbc..a88c14308b 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -1805,9 +1805,15 @@ fn bucket_alt_shift_samples_gradient_image_and_stroke_color() { let mut d = Document::new(500.0, 500.0); let l = d.layers[0].id; - let img = image::RgbaImage::from_raw(3, 1, [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255]].concat()).unwrap(); - let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let img = craft_image_codecs::Image::from_raw( + 3, + 1, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + vec![255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255], + ) + .unwrap(); + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); d.images.insert("px".into(), vectorcraft_doc::ImageBlob::png(png)); let im = vectorcraft_doc::ImageObject { key: "px".into(), diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index c5e05f004b..2f99c8ca0a 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -675,9 +675,15 @@ mod tests { let l = d.layers[0].id; let id = d.alloc_id(); // Three pixels, red, green, blue, 10 pt each. - let img = image::RgbaImage::from_raw(3, 1, [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255]].concat()).unwrap(); - let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let img = craft_image_codecs::Image::from_raw( + 3, + 1, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + vec![255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255], + ) + .unwrap(); + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); d.images.insert("px".into(), ImageBlob::png(png)); let im = ImageObject { key: "px".into(), diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 92a942f4c5..3fbf039ec6 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -46,6 +46,7 @@ egui = { workspace = true, features = ["bytemuck", "default_fonts", "monochrome_ bytemuck = { version = "1", features = ["extern_crate_alloc"] } egui_extras = { workspace = true } image = { workspace = true } +craft-image-codecs = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } log = { workspace = true } diff --git a/crates/ui-egui/src/addons/image/tests.rs b/crates/ui-egui/src/addons/image/tests.rs index 67b5b48ec5..91a6d38adb 100644 --- a/crates/ui-egui/src/addons/image/tests.rs +++ b/crates/ui-egui/src/addons/image/tests.rs @@ -20,7 +20,41 @@ fn app() -> VectorcraftApp { }) }); let mut png = Vec::new(); - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 app = VectorcraftApp::new(Session::new(), Default::default()); app.run("document.open", json!({"name": "art.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); app.run("select.all", json!({})).unwrap(); @@ -36,7 +70,24 @@ fn image(app: &VectorcraftApp) -> (String, Arc>) { /// The alpha of the selected image's pixels at the corner, on the ring and in the block. fn alphas(app: &VectorcraftApp) -> [u8; 3] { - let px = image::load_from_memory(&image(app).1).unwrap().to_rgba8(); + let px = craft_image_codecs::decode(&image(app).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(); [(0, 0), (1, 1), (4, 4)].map(|(x, y)| px.get_pixel(x, y).0[3]) } @@ -66,7 +117,24 @@ fn mask(app: &VectorcraftApp) -> Option /// (all 255 without a mask). fn masked_alphas(app: &VectorcraftApp) -> [u8; 3] { let Some(m) = mask(app) else { return [255; 3] }; - let px = image::load_from_memory(&app.session.doc().unwrap().doc.images[&m.key].bytes).unwrap().to_rgba8(); + let px = craft_image_codecs::decode(&app.session.doc().unwrap().doc.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(); [(0, 0), (1, 1), (4, 4)].map(|(x, y)| px.get_pixel(x, y).0[3]) } diff --git a/crates/ui-egui/src/addons/select/link_status/tests.rs b/crates/ui-egui/src/addons/select/link_status/tests.rs index c0515e048b..2523daf3c4 100644 --- a/crates/ui-egui/src/addons/select/link_status/tests.rs +++ b/crates/ui-egui/src/addons/select/link_status/tests.rs @@ -31,9 +31,41 @@ impl Drop for Folder { /// A `w` × `h` red PNG. fn png(w: u32, h: u32) -> Vec { let mut out = vec![]; - image::RgbaImage::from_pixel(w, h, image::Rgba([200, 40, 40, 255])) - .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(w, h, image::Rgba([200, 40, 40, 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| out.extend_from_slice(&__b)) + } + .unwrap(); out } diff --git a/crates/ui-egui/src/brand.rs b/crates/ui-egui/src/brand.rs index a1ecd3c152..eb9a45043b 100644 --- a/crates/ui-egui/src/brand.rs +++ b/crates/ui-egui/src/brand.rs @@ -9,11 +9,8 @@ const ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/128x128 /// The icon's pixels (one transparent pixel if it couldn't be decoded, which a test rules out). fn decode() -> egui::ColorImage { - match image::load_from_memory_with_format(ICON_PNG, image::ImageFormat::Png) { - Ok(img) => { - let img = img.to_rgba8(); - egui::ColorImage::from_rgba_unmultiplied([img.width() as usize, img.height() as usize], img.as_raw()) - } + match craft_image_codecs::decode_as(craft_image_codecs::Format::Png, ICON_PNG) { + Ok(img) => egui::ColorImage::from_rgba_unmultiplied([img.width() as usize, img.height() as usize], &img.to_rgba8()), Err(_) => egui::ColorImage::filled([1, 1], Color32::TRANSPARENT), } } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 9a5d7fc0b3..75d7e5fd75 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -551,7 +551,41 @@ fn clip_group_app() -> (VectorcraftApp, serde_json::Value, serde_json::Value, se app.ui.view.rulers = false; let img = image::RgbaImage::from_pixel(320, 40, image::Rgba([200, 120, 40, 255])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 data = vectorcraft_format::base64_encode(&png); app.run("file.place", json!({"name": "texture.png", "dataBase64": data, "link": false, "at": [150, 150]})).unwrap(); let image = json!(app.session.active().unwrap().selection.objects[0].0); @@ -625,7 +659,41 @@ fn a_group_of_clipped_images_shows_its_masks_and_their_bounds() { app.ui.view.rulers = false; let img = image::RgbaImage::from_pixel(160, 160, image::Rgba([40, 120, 200, 255])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 data = vectorcraft_format::base64_encode(&png); // Masks 100 × 100 at x = 20, 150, 280, 410; each image reaches 30 past its mask on every side. let masks: Vec = (0..4).map(|i| Rect::new(20.0 + 130.0 * i as f64, 100.0, 120.0 + 130.0 * i as f64, 200.0)).collect(); @@ -3306,7 +3374,41 @@ fn undecodable_images_are_marked_and_reported_once() { let cut = |w: u32| { let img = image::RgbaImage::from_fn(w, 41, |x, y| image::Rgba([(x * 37 + y * 101) as u8, (x * y) as u8, (x ^ y) as u8, 255])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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(); png.truncate(png.len() / 2); png }; @@ -10993,7 +11095,41 @@ fn the_task_bar_traces_an_image_then_expands_the_trace() { app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); let img = image::RgbaImage::from_fn(20, 20, |x, _| image::Rgba(if x < 10 { [0, 0, 0, 255] } else { [255, 255, 255, 255] })); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 data = vectorcraft_format::base64_encode(&png); app.run("file.place", json!({"name": "half.png", "dataBase64": data, "link": false, "at": [200, 150]})).unwrap(); app.select_tool("selection"); @@ -11035,7 +11171,41 @@ fn the_task_bar_removes_a_selected_images_background() { let img = image::RgbaImage::from_fn(20, 20, |x, y| image::Rgba(if (6..14).contains(&x) && (6..14).contains(&y) { [200, 0, 0, 255] } else { [255; 4] })); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 data = vectorcraft_format::base64_encode(&png); app.run("file.place", json!({"name": "dot.png", "dataBase64": data, "link": false, "at": [200, 150]})).unwrap(); app.select_tool("selection"); @@ -11049,7 +11219,24 @@ fn the_task_bar_removes_a_selected_images_background() { assert!(app.ui.dialog.is_none(), "it runs at once"); let st = app.session.active().unwrap(); let Some(NodeKind::Image(im)) = st.selection.objects.first().and_then(|id| st.doc.node(*id)).map(|n| &n.kind) else { panic!("an image") }; - let px = image::load_from_memory(&st.doc.images[&im.key].bytes).unwrap().to_rgba8(); + let px = craft_image_codecs::decode(&st.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!((px.get_pixel(0, 0).0[3], px.get_pixel(10, 10).0[3]), (0, 255), "the white background is cleared, the red dot kept"); } diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index c4ef1a984d..f86ee17f51 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -16,16 +16,18 @@ use egui::{Rect, Sense, Ui, vec2}; use serde_json::{Value, json}; -use vectorcraft_color::cms::{self, Lab}; +use vectorcraft_color::cms; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::ColorMode; use vectorcraft_engine::cmd::color_value; +use vectorcraft_engine::cmd::swatchlib; use super::form::PREVIEWED; use super::{DialogAction, DialogSpec}; use crate::panels::color::{ GAMUT_WARNING, WEB_WARNING, gamut_fix, hex_digits, is_web_safe, parse_hex, warning_chip, web_safe, working_hsb, working_rgb, }; +use crate::panels::swatches::{DOCUMENT_SWATCHES, colour_libraries}; use crate::panels::{c32, color_json}; use crate::state::Dialog; use crate::theme::Tokens; @@ -290,11 +292,22 @@ const RECOLOR_ROW: &str = "__recolorRow"; /// The Color Picker over the Recolor Artwork dialog `parent`, on `color`, the new color of row /// `row`: it previews nothing itself, its OK goes back to `parent` with the row's new color set /// ([`super::recolor::with_new_color`]) and its Cancel goes back to `parent` as it was. -pub(super) fn over_recolor(parent: &Dialog, color: Color, row: usize) -> Dialog { - let mut d = Dialog::new( - KIND, - json!({"original": color_json(&color), "channel": Channel::default().id(), "webOnly": false, "swatches": false, RECOLOR_ROW: row}), - ); +/// When `swatches` is true, the picker opens showing the Swatches view. +pub(super) fn over_recolor(parent: &Dialog, color: Color, row: usize, swatches: bool) -> Dialog { + let mut fields = json!({ + "original": color_json(&color), + "channel": Channel::default().id(), + "webOnly": false, + "swatches": swatches, + RECOLOR_ROW: row, + }); + let lib = parent.str("limitTo"); + if !lib.is_empty() + && let Some(object) = fields.as_object_mut() + { + object.insert("library".into(), json!(lib)); + } + let mut d = Dialog::new(KIND, fields); d.fields.insert(super::PARENT.into(), serde_json::to_value(parent).unwrap_or_default()); store(&mut d, &Picked::of(color)); d.fields.insert(crate::screen_color::PICKER_ID.into(), json!(crate::screen_color::picker_id())); @@ -378,10 +391,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> DialogAction { ui.with_layout(layout, |ui| { ui.spacing_mut().item_spacing.x = 0.0; ui.allocate_ui_with_layout(vec2(side + SLIDER_GAP + SLIDER_W, side), egui::Layout::top_down(egui::Align::Min), |ui| { - ui.horizontal_top(|ui| { - if swatches { - pick = swatch_list(app, ui, &p.color, side).map(Picked::of); - } else { + if swatches { + pick = swatch_list(app, ui, d, &p.color, side).map(Picked::of); + } else { + ui.horizontal_top(|ui| { let (z, x, y) = field_pos(channel, &p); let at = |x: f32, y: f32| c32(&field_pick(channel, z, x, y).snapped(web).color); if let (Some((x, y)), _) = @@ -398,8 +411,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> DialogAction { { pick = Some(field_pick(channel, z, x, y)); } - } - }); + }); + } ui.add_space(8.0); if widgets::check(ui, tl!("Only Web Colors"), web, true) { d.fields.insert("webOnly".into(), json!(!web)); @@ -612,7 +625,7 @@ fn value_fields(ui: &mut Ui, p: &Picked, channel: Channel) -> (Option, O edit = Some(Picked::of(if i < 3 { let mut l = [lab.l, lab.a, lab.b]; l[i] = if i == 0 { nv.clamp(0.0, 100.0) } else { nv.clamp(-128.0, 127.0) }; - cms.from_lab(Lab::new(l[0], l[1], l[2])) + Color::lab(l[0], l[1], l[2]) } else { let mut k = cmyk; k[i - 3] = (nv / 100.0).clamp(0.0, 1.0); @@ -626,37 +639,77 @@ fn value_fields(ui: &mut Ui, p: &Picked, channel: Channel) -> (Option, O (edit, chosen) } -/// The document's colour swatches as a list; returns the clicked swatch's colour. -fn swatch_list(app: &VectorcraftApp, ui: &mut Ui, current: &Color, side: f32) -> Option { +/// The document's colour swatches or a swatch library as a list; returns the clicked swatch's colour. +fn swatch_list(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, current: &Color, side: f32) -> Option { let t = Tokens::get(ui.ctx()); let mut chosen = None; - ui.allocate_ui(vec2(side + SLIDER_GAP + SLIDER_W, side), |ui| { - ui.set_min_size(vec2(side + SLIDER_GAP + SLIDER_W, side)); + let list_w = side + SLIDER_GAP + SLIDER_W; + ui.allocate_ui_with_layout(vec2(list_w, side), egui::Layout::top_down(egui::Align::Min), |ui| { + ui.set_min_size(vec2(list_w, side)); + let libs = colour_libraries(app); + let keys: Vec<&str> = [swatchlib::DOCUMENT_SWATCHES].into_iter().chain(libs.iter().map(|l| l.id.as_str())).collect(); + let names: Vec<&str> = [DOCUMENT_SWATCHES].into_iter().chain(libs.iter().map(|l| l.name.as_str())).collect(); + let builtin = |k: usize| k.checked_sub(1).is_none_or(|i| libs.get(i).is_some_and(|l| l.submenu.is_none())); + let shown = super::shown_names(crate::i18n::current(), &names, builtin); + let cur = d.str("library"); + let cur = if cur.is_empty() { swatchlib::DOCUMENT_SWATCHES } else { &cur }; + let at = keys.iter().position(|k| *k == cur).unwrap_or(0); + let current_label = shown.get(at).copied().unwrap_or_default(); + if let Some(i) = widgets::dropdown_names(ui, "cp-library", current_label, &shown, list_w) + && let Some(&k) = keys.get(i) + { + d.fields.insert("library".into(), json!(k)); + } + ui.add_space(4.0); widgets::list_box(ui, |ui| { - egui::ScrollArea::vertical().id_salt("cp-swatches").max_height((side - 8.0).max(1.0)).show(ui, |ui| { - ui.set_width(side + SLIDER_GAP + SLIDER_W - 8.0); - let Some(st) = app.session.active() else { - widgets::dim_label(ui, tl!("Open a document to see its swatches.")); - return; - }; - let doc = &st.doc; - for s in doc.swatches.iter().chain(doc.swatch_groups.iter().flat_map(|g| g.swatches.iter())) { - let Paint::Solid { color, .. } = &s.paint else { continue }; - let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click()); - if resp.hovered() { - ui.painter().rect_filled(r, 0.0, t.hover); + let max_h = (side - 28.0).max(1.0); + egui::ScrollArea::vertical().id_salt("cp-swatches").max_height(max_h).show(ui, |ui| { + ui.set_width(list_w - 8.0); + let cur = d.str("library"); + if cur.is_empty() || cur == swatchlib::DOCUMENT_SWATCHES { + let Some(st) = app.session.active() else { + widgets::dim_label(ui, tl!("Open a document to see its swatches.")); + return; + }; + let doc = &st.doc; + for s in doc.swatches.iter().chain(doc.swatch_groups.iter().flat_map(|g| g.swatches.iter())) { + let Some(color) = s.paint.color() else { continue }; + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click()); + if resp.hovered() { + ui.painter().rect_filled(r, 0.0, t.hover); + } + let chip = Rect::from_min_size(r.left_center() + vec2(4.0, -7.0), vec2(14.0, 14.0)); + widgets::swatch_tile(ui, chip, &s.paint, color == *current, false); + ui.painter().text( + egui::pos2(chip.right() + 8.0, r.center().y), + egui::Align2::LEFT_CENTER, + &s.name, + egui::FontId::proportional(12.0), + t.text, + ); + if resp.clicked() { + chosen = Some(color); + } } - let chip = Rect::from_min_size(r.left_center() + vec2(4.0, -7.0), vec2(14.0, 14.0)); - widgets::swatch_tile(ui, chip, &s.paint, color == current, false); - ui.painter().text( - egui::pos2(chip.right() + 8.0, r.center().y), - egui::Align2::LEFT_CENTER, - &s.name, - egui::FontId::proportional(12.0), - t.text, - ); - if resp.clicked() { - chosen = Some(*color); + } else if let Some((_, lib)) = swatchlib::library(&app.session, &cur) { + for s in lib.swatches.iter().chain(lib.groups.iter().flat_map(|g| g.swatches.iter())) { + let Some(color) = s.paint.color() else { continue }; + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click()); + if resp.hovered() { + ui.painter().rect_filled(r, 0.0, t.hover); + } + let chip = Rect::from_min_size(r.left_center() + vec2(4.0, -7.0), vec2(14.0, 14.0)); + widgets::swatch_tile(ui, chip, &s.paint, color == *current, false); + ui.painter().text( + egui::pos2(chip.right() + 8.0, r.center().y), + egui::Align2::LEFT_CENTER, + &s.name, + egui::FontId::proportional(12.0), + t.text, + ); + if resp.clicked() { + chosen = Some(color); + } } } }); diff --git a/crates/ui-egui/src/dialogs/color_picker/tests.rs b/crates/ui-egui/src/dialogs/color_picker/tests.rs index 5587b9c560..0786df7ca9 100644 --- a/crates/ui-egui/src/dialogs/color_picker/tests.rs +++ b/crates/ui-egui/src/dialogs/color_picker/tests.rs @@ -774,3 +774,47 @@ fn compact_picker_shrinks_then_scrolls_without_enlarging_the_window() { assert!(app.ui.dialog.is_none()); } } + +/// Type all three Lab components through the numeric fields, then apply the picked color. +#[test] +fn native_lab_entry_in_color_picker() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + + let mut app = app(); + app.run("ui.colorPicker", json!({"color": {"l": 50, "a": 0, "b": 0}})).unwrap(); + let mut first = true; + let builder = egui_kittest::Harness::builder().with_size(screen()); + let builder = if std::env::var_os("VECTORCRAFT_RECOLOR_CAPTURE_DIR").is_some() { builder.wgpu() } else { builder }; + let mut h = builder.build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if std::mem::replace(&mut first, false) { + crate::theme::install_fonts(ui.ctx()); + return; + } + super::super::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + for (label, text) in [("L", "70"), ("a", "-25"), ("b", "40")] { + h.get_by_role_and_label(Role::TextInput, label).focus(); + h.run_steps(2); + h.key_press_modifiers(egui::Modifiers { ctrl: true, command: true, ..Default::default() }, egui::Key::A); + h.get_by_role_and_label(Role::TextInput, label).type_text(text); + h.key_press(egui::Key::Tab); + h.run_steps(2); + assert!(matches!(picked(h.state().ui.dialog.as_ref().unwrap()).color, Color::Lab { .. }), "{label} keeps Lab"); + } + let expected = Color::lab(70.0, -25.0, 40.0); + assert_eq!(picked(h.state().ui.dialog.as_ref().unwrap()).color, expected); + if let Some(dir) = std::env::var_os("VECTORCRAFT_RECOLOR_CAPTURE_DIR") { + let dir = std::path::PathBuf::from(dir); + std::fs::create_dir_all(&dir).unwrap(); + h.render().unwrap().save(dir.join("picker-lab.png")).unwrap(); + } + h.get_by_role_and_label(Role::Button, "OK").click(); + h.run_steps(2); + assert!(h.state().ui.dialog.is_none()); + assert_eq!(crate::panels::current_paints(h.state()).0.color(), Some(expected)); +} diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 9e918fe092..f5215092e8 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -385,7 +385,8 @@ mod tests { Some(NodeKind::Image(i)) => Some(i.key.clone()), _ => None, }); - let img = image::load_from_memory(&st.doc.images[&key.expect("the rectangle became an image")].bytes).unwrap().to_rgba8(); + let decoded = craft_image_codecs::decode(&st.doc.images[&key.expect("the rectangle became an image")].bytes).unwrap(); + let img = image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap(); let p = img.get_pixel(img.width() / 2, img.height() / 2).0; assert!(p[0] == p[1] && p[1] == p[2] && p[0] < 128, "red in grayscale: {p:?}"); } diff --git a/crates/ui-egui/src/dialogs/find_links/tests.rs b/crates/ui-egui/src/dialogs/find_links/tests.rs index 650f403542..c582154173 100644 --- a/crates/ui-egui/src/dialogs/find_links/tests.rs +++ b/crates/ui-egui/src/dialogs/find_links/tests.rs @@ -42,9 +42,41 @@ fn write(path: &Path, bytes: &[u8]) { /// A PNG of one color, a different one for each `n`. fn png(n: u8) -> Vec { let mut out = vec![]; - image::RgbaImage::from_pixel(40, 30, image::Rgba([200, n.wrapping_mul(40), 0, 255])) - .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(40, 30, image::Rgba([200, n.wrapping_mul(40), 0, 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| out.extend_from_slice(&__b)) + } + .unwrap(); out } diff --git a/crates/ui-egui/src/dialogs/flatten.rs b/crates/ui-egui/src/dialogs/flatten.rs index 4859348935..0c5bc7dbee 100644 --- a/crates/ui-egui/src/dialogs/flatten.rs +++ b/crates/ui-egui/src/dialogs/flatten.rs @@ -335,10 +335,15 @@ mod tests { fn ok_says_in_the_status_bar_when_an_image_could_not_be_decoded() { const WARNING: &str = "an image couldn't be decoded and is missing from the picture"; // A PNG whose header reads but whose pixel data is cut short. - let mut png = Vec::new(); - image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + let img = craft_image_codecs::Image::from_raw( + 64, + 32, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + [200u8, 30, 30, 255].repeat(64 * 32), + ) + .unwrap(); + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); for preview in [true, false] { let mut app = scene(); let placed = vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &png, json!({})); diff --git a/crates/ui-egui/src/dialogs/indexed_color.rs b/crates/ui-egui/src/dialogs/indexed_color.rs index 6ef266c06c..90856d963c 100644 --- a/crates/ui-egui/src/dialogs/indexed_color.rs +++ b/crates/ui-egui/src/dialogs/indexed_color.rs @@ -97,9 +97,15 @@ mod tests { fn commits_the_chosen_palette_as_one_step() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); - let mut png = Vec::new(); - let img = image::RgbaImage::from_raw(2, 1, vec![200, 30, 90, 255, 20, 40, 220, 255]).unwrap(); - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let img = craft_image_codecs::Image::from_raw( + 2, + 1, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + vec![200, 30, 90, 255, 20, 40, 220, 255], + ) + .unwrap(); + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); let id = app .session .edit("Place", |d, sel| { diff --git a/crates/ui-egui/src/dialogs/missing_fonts/tests.rs b/crates/ui-egui/src/dialogs/missing_fonts/tests.rs index b173deb49c..e650e3e3ce 100644 --- a/crates/ui-egui/src/dialogs/missing_fonts/tests.rs +++ b/crates/ui-egui/src/dialogs/missing_fonts/tests.rs @@ -28,9 +28,41 @@ fn app_for(root: &Path) -> VectorcraftApp { fn png() -> Vec { let mut out = vec![]; - image::RgbaImage::from_pixel(40, 30, image::Rgba([200, 0, 0, 255])) - .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(40, 30, image::Rgba([200, 0, 0, 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| out.extend_from_slice(&__b)) + } + .unwrap(); out } diff --git a/crates/ui-egui/src/dialogs/missing_links.rs b/crates/ui-egui/src/dialogs/missing_links.rs index 5cf08aa84a..702db0c14f 100644 --- a/crates/ui-egui/src/dialogs/missing_links.rs +++ b/crates/ui-egui/src/dialogs/missing_links.rs @@ -293,12 +293,16 @@ mod tests { } fn png(rgb: [u8; 3]) -> Vec { - let mut out = vec![]; let [r, g, b] = rgb; - image::RgbaImage::from_pixel(400, 300, image::Rgba([r, g, b, 255])) - .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png) - .unwrap(); - out + let img = craft_image_codecs::Image::from_raw( + 400, + 300, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + [r, g, b, 255].repeat(400 * 300), + ) + .unwrap(); + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() } /// A document with two placed linked files, saved to a fresh folder; the files are then diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index e617c1710f..6d45b1e416 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -799,8 +799,11 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { None => form::preview(app, ui, d, "Recolor Artwork", CMD, apply_params(d)), } } - if let Some(c) = pick.and_then(|i| Some((i, to_color(rows(d).get(i)?)?))) { - *d = super::color_picker::over_recolor(d, c.1, c.0); + if let Some((i, swatches)) = pick + && let Some(row) = rows(d).get(i) + { + let c = to_color(row).or_else(|| from_colors(row).first().copied()).unwrap_or_default(); + *d = super::color_picker::over_recolor(d, c, i, swatches); } false } @@ -868,8 +871,8 @@ fn chip(ui: &Ui, r: Rect, c: Color, dim: bool) { } /// The Assign tab. Returns true when the rows changed, and the row whose new colour was -/// double-clicked. -fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut Vec) -> (bool, Option) { +/// double-clicked or chosen via "Pick from Swatches" (with `true` for swatches view). +fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut Vec) -> (bool, Option<(usize, bool)>) { let t = Tokens::get(ui.ctx()); let mut changed = false; let total: usize = rows.iter().map(|r| r["from"].as_array().map_or(0, Vec::len)).sum(); @@ -907,7 +910,8 @@ fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut }); let mut sel = selection(d); let mut clicked: Option = None; - let mut pick: Option = None; + let mut pick: Option<(usize, bool)> = None; + let mut limit_to: Option = None; let shown: Vec = rows.iter().map(|r| new_shown(app, d, r)).collect(); widgets::list_box(ui, |ui| { egui::ScrollArea::vertical().id_salt("recolor-rows").max_height(TABLE_H).show(ui, |ui| { @@ -956,7 +960,7 @@ fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut clicked = Some(i); } if nresp.double_clicked() && has_new { - pick = Some(i); + pick = Some((i, false)); } ui.add_space(6.0); let hex = if has_new { crate::panels::color::hex_digits(&to) } else { String::new() }; @@ -967,6 +971,40 @@ fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut set_to(row, &keep_model(to, c)); changed = true; } + let mut row_menu = |ui: &mut Ui| { + if widgets::menu_item(ui, tl!("Pick from Swatches"), true, false) { + pick = Some((i, true)); + ui.close(); + } + ui.menu_button(tl!("Limit to Library"), |ui| { + let cur = d.str("limitTo"); + if widgets::menu_item(ui, tl!("None"), true, cur.is_empty()) { + limit_to = Some("".to_string()); + ui.close(); + } + ui.separator(); + if let Some(k) = crate::panels::swatches::library_list(app, ui, &cur) { + limit_to = Some(k); + ui.close(); + } + }); + }; + if (cr.secondary_clicked() || nresp.secondary_clicked()) && !sel.contains(&i) { + clicked = Some(i); + } + cr.context_menu(&mut row_menu); + nresp.context_menu(&mut row_menu); + let empty_w = ui.available_width(); + if empty_w > 0.0 { + let (_, empty_resp) = ui.allocate_exact_size(vec2(empty_w, 20.0), Sense::click()); + if empty_resp.clicked() { + clicked = Some(i); + } + if empty_resp.secondary_clicked() && !sel.contains(&i) { + clicked = Some(i); + } + empty_resp.context_menu(&mut row_menu); + } }); if sel.contains(&i) { ui.painter().set(bg, egui::Shape::rect_filled(r.response.rect.expand2(vec2(2.0, 1.0)), 2.0, t.row_selected)); @@ -974,6 +1012,10 @@ fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut } }); }); + if let Some(k) = limit_to { + d.fields.insert("limitTo".into(), json!(k)); + changed = true; + } if let Some(i) = clicked { let m = ui.input(|i| i.modifiers); match sel.iter().position(|s| *s == i) { @@ -2176,6 +2218,14 @@ mod tests { crate::dialogs::confirm(&mut app).unwrap(); let to = super::rows(app.ui.dialog.as_ref().unwrap())[i]["to"].clone(); assert!(to.as_str().is_some_and(|k| k.starts_with("cmyk ")), "a color picked as RGB is CMYK in a CMYK document: {to}"); + + let rect = settled(&mut app, &ctx, 3.0, i).unwrap(); + double_click(&mut app, &ctx, rect, 3.1, i); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("color".into(), json!({"l": 55.0, "a": 20.0, "b": -30.0})); + crate::dialogs::confirm(&mut app).unwrap(); + let to = super::rows(app.ui.dialog.as_ref().unwrap())[i]["to"].clone(); + assert_eq!(to, "lab 55 20 -30", "a Lab color picked in the picker is kept as Lab: {to}"); } /// A 15 pt square at (`x`, 10) filled with `fill`, without a stroke. diff --git a/crates/ui-egui/src/dialogs/relink.rs b/crates/ui-egui/src/dialogs/relink.rs index ceca12c04a..1f2591b9d7 100644 --- a/crates/ui-egui/src/dialogs/relink.rs +++ b/crates/ui-egui/src/dialogs/relink.rs @@ -158,12 +158,16 @@ mod tests { } fn png(rgb: [u8; 3]) -> Vec { - let mut out = vec![]; let [r, g, b] = rgb; - image::RgbaImage::from_pixel(40, 30, image::Rgba([r, g, b, 255])) - .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png) - .unwrap(); - out + let img = craft_image_codecs::Image::from_raw( + 40, + 30, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + [r, g, b, 255].repeat(40 * 30), + ) + .unwrap(); + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() } /// A fresh folder with the PNG files `names` → (app with a document, folder). diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index dbceed5881..b73ec294b1 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -287,9 +287,41 @@ fn an_image_that_couldnt_be_decoded_is_named_in_the_status() { let (mut app, written, _) = app(); // A PNG whose header reads but whose pixel data is cut short. let mut png = vec![]; - image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 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(); // The image is placed on the first artboard. vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &png, json!({"at": [60, 50]})); app.run("ui.savePdfDialog", json!({"path": "/tmp/cut.pdf"})).unwrap(); diff --git a/crates/ui-egui/src/dialogs/tests_export.rs b/crates/ui-egui/src/dialogs/tests_export.rs index f8a2e05515..60a205b907 100644 --- a/crates/ui-egui/src/dialogs/tests_export.rs +++ b/crates/ui-egui/src/dialogs/tests_export.rs @@ -80,7 +80,24 @@ fn png_options_draw_and_export_with_the_chosen_options() { assert_eq!(png[28], 1, "interlaced"); let phys = png.windows(4).position(|w| w == b"pHYs").unwrap(); assert_eq!(&png[phys + 4..phys + 8], ((200.0f64 / 0.0254).round() as u32).to_be_bytes()); - let img = image::load_from_memory(&png).unwrap().to_rgba8(); + 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() + .to_rgba8(); assert_eq!(img.dimensions(), (167, 111), "60 × 40 pt at 200 ppi"); assert_eq!(img.get_pixel(0, 0).0, [0x20, 0x40, 0x80, 255]); // JPEG Options: quality, and no transparent background. @@ -112,7 +129,28 @@ fn export_as_png_picks_the_file_then_shows_png_options() { fn export_as_png_exports_the_active_artboard() { let (mut app, written) = app(2); // The ellipse is on the first artboard; the second is empty. - let opaque = |bytes: &[u8]| image::load_from_memory(bytes).unwrap().to_rgba8().pixels().any(|p| p.0[3] > 0); + let opaque = |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() + .pixels() + .any(|p| p.0[3] > 0) + }; app.view_mut().unwrap().artboard = 1; app.run("file.export.png", json!({})).unwrap(); assert_eq!(app.ui.dialog.as_ref().unwrap().fields["artboard"], json!(1)); @@ -165,7 +203,24 @@ fn export_as_with_a_range_then_png_options_writes_one_file_per_artboard() { assert_eq!(names(&written), ["/out/Untitled-1-Artboard-1.png", "/out/Untitled-1-Artboard-3.png"]); let png = &written.borrow()[0].1; assert_eq!(png[28], 1, "interlaced"); - let img = image::load_from_memory(png).unwrap().to_rgba8(); + 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() + .to_rgba8(); assert_eq!(img.dimensions(), (120, 80), "144 ppi"); assert!(img.pixels().all(|p| p[3] == 0 || p[3] == 255), "no anti-aliasing"); } @@ -256,7 +311,24 @@ fn jpeg_and_webp_options_draw_and_export() { set(&mut app, "quality", json!(70)); frame(&mut app); assert_eq!(confirm(&mut app).unwrap()["path"], "/out/Untitled-1.jpg"); - let img = image::load_from_memory(&written.borrow()[0].1).unwrap().to_rgb8(); + let img = craft_image_codecs::decode(&written.borrow()[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_rgb8(); assert_eq!(img.dimensions(), (30, 20)); let px = img.get_pixel(0, 0); assert!(px[2] > 100 && px[0] < 60, "the background colour: {px:?}"); @@ -271,7 +343,27 @@ fn jpeg_and_webp_options_draw_and_export() { confirm(&mut app).unwrap(); let (path, bytes) = written.borrow().last().cloned().unwrap(); assert_eq!(path, "/out/Untitled-1.webp", "one artboard is one file, named as picked"); - assert_eq!(image::load_from_memory(&bytes).unwrap().width(), 30); + assert_eq!( + 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() + .width(), + 30 + ); } #[test] diff --git a/crates/ui-egui/src/dialogs/tests_export_selection.rs b/crates/ui-egui/src/dialogs/tests_export_selection.rs index 15fe559974..0500a55760 100644 --- a/crates/ui-egui/src/dialogs/tests_export_selection.rs +++ b/crates/ui-egui/src/dialogs/tests_export_selection.rs @@ -206,7 +206,26 @@ fn rich_black_reaches_files_from_the_export_dialogs() { app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 30})).unwrap(); let px = |w: &Written| { let w = w.borrow(); - image::load_from_memory(&w.last().unwrap().1).unwrap().to_rgba8().get_pixel(10, 10).0 + craft_image_codecs::decode(&w.last().unwrap().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 }; app.run("file.exportAs", json!({"path": "/out/all.png"})).unwrap(); let accurate = px(&written); diff --git a/crates/ui-egui/src/dialogs/tests_package.rs b/crates/ui-egui/src/dialogs/tests_package.rs index acd1368ed4..0c0f8e492a 100644 --- a/crates/ui-egui/src/dialogs/tests_package.rs +++ b/crates/ui-egui/src/dialogs/tests_package.rs @@ -43,9 +43,41 @@ fn saved(dir: &Folder) -> VectorcraftApp { app.services.write = Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))); app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); let mut png = vec![]; - image::RgbaImage::from_pixel(300, 300, 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(300, 300, 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(); std::fs::write(dir.path("pic.png"), &png).unwrap(); app.run("file.place", json!({"path": dir.path("pic.png")})).unwrap(); app.run("document.save", json!({"path": dir.path("card.vectorcraft")})).unwrap(); diff --git a/crates/ui-egui/src/dialogs/tests_raster_formats.rs b/crates/ui-egui/src/dialogs/tests_raster_formats.rs index b69c6bdbcd..5b2695f307 100644 --- a/crates/ui-egui/src/dialogs/tests_raster_formats.rs +++ b/crates/ui-egui/src/dialogs/tests_raster_formats.rs @@ -123,14 +123,48 @@ fn save_for_office_documents_picks_the_resolution() { set(&mut app, "transparent", json!(true)); frame(&mut app); assert_eq!(confirm(&mut app).unwrap()["path"], "/out/Untitled-1.png"); - let img = image::load_from_memory(&written.borrow()[0].1).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&written.borrow()[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(); assert_eq!(img.dimensions(), (250, 167), "60 × 40 pt at 300 ppi"); assert_eq!(img.get_pixel(0, 0)[3], 0, "transparent"); // With a path (agents), no dialog. let r = app.run("document.exportForOffice", json!({"path": "/x/o.png", "ppi": 72})).unwrap(); assert_eq!(r["path"], "/x/o.png"); assert!(app.ui.dialog.is_none()); - let img = image::load_from_memory(&written.borrow()[1].1).unwrap().to_rgba8(); + let img = craft_image_codecs::decode(&written.borrow()[1].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(); assert_eq!((img.dimensions(), img.get_pixel(0, 0).0), ((60, 40), [255, 255, 255, 255])); } @@ -142,9 +176,41 @@ fn save_for_office_and_export_selection_say_when_an_image_could_not_be_decoded() assert_eq!(app.ui.status, "Saved /x/o.png"); // A PNG whose header reads but whose pixel data is cut short. let mut png = Vec::new(); - image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 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(); vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &png, json!({"at": [10, 10]})); app.run("document.exportForOffice", json!({"path": "/x/o.png", "ppi": 72})).unwrap(); assert_eq!(app.ui.status, format!("Saved /x/o.png {NOTE}")); diff --git a/crates/ui-egui/src/dialogs/tests_save_for_web.rs b/crates/ui-egui/src/dialogs/tests_save_for_web.rs index c76ed412fa..dd904bfa53 100644 --- a/crates/ui-egui/src/dialogs/tests_save_for_web.rs +++ b/crates/ui-egui/src/dialogs/tests_save_for_web.rs @@ -590,9 +590,41 @@ fn saving_says_in_the_status_bar_when_an_image_could_not_be_decoded() { const NOTE: &str = "with 1 note: an image couldn't be decoded and is missing from the picture"; // A PNG whose header reads but whose pixel data is cut short: the renderer draws nothing for it. let mut png = Vec::new(); - image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 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 place = |app: &mut VectorcraftApp| vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &png, json!({"at": [30, 20]})); let dir = vectorcraft_testkit::temp_dir("sfw-undecoded"); let (mut desktop, _) = app(&dir, false); diff --git a/crates/ui-egui/src/dialogs/tests_screen_assets.rs b/crates/ui-egui/src/dialogs/tests_screen_assets.rs index df218bd0a0..14f324ee98 100644 --- a/crates/ui-egui/src/dialogs/tests_screen_assets.rs +++ b/crates/ui-egui/src/dialogs/tests_screen_assets.rs @@ -114,7 +114,23 @@ fn the_assets_tab_exports_the_checked_assets_into_the_folder() { let r = confirm(&mut app).unwrap(); // Create Sub-folders is on by default: a folder per scale. assert_eq!(r["files"], json!([format!("{folder}/2x/Asset-2@2x.png")])); - let png = image::load_from_memory(&std::fs::read(dir.join("2x").join("Asset-2@2x.png")).unwrap()).unwrap(); + let png = craft_image_codecs::decode(&std::fs::read(dir.join("2x").join("Asset-2@2x.png")).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!((png.width(), png.height()), (60, 40), "the asset's art at 2x"); assert_eq!(log.borrow().len(), 1, "Open Location shows the file"); // The rows are remembered for the dialog and the Asset Export panel alike. diff --git a/crates/ui-egui/src/dialogs/tests_screens.rs b/crates/ui-egui/src/dialogs/tests_screens.rs index b99405ecfe..496d73aa68 100644 --- a/crates/ui-egui/src/dialogs/tests_screens.rs +++ b/crates/ui-egui/src/dialogs/tests_screens.rs @@ -242,7 +242,23 @@ fn exports_into_the_folder_and_shows_it() { assert!(app.ui.dialog.is_none()); let files: Vec<&str> = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).collect(); assert_eq!(files, [format!("{folder}/1x/Artboard-2.png"), format!("{folder}/120w/Artboard-2@120w.png"), format!("{folder}/SVG/Artboard-2.svg")]); - let png = image::load_from_memory(&std::fs::read(dir.join("120w").join("Artboard-2@120w.png")).unwrap()).unwrap(); + let png = craft_image_codecs::decode(&std::fs::read(dir.join("120w").join("Artboard-2@120w.png")).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!((png.width(), png.height()), (120, 80)); assert_eq!(log.borrow().iter().map(|(p, _)| p.as_str()).collect::>(), [files[0]], "Open Location shows the first file"); // It reopens on those settings. @@ -507,7 +523,30 @@ fn the_web_downloads_one_zip_or_the_file() { let log = log.borrow(); assert_eq!(log.len(), 1); assert_eq!(log[0].0, "Artboard-1.png"); - assert_eq!(image::load_from_memory(&log[0].1).unwrap().to_rgba8().get_pixel(1, 1).0, [0, 0, 0, 255], "the PNG settings' background"); + assert_eq!( + craft_image_codecs::decode(&log[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(1, 1) + .0, + [0, 0, 0, 255], + "the PNG settings' background" + ); } /// Include Artboard Fill: checked, the file shows the artboard's background color behind the art @@ -524,7 +563,26 @@ fn include_artboard_fill_reaches_the_files_and_is_remembered() { set(&mut app, "settings", json!({"png": {"background": "transparent"}})); frame(&mut app); confirm(&mut app).unwrap(); - let px = image::load_from_memory(&log.borrow()[0].1).unwrap().to_rgba8().get_pixel(58, 38).0; + let px = craft_image_codecs::decode(&log.borrow()[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(58, 38) + .0; assert_eq!(px, if include { [255, 0, 0, 255] } else { [0, 0, 0, 0] }, "include {include}"); if include { continue; @@ -539,9 +597,41 @@ fn the_status_bar_says_when_an_image_could_not_be_decoded() { const NOTE: &str = "with 1 note: an image couldn't be decoded and is missing from the picture"; // A PNG whose header reads but whose pixel data is cut short: the renderer draws nothing for it. let mut png = Vec::new(); - image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 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 place = |app: &mut VectorcraftApp| vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &png, json!({"at": [10, 10]})); let rows = json!([{"format": "png", "scale": "1x", "suffix": ""}, {"format": "jpg", "scale": "2x", "suffix": "@2x"}]); let dir = temp_folder("undecoded"); @@ -572,9 +662,41 @@ fn the_status_bar_says_when_an_image_could_not_be_decoded() { #[test] fn an_export_into_a_folder_keeps_every_note_for_the_hover() { let mut png = Vec::new(); - image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 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 dir = temp_folder("notes"); let folder = dir.to_string_lossy().replace('\\', "/"); let rows = json!([{"format": "png", "scale": "1x", "suffix": ""}]); @@ -788,7 +910,23 @@ fn saved_tiff_alias_gear(alias: &str, asset_panel: bool) { assert!(tags.contains(&(259, 3, 1, 1)), "saved uncompressed option survives"); assert!(tags.contains(&(262, 3, 1, 2)), "saved RGB survives"); assert!(!tags.iter().any(|t| t.0 == 34675), "saved profile-off option survives"); - let img = image::load_from_memory_with_format(bytes, image::ImageFormat::Tiff).unwrap(); + let img = craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, 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(); assert_eq!((img.width(), img.height()), if asset_panel { (60, 40) } else { (120, 80) }); } let saved = app.run("document.exportSettings", json!({})).unwrap()["settings"].clone(); @@ -859,7 +997,24 @@ fn tiff_dropdown_exports_scaled_artboards_with_options_and_reopens() { assert!(tags.contains(&(259, 3, 1, 1)), "uncompressed as selected"); assert!(tags.contains(&(262, 3, 1, 2)), "RGB"); assert!(!tags.iter().any(|t| t.0 == 34675), "ICC profile disabled"); - let img = image::load_from_memory_with_format(bytes, image::ImageFormat::Tiff).unwrap().to_rgba8(); + let img = craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, 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!(img.dimensions(), (120, 80)); assert_eq!(img.get_pixel(0, 0).0[3], 0, "transparent board corner"); let inside = img.get_pixel(40, 28).0; diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 71e443a399..613d5cd1e3 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6820,6 +6820,11 @@ breakText Glyphs Глифи Malayalam Малаялам Odia Ория Urdu Урду + Sanskrit Санскрит + Nepali Непалски + Assamese Асамски + Konkani Конкани + Sindhi Синдхи VectorCraft {release} and later (version {n}) VectorCraft {release} и по-нови (версия {n}) # Document Tools add-on: Export All Open Documents (#4920). Export All Open Documents as PDF Експортиране на всички отворени документи като PDF diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 883d6dd387..fcc034cd0f 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6872,6 +6872,11 @@ shape Open Otvoren Malayalam Malajalam Odia Odija Urdu Urdu + Sanskrit Sanskrit + Nepali Nepalski + Assamese Asamski + Konkani Konkani + Sindhi Sindi VectorCraft {release} and later (version {n}) VectorCraft {release} i novije (verzija {n}) # Document Tools add-on: Export All Open Documents (#4920). Export All Open Documents as PDF Izvezi sve otvorene dokumente kao PDF diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a8a63cbf55..ac55a78ff4 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7523,6 +7523,11 @@ breakText Glyphs Glifs Malayalam Malaiàlam Odia Oriya Urdu Urdú + Sanskrit Sànscrit + Nepali Nepalès + Assamese Assamès + Konkani Concani + Sindhi Sindi VectorCraft {release} and later (version {n}) VectorCraft {release} i posteriors (versió {n}) # Document Tools add-on: Export All Open Documents (#4920). Export All Open Documents as PDF Exporta tots els documents oberts com a PDF diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 569b1347ec..69dd46dc23 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7514,6 +7514,11 @@ breakText Glyphs Glyfy Malayalam Malajálamština Odia Urijština Urdu Urdština + Sanskrit Sanskrt + Nepali Nepálština + Assamese Ásámština + Konkani Konkánština + Sindhi Sindhština VectorCraft {release} and later (version {n}) VectorCraft {release} a novější (verze {n}) # Document Tools add-on: Export All Open Documents (#4920). Export All Open Documents as PDF Exportovat všechny otevřené dokumenty jako PDF diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4578e4efc1..7bc0ed6c94 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -9567,6 +9567,11 @@ breakText Glyphs Glyffer Malayalam Malayalam Odia Oriya Urdu Urdu + Sanskrit Sanskrit + Nepali Nepalesisk + Assamese Assamesisk + Konkani Konkani + Sindhi Sindhi VectorCraft {release} and later (version {n}) VectorCraft {release} og nyere (version {n}) # Document Tools add-on: Export All Open Documents (#4920). Export All Open Documents as PDF Eksportér alle åbne dokumenter som PDF diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c943c89dd2..4b17261bfb 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -7105,6 +7105,11 @@ breakText Glyphs Glyphen Malayalam Malayalam Odia Oriya Urdu Urdu + Sanskrit Sanskrit + Nepali Nepalesisch + Assamese Assamesisch + Konkani Konkani + Sindhi Sindhi VectorCraft {release} and later (version {n}) VectorCraft {release} und neuer (Version {n}) # Document Tools add-on: Export All Open Documents (#4920). Export All Open Documents as PDF Alle geöffneten Dokumente als PDF exportieren diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 906640aa0a..bba8d392ad 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7496,6 +7496,11 @@ breakText Glyphs Γλύφοι Malayalam Μαλαγιάλαμ Odia Όντια Urdu Ούρντου + Sanskrit Σανσκριτικά + Nepali Νεπαλικά + Assamese Ασαμικά + Konkani Κονκανικά + Sindhi Σίντι VectorCraft {release} and later (version {n}) VectorCraft {release} και νεότερες (έκδοση {n}) # Document Tools add-on: Export All Open Documents (#4920). Export All Open Documents as PDF Εξαγωγή όλων των ανοιχτών εγγράφων ως PDF diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9239c93a73..57e7f44e87 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7484,6 +7484,11 @@ breakText Glyphs Glifos Malayalam Malayálam Odia Oriya Urdu Urdu + Sanskrit Sánscrito + Nepali Nepalí + Assamese Asamés + Konkani Konkaní + Sindhi Sindi VectorCraft {release} and later (version {n}) VectorCraft {release} y posteriores (versión {n}) # Document Tools add-on: Export All Open Documents (#4920). Export All Open Documents as PDF Exportar todos los documentos abiertos como PDF diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 423703e5c1..0276e5b6ed 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7572,6 +7572,11 @@ breakText Glyphs Merkit Malayalam Malajalam Odia Orija Urdu Urdu + Sanskrit Sanskrit + Nepali Nepali + Assamese Assami + Konkani Konkani + Sindhi Sindhi VectorCraft {release} and later (version {n}) VectorCraft {release} ja uudemmat (versio {n}) # Document Tools add-on: Export All Open Documents (#4920). Export All Open Documents as PDF Vie kaikki avoimet asiakirjat PDF-muodossa diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8af602785b..75f4f14c6f 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7464,9 +7464,9 @@ breakText Glyphs Glyphes @msg a selected path has no area un tracé sélectionné n’a pas de surface @msg a selected path has more than 10000 segments un tracé sélectionné a plus de 10000 segments @msg the two paths have the same outline les deux tracés ont le même contour -@msg One path lies inside the other, so they have no common tangents Un tracé se trouve à l’intérieur de l’autre : ils n’ont donc aucune tangente commune -@msg The paths overlap, so they have no internal tangents Les tracés se chevauchent : ils n’ont donc aucune tangente interne -@msg One path lies inside the other, so they have no internal tangents Un tracé se trouve à l’intérieur de l’autre : ils n’ont donc aucune tangente interne +@msg One path lies inside the other, so they have no common tangents Un tracé se trouve à l’intérieur de l’autre : ils n’ont donc aucune tangente commune +@msg The paths overlap, so they have no internal tangents Les tracés se chevauchent : ils n’ont donc aucune tangente interne +@msg One path lies inside the other, so they have no internal tangents Un tracé se trouve à l’intérieur de l’autre : ils n’ont donc aucune tangente interne # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Décomposer les tirets en tracés @msg select paths with dashed strokes to expand sélectionnez des tracés à contour pointillé à décomposer @@ -7509,6 +7509,11 @@ breakText Glyphs Glyphes Malayalam Malayalam Odia Odia Urdu Ourdou + Sanskrit Sanskrit + Nepali Népalais + Assamese Assamais + Konkani Konkani + Sindhi Sindhi VectorCraft {release} and later (version {n}) VectorCraft {release} et ultérieures (version {n}) # Document Tools add-on: Export All Open Documents (#4920). Export All Open Documents as PDF Exporter tous les documents ouverts en PDF diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index de33cdbd92..094d49ce52 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -5527,6 +5527,11 @@ antiAlias Sharp शार्प Update Modified Links अद्यतन संशोधित लिंक Update Selection अद्यतन सिलेक्शन UPPERCASE अपरकैस + Sanskrit संस्कृत + Nepali नेपाली + Assamese असमिया + Konkani कोंकणी + Sindhi सिंधी Urdu उर्दू URL: यूआरएल: Use उपयोग diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f869e7d07b..d5f42ce788 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7499,6 +7499,11 @@ breakText Glyphs Glifák Malayalam Malajálam Odia Odia Urdu Urdu + Sanskrit Szanszkrit + Nepali Nepáli + Assamese Asszámi + Konkani Konkani + Sindhi Szindhi VectorCraft {release} and later (version {n}) VectorCraft {release} és újabb (verzió: {n}) # Document Tools add-on: Export All Open Documents (#4920). Export All Open Documents as PDF Az összes megnyitott dokumentum exportálása PDF-ként diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5f865e69b..b349f589a5 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6835,6 +6835,11 @@ breakText Glyphs Glif Malayalam Malayalam Odia Oriya Urdu Urdu + Sanskrit Sanskerta + Nepali Nepali + Assamese Assam + Konkani Konkani + Sindhi Sindhi VectorCraft {release} and later (version {n}) VectorCraft {release} dan yang lebih baru (versi {n}) # Document Tools add-on: Export All Open Documents (#4920). Export All Open Documents as PDF Ekspor Semua Dokumen Terbuka sebagai PDF diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 08cefdbed7..8bc9d44147 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -7141,6 +7141,11 @@ breakText Glyphs Glifi Malayalam Malayalam Odia Odia Urdu Urdu + Sanskrit Sanscrito + Nepali Nepalese + Assamese Assamese + Konkani Konkani + Sindhi Sindhi VectorCraft {release} and later (version {n}) VectorCraft {release} e successive (versione {n}) # Document Tools add-on: Export All Open Documents (#4920). Export All Open Documents as PDF Esporta tutti i documenti aperti come PDF diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 59c7628f40..57c9aee61e 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -9020,6 +9020,11 @@ breakText Glyphs 字形 Malayalam マラヤーラム語 Odia オディア語 Urdu ウルドゥー語 + Sanskrit サンスクリット語 + Nepali ネパール語 + Assamese アッサム語 + Konkani コンカニ語 + Sindhi シンド語 VectorCraft {release} and later (version {n}) VectorCraft {release} 以降 (バージョン {n}) # Document Tools add-on: Export All Open Documents (#4920). Export All Open Documents as PDF 開いているすべてのドキュメントを PDF として書き出し diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9393433cdb..a661bc0cbb 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9631,6 +9631,9 @@ breakText Glyphs გლიფები Urdu ურდუ Assamese ასამური Sanskrit სანსკრიტი + Nepali ნეპალური + Konkani კონკანი + Sindhi სინდჰური German: Swiss გერმანული: შვეიცარია Catalan კატალანური Danish დანიური diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 49d5e10dc1..632c2473f8 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -7105,6 +7105,11 @@ breakText Glyphs 글리프 Malayalam 말라얄람어 Odia 오리야어 Urdu 우르두어 + Sanskrit 산스크리트어 + Nepali 네팔어 + Assamese 아삼어 + Konkani 코카니어 + Sindhi 신디어 VectorCraft {release} and later (version {n}) VectorCraft {release} 이상 (버전 {n}) # Document Tools add-on: Export All Open Documents (#4920). Export All Open Documents as PDF 열린 모든 문서를 PDF로 내보내기 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f071ebd0e2..0137b7ac5b 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -9392,6 +9392,11 @@ breakText Glyphs Glyphs Malayalam Malayalam Odia Odia Urdu Urdu + Sanskrit Sanskriet + Nepali Nepalees + Assamese Assamees + Konkani Konkani + Sindhi Sindhi VectorCraft {release} and later (version {n}) VectorCraft {release} en nieuwer (versie {n}) # Document Tools add-on: Export All Open Documents (#4920). Export All Open Documents as PDF Alle geopende documenten exporteren als PDF diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2477c73abd..a2909473c2 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7370,6 +7370,11 @@ breakText Glyphs Glify Malayalam Malajalam Odia Orija Urdu Urdu + Sanskrit Sanskryt + Nepali Nepalski + Assamese Asamski + Konkani Konkani + Sindhi Sindhi VectorCraft {release} and later (version {n}) VectorCraft {release} i nowsze (wersja {n}) # Document Tools add-on: Export All Open Documents (#4920). Export All Open Documents as PDF Eksportuj wszystkie otwarte dokumenty jako PDF diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 333351b9af..9c7e0fddd5 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7545,6 +7545,11 @@ breakText Glyphs Glifos Malayalam Malaiala Odia Oriá Urdu Urdu + Sanskrit Sânscrito + Nepali Nepalês + Assamese Assamês + Konkani Concani + Sindhi Sindi VectorCraft {release} and later (version {n}) VectorCraft {release} e posteriores (versão {n}) # Document Tools add-on: Export All Open Documents (#4920). Export All Open Documents as PDF Exportar todos os documentos abertos como PDF diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ae33aa0d55..87424a1938 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -7504,6 +7504,11 @@ breakText Glyphs Глифы Malayalam Малаялам Odia Ория Urdu Урду + Sanskrit Санскрит + Nepali Непальский + Assamese Ассамский + Konkani Конкани + Sindhi Синдхи VectorCraft {release} and later (version {n}) VectorCraft {release} и новее (версия {n}) # Document Tools add-on: Export All Open Documents (#4920). Export All Open Documents as PDF Экспортировать все открытые документы в PDF diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1bd4fd0692..62ac5b67a8 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7542,6 +7542,9 @@ breakText Glyphs Glyfer Malayalam Malayalam Odia Oriya Urdu Urdu + Nepali Nepalesiska + Konkani Konkani + Sindhi Sindhi VectorCraft {release} and later (version {n}) VectorCraft {release} och senare (version {n}) # Document Tools add-on: Export All Open Documents (#4920). Export All Open Documents as PDF Exportera alla öppna dokument som PDF diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index d21a146585..0daefad24a 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -4147,7 +4147,41 @@ fn the_keep_colors_trace_warnings_are_translated() { image::Rgba(if (10..30).contains(&x) && (10..30).contains(&y) { [0, 0, 0, 255] } else { [255, 255, 255, 255] }) }); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 data = vectorcraft_format::base64_encode(&png); let mut warnings = vec![]; for (params, shown) in [ diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a2a38c679a..9076b8da7c 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -9394,6 +9394,11 @@ breakText Glyphs Glifler Malayalam Malayalam dili Odia Oriya dili Urdu Urduca + Sanskrit Sanskrit + Nepali Nepalce + Assamese Assamca + Konkani Konkani dili + Sindhi Sindhi dili VectorCraft {release} and later (version {n}) VectorCraft {release} ve sonrası (sürüm {n}) # Document Tools add-on: Export All Open Documents (#4920). Export All Open Documents as PDF Tüm Açık Belgeleri PDF Olarak Dışa Aktar diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 17c673885d..c701f1bd5d 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -7123,6 +7123,11 @@ breakText Glyphs Гліфи Malayalam Малаялам Odia Одія Urdu Урду + Sanskrit Санскрит + Nepali Непальська + Assamese Ассамська + Konkani Конкані + Sindhi Синдхі VectorCraft {release} and later (version {n}) VectorCraft {release} і новіші (версія {n}) # Document Tools add-on: Export All Open Documents (#4920). Export All Open Documents as PDF Експортувати всі відкриті документи як PDF diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index da89525314..7ce09032d1 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7153,6 +7153,11 @@ breakText Glyphs Glyph Malayalam Tiếng Malayalam Odia Tiếng Odia Urdu Tiếng Urdu + Sanskrit Tiếng Phạn + Nepali Tiếng Nepal + Assamese Tiếng Assam + Konkani Tiếng Konkani + Sindhi Tiếng Sindhi VectorCraft {release} and later (version {n}) VectorCraft {release} trở lên (phiên bản {n}) # Document Tools add-on: Export All Open Documents (#4920). Export All Open Documents as PDF Xuất tất cả tài liệu đang mở dưới dạng PDF diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f612cb0d4..86f04f416e 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7355,6 +7355,11 @@ breakText Glyphs 字形 Malayalam 马拉雅拉姆语 Odia 奥里亚语 Urdu 乌尔都语 + Sanskrit 梵语 + Nepali 尼泊尔语 + Assamese 阿萨姆语 + Konkani 孔卡尼语 + Sindhi 信德语 VectorCraft {release} and later (version {n}) VectorCraft {release} 及更高版本 (版本 {n}) # Document Tools add-on: Export All Open Documents (#4920). Export All Open Documents as PDF 将所有打开的文档导出为 PDF diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e0b5a13ee2..65e5274812 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7164,6 +7164,11 @@ breakText Glyphs 字符 Malayalam 馬來亞拉姆文 Odia 歐利亞文 Urdu 烏都文 + Sanskrit 梵文 + Nepali 尼泊爾文 + Assamese 阿薩姆文 + Konkani 貢根文 + Sindhi 信德文 VectorCraft {release} and later (version {n}) VectorCraft {release} 及更新版本 (版本 {n}) # Document Tools add-on: Export All Open Documents (#4920). Export All Open Documents as PDF 將所有開啟的文件匯出為 PDF diff --git a/crates/ui-egui/src/opening/tests.rs b/crates/ui-egui/src/opening/tests.rs index 5840df50cc..43fe46e217 100644 --- a/crates/ui-egui/src/opening/tests.rs +++ b/crates/ui-egui/src/opening/tests.rs @@ -162,7 +162,41 @@ fn a_file_ready_during_a_place_cursor_drag_waits_for_it_to_end() { let mut app = VectorcraftApp::new(Session::new(), Services::default()); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); let mut png = vec![]; - image::RgbImage::new(8, 8).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbImage::new(8, 8)).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(); app.run("file.place.queue", json!({"files": [{"name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png)}]})).unwrap(); let view = vectorcraft_engine::ViewInfo::default(); for (kind, x) in [(PointerKind::Down, 20.0), (PointerKind::Drag, 60.0)] { @@ -282,14 +316,47 @@ fn a_file_read_off_the_ui_thread_opens_as_one_read_at_once() { /// leaves a step to undo, and both ask the same question. #[test] fn a_file_read_off_the_ui_thread_has_its_links_and_type_as_one_read_at_once() { - use image::ImageFormat::{Bmp, Jpeg, Png, Tiff}; + use craft_image_codecs::Format::{Bmp, Jpeg, Png, Tiff}; let dir = crate::tests_folder::Folder::new("opening-links"); let (before, after) = (dir.join("before"), dir.join("after")); std::fs::create_dir_all(&before).unwrap(); let file = |folder: &std::path::Path, name: &str| folder.join(name).to_string_lossy().into_owned(); - let picture = |format: image::ImageFormat, rgb: [u8; 3]| { + let picture = |format: craft_image_codecs::Format, rgb: [u8; 3]| { let mut out = vec![]; - image::RgbImage::from_pixel(60, 40, image::Rgb(rgb)).write_to(&mut std::io::Cursor::new(&mut out), format).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbImage::from_pixel(60, 40, image::Rgb(rgb))).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, format, &craft_image_codecs::EncodeOptions::default()).map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out }; let mut app = VectorcraftApp::new(Session::new(), Services::default()); diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 1c5509e9ae..6605f94ddc 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -6486,8 +6486,10 @@ mod tests { #[test] fn place_cursor_exec_checks_recording_step_limit_on_completion() { let steps = "the action already has 10,000 steps"; - let mut png = vec![]; - image::RgbImage::new(8, 8).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let raw = + craft_image_codecs::Image::from_raw(8, 8, craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, vec![0; 8 * 8 * 3]) + .unwrap(); + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); let placed = |app: &VectorcraftApp| { let st = app.session.active().unwrap(); st.doc.layers.iter().flat_map(|l| l.children().into_iter().flatten()).filter(|n| n.name.as_deref() == Some("a.png")).count() diff --git a/crates/ui-egui/src/panels/appearance/tests.rs b/crates/ui-egui/src/panels/appearance/tests.rs index 27bae8fcf4..1b26bd3436 100644 --- a/crates/ui-egui/src/panels/appearance/tests.rs +++ b/crates/ui-egui/src/panels/appearance/tests.rs @@ -465,9 +465,41 @@ fn a_plug_in_effect_s_editor_follows_its_manifest() { #[test] fn the_effect_editor_lists_a_loaded_glass_texture() { let mut png = vec![]; - image::RgbaImage::from_pixel(4, 4, image::Rgba([90, 120, 150, 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([90, 120, 150, 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 stored = vectorcraft_engine::cmd::fileio::texture_image(&png).unwrap(); let (mut app, ctx, id) = editing("distort.glass"); app.run("effect.setParams", json!({"item": null, "index": 0, "params": {"texture": "loaded", "textureImage": stored}})).unwrap(); @@ -788,7 +820,41 @@ fn images_show_a_contents_row_with_new_fills_and_strokes_below_it() { run(&mut app, "file.new", json!({"width": 100, "height": 100})); let rows = |t: Vec| t.into_iter().filter(|t| ["Fill:", "Stroke:", "Contents"].contains(&t.as_str())).collect::>(); let mut png = vec![]; - image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 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([255, 0, 0, 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 app, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png)})); assert_eq!(rows(frame(&mut app)), ["Contents"]); run(&mut app, "appearance.addStroke", json!({})); diff --git a/crates/ui-egui/src/panels/brushes/tests.rs b/crates/ui-egui/src/panels/brushes/tests.rs index aeab927e23..a6dc1c304c 100644 --- a/crates/ui-egui/src/panels/brushes/tests.rs +++ b/crates/ui-egui/src/panels/brushes/tests.rs @@ -714,7 +714,41 @@ fn symbols_rendered(ctx: &egui::Context, app: &mut VectorcraftApp) -> usize { fn png(rgb: [u8; 3]) -> Vec { let img = image::RgbaImage::from_pixel(4, 4, image::Rgba([rgb[0], rgb[1], rgb[2], 255])); let mut out = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 } diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index 72e30921ac..7f686db45a 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -37,7 +37,41 @@ fn traced_app_with_ink(ink: u8) -> VectorcraftApp { app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); let img = image::RgbaImage::from_fn(20, 20, |x, _| image::Rgba(if x < 10 { [ink, ink, ink, 255] } else { [255, 255, 255, 255] })); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 data = vectorcraft_format::base64_encode(&png); app.run("file.place", json!({"name": "half.png", "dataBase64": data, "link": false})).unwrap(); app.run("imageTrace.make", json!({"preset": "Default"})).unwrap(); @@ -88,7 +122,41 @@ fn a_large_image_traces_and_the_status_bar_says_it_is_slower() { app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); let img = image::RgbaImage::from_fn(1601, 12, |x, _| image::Rgba(if x < 800 { [0, 0, 0, 255] } else { [255, 255, 255, 255] })); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 data = vectorcraft_format::base64_encode(&png); app.run("file.place", json!({"name": "wide.png", "dataBase64": data, "link": false})).unwrap(); trace_with(&mut app, "Default"); @@ -102,7 +170,41 @@ fn a_large_image_traced_as_a_flat_logo_shows_the_size_it_was_traced_at() { app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); let img = image::RgbaImage::from_fn(1602, 1602, |x, _| image::Rgba(if x < 800 { [0, 0, 0, 255] } else { [255, 255, 255, 255] })); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 data = vectorcraft_format::base64_encode(&png); app.run("file.place", json!({"name": "logo.png", "dataBase64": data, "link": false})).unwrap(); trace_with(&mut app, "Flat Logo"); @@ -360,7 +462,41 @@ fn settings_that_wait_are_kept_when_a_plain_image_is_traced_in_between() { click(&mut app, &ctx, "Strokes"); let img = image::RgbaImage::from_fn(20, 20, |_, y| image::Rgba(if y < 10 { [0, 0, 0, 255] } else { [255, 255, 255, 255] })); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 data = vectorcraft_format::base64_encode(&png); app.run("file.place", json!({"name": "plain.png", "dataBase64": data, "link": false})).unwrap(); assert!(target(&app).1, "a plain image is selected"); @@ -770,7 +906,41 @@ fn a_color_group_the_active_document_lacks_is_all() { app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); let img = image::RgbaImage::from_fn(20, 20, |x, _| image::Rgba(if x < 10 { [0, 0, 0, 255] } else { [255, 255, 255, 255] })); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 data = vectorcraft_format::base64_encode(&png); app.run("file.place", json!({"name": "half.png", "dataBase64": data, "link": false})).unwrap(); let texts = frame(&mut app, &ctx, vec![]); diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index ae058ff348..123a9aacd1 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -1201,9 +1201,41 @@ fn kinds() -> (VectorcraftApp, HashMap<&'static str, NodeId>) { ids.insert("guide", guide); run(&mut app, "guide.add", json!({"vertical": true, "pos": 50})); let mut png = vec![]; - image::RgbaImage::from_pixel(4, 4, image::Rgba([200, 40, 40, 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([200, 40, 40, 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 = |app: &mut VectorcraftApp, p: serde_json::Value| NodeId(run(app, "file.place", p)["ids"][0].as_u64().unwrap()); ids.insert("embedded", placed(&mut app, json!({"name": "pic.png", "dataBase64": vectorcraft_format::base64_encode(&png)}))); // One file for every test that calls this, written by the first. diff --git a/crates/ui-egui/src/panels/libraries.rs b/crates/ui-egui/src/panels/libraries.rs index 9c10281783..44f4b30ed5 100644 --- a/crates/ui-egui/src/panels/libraries.rs +++ b/crates/ui-egui/src/panels/libraries.rs @@ -830,8 +830,10 @@ fn thumbnail(ctx: &egui::Context, library: &str, item: &str, png: &str, px: u32) if let Some(t) = CACHE.with(|c| c.borrow().get(&key).cloned()) { return t; } - let tex = - vectorcraft_format::base64_decode(png).and_then(|png| image::load_from_memory_with_format(&png, image::ImageFormat::Png).ok()).map(|img| { + let tex = vectorcraft_format::base64_decode(png) + .and_then(|png| craft_image_codecs::decode_as(craft_image_codecs::Format::Png, &png).ok()) + .and_then(|img| image::RgbaImage::from_raw(img.width(), img.height(), img.to_rgba8()).map(image::DynamicImage::ImageRgba8)) + .map(|img| { let rgba = shrunk_thumbnail(img, px); let image = egui::ColorImage::from_rgba_unmultiplied([rgba.width() as usize, rgba.height() as usize], rgba.as_raw()); ctx.load_texture(format!("library-{library}-{item}-{px}"), image, egui::TextureOptions::LINEAR) diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index 6c3872e97f..a847fd44cf 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -914,7 +914,41 @@ fn deselecting_keeps_the_arts_swatch_highlighted() { fn images_and_unswatched_text_highlight_no_swatch() { let mut app = app(); let mut png = vec![]; - image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 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([255, 0, 0, 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 data = vectorcraft_format::base64_encode(&png); app.run("file.place", json!({"name": "a.png", "dataBase64": data, "link": false})).unwrap(); assert_eq!(active_swatch(&app), None, "an image: no swatch"); diff --git a/crates/ui-egui/src/panels/tests_appearance.rs b/crates/ui-egui/src/panels/tests_appearance.rs index 3d486dfe23..1db803b636 100644 --- a/crates/ui-egui/src/panels/tests_appearance.rs +++ b/crates/ui-egui/src/panels/tests_appearance.rs @@ -1074,9 +1074,49 @@ fn transform_effect_preview_commit_cancel_and_undo_cover_artwork_targets() { } "image" => { let mut png = Vec::new(); - image::RgbaImage::from_pixel(20, 20, image::Rgba([255, 0, 0, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(20, 20, image::Rgba([255, 0, 0, 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(); app.run( "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "link": false, "at": [30, 70]}), diff --git a/crates/ui-egui/src/panels/tests_asset_export.rs b/crates/ui-egui/src/panels/tests_asset_export.rs index 8b9a9ed884..e621785cc9 100644 --- a/crates/ui-egui/src/panels/tests_asset_export.rs +++ b/crates/ui-egui/src/panels/tests_asset_export.rs @@ -734,7 +734,24 @@ fn tiff_dropdown_exports_only_the_selected_asset_and_shares_settings() { let [(name, bytes)] = log.as_slice() else { panic!("expected only the selected asset") }; assert_eq!(name, "Badge@2x.tif"); assert_eq!(&bytes[..4], b"MM\0*", "the saved TIFF byte order reaches asset export"); - let img = image::load_from_memory_with_format(bytes, image::ImageFormat::Tiff).unwrap().to_rgba8(); + let img = craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, 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!(img.dimensions(), (60, 40), "the selected 30x20 asset at 2x"); let pixel = img.get_pixel(30, 20).0; assert!(pixel[0] > pixel[1] && pixel[0] > pixel[2] && pixel[3] == 255, "the red Badge, not the blue Other asset: {pixel:?}"); @@ -866,7 +883,24 @@ fn tiff_panel_preserves_shared_antialias_and_explicit_overrides() { let log = log.borrow(); let [(name, bytes)] = log.as_slice() else { panic!("expected one TIFF: format={format_aa:?}, row={row_aa:?}") }; assert_eq!(name, "Edge.tif"); - let img = image::load_from_memory_with_format(bytes, image::ImageFormat::Tiff).unwrap().to_rgba8(); + let img = craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, 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!(img.pixels().any(|p| p[3] == 255), "the ellipse is present"); assert!(img.pixels().any(|p| p[3] == 0), "transparent outside the ellipse"); let hard = img.pixels().all(|p| p[3] == 0 || p[3] == 255); @@ -917,12 +951,44 @@ fn tiff_saved_aliases_use_document_defaults_and_explicit_rgb() { let bytes = std::fs::read(folder.join("Badge@2x.tif")).unwrap(); assert_eq!(tiff_photometric(&bytes), if rgb_override { 2 } else { 5 }, "saved alias {alias}, explicit RGB={rgb_override}"); if rgb_override { - let img = image::load_from_memory_with_format(&bytes, image::ImageFormat::Tiff).unwrap(); + let img = craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, &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(); assert_eq!((img.width(), img.height()), (60, 40), "the saved TIFF row is still 2x"); } if mixed { let png = std::fs::read(folder.join("Badge.png")).unwrap(); - let img = image::load_from_memory_with_format(&png, image::ImageFormat::Png).unwrap(); + let img = 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(); assert_eq!((img.width(), img.height()), (30, 20), "the PNG row keeps its own 1x scale"); assert_eq!(png.get(28), Some(&1), "the saved PNG interlace option survives the TIFF defaults"); } diff --git a/crates/ui-egui/src/panels/tests_css_properties.rs b/crates/ui-egui/src/panels/tests_css_properties.rs index e03fc9a59c..a618293b75 100644 --- a/crates/ui-egui/src/panels/tests_css_properties.rs +++ b/crates/ui-egui/src/panels/tests_css_properties.rs @@ -137,9 +137,41 @@ fn export_says_in_the_status_bar_when_an_image_could_not_be_decoded() { assert_eq!(app.ui.status, "Exported /tmp/site/site.css"); // A PNG whose header reads but whose pixel data is cut short. let mut png = Vec::new(); - image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 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(); vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &png, json!({})); let r = app.run("css.exportFile", json!({"path": "/tmp/site/site.css", "scope": "all", "rasterize": true})).unwrap(); assert_eq!(r["warnings"], json!([WARNING])); @@ -153,9 +185,41 @@ fn export_says_in_the_status_bar_when_an_image_could_not_be_decoded() { fn export_keeps_every_note_for_the_hover() { let (mut app, _) = app(); let mut png = Vec::new(); - image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 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(); vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &png, json!({})); // Type painted with a gradient is rasterized, and its picture is drawn in the fallback font. app.run("text.create", json!({"x": 5, "y": 20, "text": "Ab", "font": "Nonexistent Sans Probe"})).unwrap(); diff --git a/crates/ui-egui/src/panels/tests_effectedit.rs b/crates/ui-egui/src/panels/tests_effectedit.rs index dc8f6a51ce..1fdbc52fa0 100644 --- a/crates/ui-egui/src/panels/tests_effectedit.rs +++ b/crates/ui-egui/src/panels/tests_effectedit.rs @@ -90,9 +90,41 @@ fn an_effect_name_opens_its_dialog_prefilled_and_ok_edits_it_in_place() { fn the_inline_editor_shows_a_loaded_texture_by_its_size() { let mut app = app_with_rect(); let mut png = Vec::new(); - image::GrayImage::from_fn(5, 3, |x, _| image::Luma([(x * 60) as u8])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::GrayImage::from_fn(5, 3, |x, _| image::Luma([(x * 60) as u8]))).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 file = json!({"name": "t.png", "dataBase64": vectorcraft_format::base64_encode(&png)}); run(&mut app, "effect.apply", json!({"effect": "distort.glass", "params": {"textureImage": file}})); let ctx = egui::Context::default(); diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 2771fe568e..781c4f5840 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -35,9 +35,41 @@ impl Drop for Folder { fn png(w: u32, h: u32) -> Vec { let mut out = vec![]; - image::RgbaImage::from_pixel(w, h, image::Rgba([200, 40, 40, 255])) - .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(w, h, image::Rgba([200, 40, 40, 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| out.extend_from_slice(&__b)) + } + .unwrap(); out } diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index 08aa580d56..6485cafd8c 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -589,8 +589,8 @@ pub(crate) fn show_thumbnails(app: &mut VectorcraftApp, r: &Value, asks: bool) { .flatten() .filter_map(|f| { let png = vectorcraft_format::base64_decode(f["thumbnailBase64"].as_str()?)?; - let img = image::load_from_memory_with_format(&png, image::ImageFormat::Png).ok()?.to_rgba8(); - let color = egui::ColorImage::from_rgba_unmultiplied([img.width() as usize, img.height() as usize], img.as_raw()); + let img = craft_image_codecs::decode_as(craft_image_codecs::Format::Png, &png).ok()?; + let color = egui::ColorImage::from_rgba_unmultiplied([img.width() as usize, img.height() as usize], &img.to_rgba8()); Some((f["name"].as_str()?.to_string(), Thumb { image: std::sync::Arc::new(color), tex: None })) }) .collect(); diff --git a/crates/ui-egui/src/placing/tests.rs b/crates/ui-egui/src/placing/tests.rs index f9211a61bb..9043bac0ea 100644 --- a/crates/ui-egui/src/placing/tests.rs +++ b/crates/ui-egui/src/placing/tests.rs @@ -1,4 +1,4 @@ -use image::ImageFormat::{Bmp, Png, Tiff}; +use craft_image_codecs::Format::{Bmp, Png, Tiff}; use vectorcraft_doc::{Document, NodeId}; use vectorcraft_engine::Session; use vectorcraft_engine::cmd::clipboard::{BITMAP, Flavour, PNG, TEXT}; @@ -27,9 +27,42 @@ fn saved(test: &str, name: &str, bytes: &[u8]) -> String { } /// A `w` × `h` picture of one color in `format`. -fn picture(format: image::ImageFormat, w: u32, h: u32) -> Vec { +fn picture(format: craft_image_codecs::Format, w: u32, h: u32) -> Vec { let mut out = vec![]; - image::RgbImage::from_pixel(w, h, image::Rgb([200, 40, 40])).write_to(&mut std::io::Cursor::new(&mut out), format).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbImage::from_pixel(w, h, image::Rgb([200, 40, 40]))).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, format, &craft_image_codecs::EncodeOptions::default()).map(|__b| out.extend_from_slice(&__b)) + } + .unwrap(); out } @@ -1075,7 +1108,41 @@ fn a_placed_image_is_drawn_without_decoding_it_on_the_ui_thread() { // The image has pixels no other test uses, since every test shares the image store. let noise = image::RgbImage::from_fn(2000, 2000, |x, y| image::Rgb([(x % 251) as u8, (y % 241) as u8, ((x + y) % 239) as u8])); let mut png = vec![]; - noise.write_to(&mut std::io::Cursor::new(&mut png), Png).unwrap(); + { + let __dyn: image::DynamicImage = noise.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 path = saved("seeded", "photo.png", &png); let mut app = app(true); start(&mut app, &json!({"path": path}), false).unwrap(); @@ -1106,7 +1173,41 @@ fn a_file_that_cant_be_read_off_the_ui_thread_reports_as_at_once() { image::Rgb([v as u8, (v >> 8) as u8, (v >> 16) as u8]) }); let mut png = vec![]; - noise.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = noise.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(); png.truncate(png.len() / 2); let cut = saved("unread", "cut.png", &png); for path in [gone, unknown, cut] { diff --git a/crates/ui-egui/src/tests/automation.rs b/crates/ui-egui/src/tests/automation.rs index 0d73d42d21..541e78ff39 100644 --- a/crates/ui-egui/src/tests/automation.rs +++ b/crates/ui-egui/src/tests/automation.rs @@ -456,7 +456,26 @@ fn control_render_matches_a_png_export_on_white() { std::fs::write(base.join("in/edges.svg"), svg).unwrap(); let r = request(&mut app, &tx, "app.open", json!({"path": s(base.join("in/edges.svg"))})); assert_eq!(r["ok"], true, "{r}"); - let pixels = |v: &Value| image::load_from_memory(&vectorcraft_format::base64_decode(v.as_str().unwrap()).unwrap()).unwrap().to_rgba8(); + let pixels = |v: &Value| { + craft_image_codecs::decode(&vectorcraft_format::base64_decode(v.as_str().unwrap()).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() + .to_rgba8() + }; let r = request(&mut app, &tx, "app.export", json!({"format": "png", "background": "white"})); let export = pixels(&r["result"]["dataBase64"]); let r = request(&mut app, &tx, "ui.render", json!({})); @@ -485,7 +504,26 @@ fn control_render_draws_the_trace_view_with_trace_views() { app.run("select.all", json!({})).unwrap(); app.run("imageTrace.make", json!({"params": {"ignoreWhite": true}})).unwrap(); app.run("imageTrace.setView", json!({"view": "sourceImage"})).unwrap(); - let pixels = |v: &Value| image::load_from_memory(&vectorcraft_format::base64_decode(v.as_str().unwrap()).unwrap()).unwrap().to_rgba8(); + let pixels = |v: &Value| { + craft_image_codecs::decode(&vectorcraft_format::base64_decode(v.as_str().unwrap()).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() + .to_rgba8() + }; let view = pixels(&request(&mut app, &tx, "ui.render", json!({"traceViews": true}))["result"]["pngBase64"]); let result = pixels(&request(&mut app, &tx, "ui.render", json!({}))["result"]["pngBase64"]); let (beside, middle) = (view.get_pixel(10, 10).0, view.get_pixel(50, 50).0); diff --git a/crates/ui-egui/src/tests/place.rs b/crates/ui-egui/src/tests/place.rs index 0141f69403..58af75a1d2 100644 --- a/crates/ui-egui/src/tests/place.rs +++ b/crates/ui-egui/src/tests/place.rs @@ -17,7 +17,41 @@ use crate::tests_folder::Folder; /// A `w`×`h` red PNG declaring `ppi`. fn png(w: u32, h: u32, ppi: f64) -> Vec { let mut out = vec![]; - image::RgbaImage::from_pixel(w, h, image::Rgba([255, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(w, h, image::Rgba([255, 0, 0, 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| out.extend_from_slice(&__b)) + } + .unwrap(); vectorcraft_engine::cmd::fileio::ppi::with_png_resolution(&out, (ppi, ppi)) } diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index ec6921500b..e6b2aa44b6 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -231,7 +231,9 @@ fn assign_harness(mut app: VectorcraftApp, open: Value) -> egui_kittest::Harness app.run("ui.recolorDialog", open).unwrap(); set(&mut app, "method", json!("exact")); let mut fonts = false; - let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 800.0)).build_ui_state( + let builder = egui_kittest::Harness::builder().with_size(vec2(900.0, 800.0)); + let builder = if std::env::var_os("VECTORCRAFT_RECOLOR_CAPTURE_DIR").is_some() { builder.wgpu() } else { builder }; + let mut h = builder.build_ui_state( move |ui, app: &mut VectorcraftApp| { if !std::mem::replace(&mut fonts, true) { crate::theme::install_fonts(ui.ctx()); @@ -1339,3 +1341,93 @@ fn a_color_bars_menu_removes_its_color() { assert!(h.query_by_role_and_label(egui::accesskit::Role::Button, "Color 2").is_none(), "its bar goes"); assert_eq!(field(h.state(), "__sel"), json!([0])); } + +// Optional local visual QA; these captures are not committed assets. +fn capture_recolor(h: &mut egui_kittest::Harness<'_, VectorcraftApp>, name: &str) { + if let Some(dir) = std::env::var_os("VECTORCRAFT_RECOLOR_CAPTURE_DIR") { + let dir = std::path::PathBuf::from(dir); + std::fs::create_dir_all(&dir).unwrap(); + h.render().unwrap().save(dir.join(format!("{name}.png"))).unwrap(); + } +} + +/// Secondary-click the actual New chip; the menu must dispatch through its UI callbacks. +fn row_context_menu(h: &mut egui_kittest::Harness<'_, VectorcraftApp>, row: usize) { + let pos = h.ctx.read_response(egui::Id::unique(("recolor-new", row))).expect("New chip").rect.center(); + h.event(Event::PointerMoved(pos)); + h.run_steps(1); + for pressed in [true, false] { + h.event(Event::PointerButton { pos, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(1); + } + h.run_steps(2); +} + +#[test] +fn row_context_menu_pick_from_swatches_and_limit_to_library() { + use egui::accesskit::Role; + + for empty_new in [false, true] { + let mut app = app(); + art(&mut app, &["#ff0000", "#0000ff"]); + // A known, single-color palette makes it impossible to pass without snapping the rows. + let doc = &app.session.doc().unwrap().doc; + let names: Vec<_> = doc + .swatches + .iter() + .filter(|s| !s.is_reserved()) + .map(|s| s.name.clone()) + .chain(doc.swatch_groups.iter().map(|g| g.name.clone())) + .collect(); + app.run("swatch.delete", json!({"names": names})).unwrap(); + app.run("swatch.new", json!({"name": "Only Yellow", "color": "#ffff00"})).unwrap(); + let undo = app.session.doc().unwrap().history.undo.len(); + let mut h = assign_harness(app, json!({})); + let row = 1; + if empty_new { + let mut rows = field(h.state(), "rows"); + rows[row]["to"] = Value::Null; + set(h.state_mut(), "rows", rows); + h.run_steps(2); + } + let before = field(h.state(), "rows"); + let expected = if empty_new { before[row]["from"][0].clone() } else { before[row]["to"].clone() }; + row_context_menu(&mut h, row); + assert_eq!(field(h.state(), "__sel"), json!([row]), "right-click selects the targeted row"); + capture_recolor(&mut h, "assign-row-menu"); + h.get_by_label(" Pick from Swatches").click(); + h.run_steps(3); + let picker = h.state().ui.dialog.as_ref().expect("picker opened by menu"); + assert_eq!(picker.kind, "colorPicker"); + assert!(picker.bool("swatches")); + assert_eq!(picker.fields["__recolorRow"], json!(row)); + assert_eq!(picker.fields.get("color").and_then(vectorcraft_engine::cmd::color_value), vectorcraft_engine::cmd::color_value(&expected)); + capture_recolor(&mut h, "picker-swatches"); + h.get_by_role_and_label(Role::Button, "Cancel").click(); + h.run_steps(3); + assert_eq!(field(h.state(), "rows"), before, "picker Cancel preserves all rows"); + + row_context_menu(&mut h, row); + h.get_by_label("Limit to Library").click(); + h.run_steps(3); + capture_recolor(&mut h, "assign-library-menu"); + h.get_by_label(" Document Swatches").click(); + h.run_steps(3); + assert_eq!(field(h.state(), "limitTo"), json!("document")); + let snapped = field(h.state(), "rows"); + for (i, r) in snapped.as_array().unwrap().iter().enumerate() { + assert_eq!(r["to"], "rgb 255 255 0", "row {i} snaps to the palette"); + } + assert_ne!(snapped, before, "the menu changes row colors"); + row_context_menu(&mut h, row); + h.get_by_label("Limit to Library").click(); + h.run_steps(3); + h.get_by_label(" None").click(); + h.run_steps(3); + assert_eq!(field(h.state(), "limitTo"), json!("")); + assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo, "menu actions remain previews"); + h.get_by_role_and_label(Role::Button, "Cancel").click(); + h.run_steps(2); + assert_eq!(colors(h.state_mut()), 2, "Recolor Cancel restores the original artwork"); + } +} diff --git a/crates/ui-egui/src/tests/recovery.rs b/crates/ui-egui/src/tests/recovery.rs index 946c535fd4..3e22b9b6e7 100644 --- a/crates/ui-egui/src/tests/recovery.rs +++ b/crates/ui-egui/src/tests/recovery.rs @@ -119,7 +119,41 @@ fn launching_after_a_crash_offers_the_copies() { fn png(rgb: [u8; 3]) -> Vec { let mut out = vec![]; let [r, g, b] = rgb; - image::RgbaImage::from_pixel(40, 30, image::Rgba([r, g, b, 255])).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(40, 30, image::Rgba([r, g, b, 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| out.extend_from_slice(&__b)) + } + .unwrap(); out } diff --git a/crates/ui-egui/src/tests/sysclip.rs b/crates/ui-egui/src/tests/sysclip.rs index 1da5b93322..089fcdafaa 100644 --- a/crates/ui-egui/src/tests/sysclip.rs +++ b/crates/ui-egui/src/tests/sysclip.rs @@ -231,7 +231,41 @@ fn text_and_image_paste_events_paste_once_as_text() { pub(crate) fn blue_png() -> Vec { let img = image::RgbaImage::from_pixel(4, 2, image::Rgba([0, 0, 255, 255])); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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(); png } @@ -385,9 +419,41 @@ fn copy_says_in_the_status_bar_when_an_image_could_not_be_decoded() { const WARNING: &str = "an image couldn't be decoded and is missing from the picture"; // A PNG whose header reads but whose pixel data is cut short. let mut png = Vec::new(); - image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 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(); for worker in [false, true] { let (mut app, board) = if worker { app_with_worker() } else { app() }; app.status("Ready"); diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index b6d04ff12b..8230969c97 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -157,9 +157,41 @@ fn a_clipping_mask_offers_edit_clipping_path_and_release() { fn an_image_with_vector_art_offers_make_clipping_mask() { let mut app = app(); let mut png = vec![]; - image::RgbaImage::from_pixel(20, 20, image::Rgba([0, 128, 255, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); + { + let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(20, 20, image::Rgba([0, 128, 255, 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 dir = crate::tests_folder::Folder::new("ui-taskbar"); let path = dir.file("blue.png", &png); app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); diff --git a/crates/ui-egui/src/tests/trace_runs.rs b/crates/ui-egui/src/tests/trace_runs.rs index 8dd72efe91..478631ad18 100644 --- a/crates/ui-egui/src/tests/trace_runs.rs +++ b/crates/ui-egui/src/tests/trace_runs.rs @@ -16,7 +16,41 @@ fn app() -> VectorcraftApp { app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); let img = image::RgbaImage::from_fn(40, 40, |x, y| image::Rgba(if x < 20 && y < 30 { [0, 0, 0, 255] } else { [255, 255, 255, 255] })); let mut png = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + { + let __dyn: image::DynamicImage = img.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 data = vectorcraft_format::base64_encode(&png); app.run("file.place", json!({"name": "half.png", "dataBase64": data, "link": false})).unwrap(); app.trace_runs.off_the_ui_thread = true; diff --git a/docs/gaps.md b/docs/gaps.md index c09d0e1281..eff4de81a0 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -124,7 +124,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Done:** Distance Guides ([public page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-distance-guides-for-accurate-placement.html)): with Smart Guides on and something selected, the Selection tool with Alt/Option held over another object shows the horizontal and vertical distances between them, and over an empty part of an artboard the selection's distances from its four edges, labelled in the General unit; Preferences › Smart Guides › Invoke Distance Guides turns them off. Hover only, as documented: not while moving or nudging. No entry closed; estimates unchanged. -- **Done (#4028):** Recolor Artwork › Assign: double-clicking a row's new color opens the Color Picker, as the [public page](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html) describes. OK sets the row's new color in the model it was picked in, so a CMYK mix is no longer a hex value converted back; Cancel leaves the row. Lab color values can be typed directly in the Color Picker's Lab fields without converting to RGB. Swatch libraries are accessible in the picker via a library dropdown. Rows in the Recolor Artwork Assign tab feature a right-click context menu with "Pick from Swatches" (opening Color Picker in swatches view) and "Limit to Library" (with library submenu). +- **Done (#4028):** Recolor Artwork › Assign: double-clicking a row's new color opens the Color Picker, as the [public page](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html) describes. OK sets the row's new color in the model it was picked in, so a CMYK mix is no longer a hex value converted back; Cancel leaves the row. Lab color values can be typed directly in the Color Picker's Lab fields without converting to RGB. Swatch libraries are accessible in the picker via a library dropdown. Rows in the Recolor Artwork Assign tab feature a right-click context menu with "Pick from Swatches" (opening Color Picker in swatches view) and "Limit to Library" (with library submenu). #4090 supplied the double-click picker and #5113 supplied the Assign sliders; #8031 completes these deferred picker/menu paths. Regression evidence: `native_lab_entry_in_color_picker` types into all three Lab fields and confirms; `row_context_menu_pick_from_swatches_and_limit_to_library` secondary-clicks populated and empty New chips, opens the picker for the targeted row, and snaps row colors through the library submenu. - **Done (#3416):** Recolor Artwork Edit chips scroll to the last color while the heading, color wheel and actions stay visible. Screen resize and UI scaling, Preview, Confirm, Cancel, Undo and #1733 wheel drags are covered in `tests/recolor.rs`. No gap entry closed; estimates unchanged. @@ -896,6 +896,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged. | | 2026-11-14 | minor | Type: Middle Eastern & South Asian and Standard composers per paragraph (#4935): Paragraph panel menu, paragraph styles, `text.setFormat {composer}` and the native file; the Standard composers set Indic, Arabic and Hebrew type glyph by glyph. `.ai`, EPS and PDF files carry no composer. Scores and estimates unchanged. | | 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. | | 2026-11-12 | minor | 3D: The seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins (the seams of Revolve and of colored lights, and 3D (Classic) Wireframe edges, were already round): no thorns on edge-on facets, and facets with no neighbour now have rounded convex corners ([three-d.md](three-d.md#seams)). Scores and estimates unchanged. | diff --git a/docs/roadmap.md b/docs/roadmap.md index fae091f647..a5525a41ae 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (#8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -159,7 +159,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M0 | Skeleton + vertical slice | ✅ done | — | | M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 | | M2 | Drawing tools + smart guides | ✅ mostly done (#3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123) | 12–18 | -| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); | 4–8 | +| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416; native Lab entry and swatch libraries in the picker, Assign-row menus, #8031/#4028); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); | 4–8 | | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | | M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | @@ -208,6 +208,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged. | | 2026-11-16 | minor | Color panel: the spectrum fills the vertical space of a resized panel, with options shown or hidden (#8005). Compact auto-fit flyouts and embedded mixers keep their existing size. Evidence: panels::color::tests::the_spectrum_grows_with_the_color_panel. Scores and estimates unchanged. | | 2026-11-15 | minor | PDF import: stroked type (text rendering modes 1, 2, 5 and 6, and glyphs under `ActualText`) keeps the line cap, line join and miter limit of the graphics state it is stroked with, as paths do, instead of butt caps, miter joins and a miter limit of 10; a glyph filled and then stroked otherwise than the run its fill joined comes in as a run of its own, so the glyphs before it keep their stroke (#7741; `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`). Scores and estimates unchanged. | | 2026-11-15 | minor | M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimates unchanged | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a3af153277..89742beda2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (#8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -61,6 +61,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | Recolor Artwork › Assign: native Lab entry in the Color Picker, swatch libraries access in the picker, and row context menu options (Pick from Swatches, Limit to Library) (#4028); scores and estimates unchanged. | | 2026-11-15 | minor | PDF import: stroked type (text rendering modes 1, 2, 5 and 6, and glyphs under `ActualText`) keeps the line cap, line join and miter limit of the graphics state it is stroked with, as paths do, instead of butt caps, miter joins and a miter limit of 10; a glyph filled and then stroked otherwise than the run its fill joined comes in as a run of its own, so the glyphs before it keep their stroke (#7741; `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`). Scores and estimates unchanged. | | 2026-11-15 | minor | G5: Neon & Glow joins Shadows and Glows, Outlines and Rules, Hand-Drawn, Textures, Painted and Sketched, Gradient Finishes, Shape Effects, Blends and Transparency, Game HUD and Status Effects as an eleventh built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor; original procedural styles generated in code); area score and estimate unchanged. | | 2026-11-14 | minor | G5: Weather Icons joins Basic Shapes, UI Frames, Map Markers, Inventory Icons and Skill Icons as a sixth built-in symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow; original procedural vector symbols generated in code, no default 9-slice); area score and estimate unchanged. | @@ -249,7 +250,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | -| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005) | +| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005) | | Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (ten generated libraries including Tech Circuit, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, the rest of 3D Classic (Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | @@ -518,7 +519,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of similar groups, transform nuances (the rotated persistent bounding box is done) | 4–6 | | Drawing tools | 7 | 86% | rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; Pencil: Alt key toggles to Smooth Tool (#2001); remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, Blob Brush Merge Only with Selection, Touch Type, Live Corners' Relative rounding | 7–12 | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder gap detection, options (Tool Options dialog, clicking a stroke in merge mode) and Shift-drag marquee | 3–6 | -| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); freeform gradients in SVG/PDF and mixed spot/process gradients in SVG (exported as stops; PDF export keeps the spot inks in a DeviceN shading, except next to RGB or Lab stops; dithered fills and Perceptual gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve are written as images in process colors), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) | +| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); freeform gradients in SVG/PDF and mixed spot/process gradients in SVG (exported as stops; PDF export keeps the spot inks in a DeviceN shading, except next to RGB or Lab stops; dithered fills and Perceptual gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve are written as images in process colors), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) | | Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (ten generated in code including Tech Circuit, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | | Appearance, transparency, graphic styles, masks | 5 | 98% | Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 | | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap (since done: #3061, #3063, #3785), SVG Filters, Transform Patterns and Scale Strokes & Effects on a fill's or stroke's own Transform effect | 6–10 | @@ -583,6 +584,8 @@ since 2026-10-01. ## Evidence: what ships today, by area +- **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged. + - **Save refusal (#6146):** ordinary File > Save to its own location offers Save As after a terminal permission/read-only refusal, suggesting the original name and format, preserving options for the unchanged format and opening the chosen format’s Save options on a change. Cancel keeps the failed-save state. Busy pickers, recovery-copy errors, other failures, explicit destinations and Close/Quit keep the existing dialog. Engine, UI and MCP regression cases are in `cmd/fileio/tests_readonly.rs`, `io/tests_read_only_save.rs` and MCP `tests/fileio.rs`; focused UI regressions passed; engine regression execution and native panel acceptance pending. Scores and hours unchanged. - **PDF authored replacement text (#6165):** `crates/pdf/src/tests/actual_text.rs` covers replacement once with suffix placement, PDF text-string decoding, empty and nested owners, sibling spans, page reset, multiple text-show operations, style/line changes, fill-and-stroke, reader windows and bounded input. Authored logical-order stretches are protected while adjacent ordinary text still undergoes reconstruction. The replacement takes its first placed glyph's style and line; its characters are not redistributed over later lines/styles. Exact mixed-direction paragraph layout is not claimed. No export changes; scores and hours stay at 75% / 10–20 h. @@ -2652,6 +2655,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged. | | 2026-11-16 | minor | Color panel: the spectrum fills the vertical space of a resized panel, with options shown or hidden (#8005). Compact auto-fit flyouts and embedded mixers keep their existing size. Evidence: panels::color::tests::the_spectrum_grows_with_the_color_panel. Scores and estimates unchanged. | | 2026-11-14 | minor | Paragraph composers (#4935): `text.setFormat {composer}` and paragraph styles take `singleLine` and `everyLine` (the Middle Eastern & South Asian composers, what all type used and the default) and `standardSingleLine` and `standardEveryLine`, which break lines the same way and set a complex script (Indic, Arabic, Hebrew) glyph by glyph as the font maps its characters, with no conjuncts, reordering, marks placed or joining forms. The choice is per paragraph, saved in the native file only when it is not Every-line, and not written to `.ai`, EPS or PDF files, whose composer setting this app has no recorded format for. Scores and estimates unchanged. Tests `tests::composers`. | | 2026-11-14 | minor | G5: Weather Icons joins Basic Shapes, UI Frames, Map Markers, Inventory Icons and Skill Icons as a sixth built-in symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow; original procedural vector symbols generated in code, no default 9-slice); area score and estimate unchanged. | diff --git a/docs/type-parity.md b/docs/type-parity.md index 70e82e7020..d92142dd88 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -77,8 +77,7 @@ against Illustrator's public documentation; **estimated** unless noted. | CJK: warichu | done | Character panel menu › Warichu and Warichu Settings… (`text.setFormat` / `text.setRangeStyle {warichu, warichuLines, warichuGap, warichuScale, warichuAlign}`, `ui.warichuSettings`), with Show East Asian Options ([Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)): marked characters set at a percentage of their size and stacked on 1 to 6 lines inside their line, one above the other in horizontal type and side by side in vertical type, with a line gap and eight alignments; a block stays whole on one line. Saved natively, carried by character styles, drawn on the canvas and in every export (SVG, PDF and `.ai` write such type as outlines). Type on a path sets the characters at their own size. Evidence: `tests::warichu`, `dialogs::warichu::tests`, `typecmd::area_tests::warichu_is_a_character_attribute_set_saved_and_exported` | | CJK: composite fonts | partial | Type › Composite Fonts… (`type.compositeFonts.set`), with Show East Asian Options: a font made of a font per class of character (Kanji, Kana, Punctuation, Symbols, Roman, Numerals), each with its own style, size and baseline in percent of the type's size, Kana, Roman and Numerals with horizontal and vertical scale, and Kana with Scale at Center; New, Delete Font, Import… and Export… (`.vccomposite`, `type.compositeFonts.import` and `.export`) ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347)); custom character sets (Custom: New, Delete Set, characters added by Direct Entry or Unicode code and deleted), each with its own font, style, size, baseline and scales, ahead of the classes, the later set winning a character two list (`custom` in `type.compositeFonts.set`) ([Customize characters in a composite font](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348)). Composite fonts are listed first in the font menus, saved with the document, and their type is laid out per set and class; SVG and legacy `.ai` write it as outlines. Show Sample draws the font picked with lines for its ICF box, em box, baseline, cap height, highest ascent and lowest descent, highest ascender and x-height, each shown or hidden by its button, at the Zoom picked ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=352)). Not yet: the Units menu. Evidence: `text::composite::tests::characters_fall_in_their_classes`, `text::composite::tests::custom_sets_take_their_characters_before_the_classes`, `tests::composite::composite_type_draws_each_class_in_its_font`, `tests::composite::custom_character_sets_take_their_characters_first`, `compositefonts::tests`, `dialogs::composite_fonts::tests` | | CJK: ruby | partial | ruby (ふりがな) for live text (`type.ruby`): a reading over a byte range, above (right of the column in vertical type) or below, start/centre/end alignment, size, overhang or squeeze; saved natively, laid out with its line growing, drawn on the canvas, in SVG and PDF (as outlines where ruby is present), in EPS, EMF/WMF and legacy `.ai` (legacy `.ai` writes type with ruby as outlines), and kept by Create Outlines, Expand Appearance and flattening, each glyph where the layout puts it (`typecmd::ruby_tests::create_outlines_keeps_the_ruby_where_it_is_laid_out`) | #633 | -| Language per character (Character panel › Language, character styles), text shaped in it | done | `text.setFormat` / `text.setRangeStyle {language}` by name or BCP 47 tag, one of Document Setup's languages (Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu added, #4943; Assamese and Sanskrit added, #4947; Serbian: Cyrillic, Serbian: Latin and Croatian); the shaper gets the tag, so the font's language forms apply (OpenType `locl`: Turkish keeps `fi` apart and the dot on its i, #4940); new type takes the document's language; saved as the tag only when set, carried by character styles (#4946). English, eleven Indian languages, Bulgarian, Turkish and Russian hyphenate by run language, and German, Polish, Portuguese and Italian do in builds that embed their patterns; a word outside its language's script stays whole; Sanskrit automatic hyphenation awaits allowlisted patterns (#4947). Not yet: `.ai`/PDF import of a text's language, paragraph styles. Evidence: `features::tests::language_picks_the_fonts_forms`, `features::tests::serbian_gets_the_fonts_serbian_forms`, `typecmd::area_tests::language_is_a_character_attribute_saved_only_when_set`, `tests::typo::indic_language_runs_hyphenate_with_both_composers`, `hyphen::tests::sanskrit_without_allowlisted_patterns_uses_only_exceptions`, `hyphen::tests::rule_languages_break_by_their_own_rules`, `hyphen::tests::pattern_languages_break_at_their_own_patterns`, `tests::typo::a_russian_run_hyphenates_at_russian_break_points`; spelling is checked in each run's Language (`text.spelling.check`, #4936) | -| Language per character (Character panel › Language, character styles), text shaped in it | done | `text.setFormat` / `text.setRangeStyle {language}` by name or BCP 47 tag, one of Document Setup's languages (Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu added, #4943; Serbian: Cyrillic, Serbian: Latin and Croatian; Bulgarian, #5945); the shaper gets the tag, so the font's language forms apply (OpenType `locl`: Turkish keeps `fi` apart and the dot on its i, #4940); new type takes the document's language; saved as the tag only when set, carried by character styles (#4946). Not yet: hyphenation by it in languages other than English, the eleven Indian languages above, Bulgarian, Turkish, Russian, German, Polish, Portuguese and Italian, `.ai`/PDF import of a text's language, paragraph styles. Evidence: `features::tests::language_picks_the_fonts_forms`, `features::tests::serbian_gets_the_fonts_serbian_forms`, `typecmd::area_tests::language_is_a_character_attribute_saved_only_when_set`; spelling is checked in each run's Language (`text.spelling.check`, #4936) | +| Language per character (Character panel › Language, character styles), text shaped in it | done | `text.setFormat` / `text.setRangeStyle {language}` by name or BCP 47 tag, one of Document Setup's languages (Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu added, #4943; Assamese and Sanskrit added, #4947; Nepali, Konkani and Sindhi added, #4943; Serbian: Cyrillic, Serbian: Latin and Croatian; Bulgarian, #5945); the shaper gets the tag, so the font's language forms apply (OpenType `locl`: Turkish keeps `fi` apart and the dot on its i, #4940); new type takes the document's language; saved as the tag only when set, carried by character styles (#4946). English, eleven Indian languages, Bulgarian, Turkish and Russian hyphenate by run language, and German, Polish, Portuguese and Italian do in builds that embed their patterns; a word outside its language's script stays whole; Sanskrit automatic hyphenation awaits allowlisted patterns (#4947). Not yet: `.ai`/PDF import of a text's language, paragraph styles. Evidence: `features::tests::language_picks_the_fonts_forms`, `features::tests::serbian_gets_the_fonts_serbian_forms`, `typecmd::area_tests::language_is_a_character_attribute_saved_only_when_set`, `tests::typo::indic_language_runs_hyphenate_with_both_composers`, `hyphen::tests::sanskrit_without_allowlisted_patterns_uses_only_exceptions`, `hyphen::tests::rule_languages_break_by_their_own_rules`, `hyphen::tests::pattern_languages_break_at_their_own_patterns`, `tests::typo::a_russian_run_hyphenates_at_russian_break_points`, `tests::docsetup::the_further_indian_languages_are_document_and_text_languages`; spelling is checked in each run's Language (`text.spelling.check`, #4936) | | No Break | done | Character panel menu (`text.setFormat` / `text.setRangeStyle {noBreak}`): the marked characters stay on one line, including across a space; a run that does not fit after earlier text moves together, and a run longer than the line stays together. Evidence: `layout::wrapping_tests::no_break_keeps_marked_characters_on_one_line`, `tests::no_break_keeps_marked_words_on_one_line`, `typecmd::no_break_is_a_character_attribute_saved_only_when_on` | | Inline symbols in text | beyond Illustrator | not scored | | Align Stroke (inside, outside) on live type's character stroke | beyond Illustrator | not scored; `stroke.set {align}` and `text.setRangeStyle {strokeOptions: {align}}`; saved natively, drawn around the glyphs on the canvas and in PDF, EPS and SVG (live text, stroke on the glyph outlines); visual bounds grow with it (#2294) | @@ -108,6 +107,7 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | 2026-11-09 | minor | PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged. Decoded stream and placement regressions; reader ActualText (#6165), styled clusters and external viewer validation remain separate. | | 2026-11-09 | minor | Custom dictionary and Ignore All (#4936): `text.spelling.addWord`, `removeWord`, `changeWord` and `dictionary`, saved beside the preferences, and `text.spelling.ignoreAll` for the active document; the Check Spelling and Edit Custom Dictionary dialogs and Auto Spell Check remain. Scores and estimates unchanged. | | 2026-11-08 | minor | Spell check engine (#4936): `text.spelling.check` lists unknown words per run language at `text.editRange` byte offsets and `text.spelling.suggest` gives suggestions, from craft-proof; the dialog, Auto Spell Check and the custom dictionary remain. Spelling noted in the Language per character rows, which no longer list it as not yet done; their hyphenation note names the languages that still lack it. Scores and estimates unchanged. | +| 2026-11-10 | minor | Nepali (`ne`), Konkani (`kok`) and Sindhi (`sd`) complete the remaining language-list additions (#4943); Assamese and Sanskrit already landed in #5946. The five languages use quotes inherited from [CLDR root](https://github.com/unicode-org/cldr/blob/main/common/main/root.xml). Hyphenation behavior from #4947 is retained; scores unchanged | | 2026-11-07 | minor | Tabs: in right-aligned area type, the text before a line's last tab sits at its stops, measured from the left edge, and the text after it (none, when the tab ends the line) against the right edge; the line was aligned as a whole, which moved its start off the left edge. Illustrator's own layout in a user's `.ai` (used locally, not committed) sets its price lists so. Centred and justified lines keep their alignment as a whole. Scores and estimates unchanged. | | 2026-11-07 | minor | Soft return: in Justify Left, Center or Right, the line a soft return ends is justified as a wrapped line is; only the paragraph's last line keeps its alignment. Illustrator's own layout in a user's `.ai` (used locally, not committed) justifies those lines. Scores and estimates unchanged. | | 2026-11-08 | minor | Style panels: a double-click on a user character style's row opens its Character Style Options (`ui.charStyleOptions`), and on a paragraph style's row its Paragraph Style Options (rename); the Character Style Options dialog keeps a fixed width and scrolls its sections in a shorter window, so OK and Cancel stay on screen. Tests `panels::text_styles::tests::double_clicking_a_character_style_row_opens_its_options` and `dialogs::char_style_options::tests::the_sections_scroll_in_a_window_shorter_than_the_general_list`. Scores and estimates unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8e06948b33..9a2e406d2d 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (#8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -53,6 +53,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-09 | minor | Document Setup and Character panel Language lists: Nepali, Konkani and Sindhi complete #4943; Assamese and Sanskrit are already present from #5946. Names in all 27 catalogs come from [CLDR locale language-name data](https://github.com/unicode-org/cldr/tree/main/common/main). The public [language assignment documentation](https://helpx.adobe.com/illustrator/using/spelling-language-dictionaries.html) describes the Character panel Language menu, but does not establish that these five languages are listed there; inclusion and a single Sindhi entry remain maintainer decisions. Scores unchanged | | 2026-11-14 | minor | G5: Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. | | 2026-11-14 | minor | Layers panel: right-clicking a layer/group/object row shows a context menu with Options…, Duplicate, Delete, Lock/Hide Others, Locate Object, and Collect for Export — matching standard desktop layer panel conventions. Scores unchanged. | | 2026-11-13 | minor | Pencil cursors: the continuation cursor (a short rising line) shows over an open end of a selected path before any press, freehand too, and while a continuing stroke nears another selected path's open end it connects to; the straight-line cursor is a short level line; a continued path, a straight line too, shows the closing cursor and closes within Close Paths When Ends Are Within of its other end, and with Alt at the release. Scores and estimates unchanged. | @@ -505,7 +506,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po - [x] Home screen (part of #4684, shared UI with PhotoCraft): the welcome, New / Open buttons and Community block are centred, and the large Discord button takes the theme's accent instead of Discord's colour; the layout and wording of the preset cards and Recent Files are unchanged. Still open from #4684: shortcut hints on the buttons, PhotoCraft's PRO and STUDIO themes, the Preferences layout (search box, theme swatches, Apply) and the title bar. -- [x] Recolor Artwork › Assign: double-click a row's new color to pick it in the Color Picker, in the model it was picked in, with native Lab entry, swatch libraries access in the picker, and row context menu options (Pick from Swatches, Limit to Library) (#4028). +- [x] Recolor Artwork › Assign: double-click a row's new color to pick it in the Color Picker, in the model it was picked in, with native Lab entry, swatch libraries access in the picker, and row context menu options (Pick from Swatches, Limit to Library) (#8031, follow-up to #4090/#5113 for #4028). Evidence: `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise numeric entry and actual menu clicks. - [x] Recolor Artwork › Color Theme Picker: with the button beside the tabs on, a click on the canvas takes the color palette of an object or image, a drag takes the palette of the art inside its marquee, and Shift adds more picks; the rows that aren't excluded take the palette as their new colors and the art previews them ([Recolor artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/recolor-artwork.html)). The number and order of the picked colors are VectorCraft's own rule (`recolor.pickTheme`). Tests: `theme_picks_give_the_rows_the_palette_of_the_art_picked` and `the_theme_picker_takes_clicks_and_shift_drags_on_the_canvas` in `crates/ui-egui/src/dialogs/recolor.rs`, `theme_picker_*` in `crates/engine/src/tests/recolor.rs`. @@ -554,6 +555,8 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged. | +| 2026-11-16 | minor | Recolor Artwork › Assign: native Lab entry in the Color Picker, swatch libraries access in the picker, and row context menu options (Pick from Swatches, Limit to Library) (#4028). Scores and estimates unchanged. | | 2026-11-16 | minor | Color panel: the spectrum fills the vertical space of a resized panel, with options shown or hidden (#8005). Compact auto-fit flyouts and embedded mixers keep their existing size. Evidence: panels::color::tests::the_spectrum_grows_with_the_color_panel. Scores and estimates unchanged. | | 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. | | 2026-11-12 | minor | Numeric fields: a focus click released more than 1 pt from its press keeps the caret; a tap within 1 pt still selects the whole value (#6659, follow-up to #1326). Scores and estimates unchanged. | diff --git a/licenses/jpeg-encoder-0.6.1/IJG-NOTICE.txt b/licenses/jpeg-encoder-0.6.1/IJG-NOTICE.txt new file mode 100644 index 0000000000..4fcb9b583b --- /dev/null +++ b/licenses/jpeg-encoder-0.6.1/IJG-NOTICE.txt @@ -0,0 +1,72 @@ +/* + * 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. + */ diff --git a/licenses/jpeg-encoder-0.6.1/LICENSE-APACHE b/licenses/jpeg-encoder-0.6.1/LICENSE-APACHE new file mode 100644 index 0000000000..dae6969815 --- /dev/null +++ b/licenses/jpeg-encoder-0.6.1/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/licenses/jpeg-encoder-0.6.1/LICENSE-MIT b/licenses/jpeg-encoder-0.6.1/LICENSE-MIT new file mode 100644 index 0000000000..6a4eb87467 --- /dev/null +++ b/licenses/jpeg-encoder-0.6.1/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2021 Volker Ströbel + +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. \ No newline at end of file diff --git a/licenses/jpeg-encoder-0.6.1/SIMD-NOTICE.txt b/licenses/jpeg-encoder-0.6.1/SIMD-NOTICE.txt new file mode 100644 index 0000000000..58e09bf431 --- /dev/null +++ b/licenses/jpeg-encoder-0.6.1/SIMD-NOTICE.txt @@ -0,0 +1,8 @@ +/* + * Ported from mozjpeg / jfdctint-avx2.asm to rust + * Copyright 2009 Pierre Ossman 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. + */ diff --git a/licenses/jpeg-encoder-0.6.1/SOURCE.json b/licenses/jpeg-encoder-0.6.1/SOURCE.json new file mode 100644 index 0000000000..8a7fb7ab24 --- /dev/null +++ b/licenses/jpeg-encoder-0.6.1/SOURCE.json @@ -0,0 +1,29 @@ +{ + "package": "jpeg-encoder", + "version": "0.6.1", + "source": "https://crates.io/crates/jpeg-encoder/0.6.1", + "registry_checksum": "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f", + "license": "(MIT OR Apache-2.0) AND IJG", + "files": { + "LICENSE-MIT": { + "source": "LICENSE-MIT", + "source_sha256": "4d022727ea392ebba2fe5e9a5f78c610a0eae506b491f3db29c78b6d430d6503", + "sha256": "4d022727ea392ebba2fe5e9a5f78c610a0eae506b491f3db29c78b6d430d6503" + }, + "LICENSE-APACHE": { + "source": "LICENSE-APACHE", + "source_sha256": "85a884980abd6032fc6b5439ba918ab16db9ac9051b5cf18db9c27c587df07c0", + "sha256": "85a884980abd6032fc6b5439ba918ab16db9ac9051b5cf18db9c27c587df07c0" + }, + "IJG-NOTICE.txt": { + "source": "src/fdct.rs", + "source_sha256": "0b59244bbd05b2593ded252ecf0d010a8a4c6ec1d4713b3caeb6fb724586e4d6", + "sha256": "432424ca69caaa82565c0491c11cdab311a2e7d39180970b8ba22017996bf678" + }, + "SIMD-NOTICE.txt": { + "source": "src/avx2/fdct.rs", + "source_sha256": "bc362322f568f92c3699f4ca2922b261c12b7dd997120b01fd3cab58d9d2f9ab", + "sha256": "ee36eeaa9df1f7f09c7046f428ce4a848fcf518394e63d3e2125ec261949e8ba" + } + } +} diff --git a/sonar-project.properties b/sonar-project.properties index 287b7eb9cf..9a1a027a81 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -1,6 +1,15 @@ sonar.projectKey=storytold_vectorcraft sonar.organization=storytold +# Sources and tests both start at the root, as in craft-libs: sonar.tests alone stops the +# scanner defaulting sources to the repository. Test files are the ones the coverage job +# leaves out of lcov (tests/ directories, tests.rs and *_tests.rs), plus this repo's +# tests_*.rs naming. Classifying them as tests keeps coverage and duplication on new code +# measuring the product, not the tests. +sonar.sources=. +sonar.tests=. +sonar.test.inclusions=**/tests/**,**/tests.rs,**/*_tests.rs,**/tests_*.rs + # S4790 (weak hash): MD5 is the key derivation of the PDF standard security handler revisions 2-4 # (ISO 32000-1 §7.6.3.3), which PDF 1.3-1.6 files use. It is needed to read those files and to write # the compatibility the user picks, not chosen for new security: the default is 256-bit AES diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 180e90bc3e..02216d18f2 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,7 +5,7 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"; +const REV: &str = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV),