diff --git a/Cargo.lock b/Cargo.lock index 887b10ab11..4f74f10fc4 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", ] @@ -508,6 +523,12 @@ dependencies = [ "serde", ] +[[package]] +name = "bit_field" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1" + [[package]] name = "bitflags" version = "1.3.2" @@ -590,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]] @@ -601,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]] @@ -970,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", @@ -981,17 +1012,17 @@ dependencies = [ [[package]] name = "craft-codepage" 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-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=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2" +source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" dependencies = [ "craft-codepage", "encoding_rs", @@ -1003,17 +1034,33 @@ 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=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +dependencies = [ + "flate2", +] [[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", @@ -1033,20 +1080,122 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-image-codecs" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830#431f704478962677ec47e512754464d372901830" +dependencies = [ + "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830)", + "crc32fast", + "exr", + "flate2", + "half", + "hayro-jpeg2000", + "image", + "image-webp", + "jpeg-encoder", + "png 0.18.1", + "rayon", + "serde_json", + "thiserror 2.0.21", + "tiff", + "zune-core", + "zune-jpeg", + "zune-jpegxl", +] + +[[package]] +name = "craft-image-codecs" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +dependencies = [ + "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "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=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", @@ -1057,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", @@ -1068,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", @@ -1082,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", @@ -1090,14 +1239,40 @@ dependencies = [ "unicode-normalization", ] +[[package]] +name = "craft-psd" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +dependencies = [ + "encoding_rs", + "flate2", + "rayon", + "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", + "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", @@ -1105,10 +1280,28 @@ dependencies = [ "vectorcraft-pathops 0.18.0", ] +[[package]] +name = "craft-tiff" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830#431f704478962677ec47e512754464d372901830" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-tiff" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + [[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", @@ -1129,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", @@ -1156,7 +1349,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" 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 = [ "flate2", "serde", @@ -1178,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", @@ -1189,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", ] @@ -1197,9 +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=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +dependencies = [ + "quick-xml 0.41.0", + "serde", "thiserror 2.0.21", ] @@ -1677,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]] @@ -1715,6 +1919,22 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "exr" +version = "1.74.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6" +dependencies = [ + "bit_field", + "half", + "lebe", + "miniz_oxide 0.8.9", + "multiversion", + "rayon-core", + "smallvec", + "zune-inflate", +] + [[package]] name = "fastrand" version = "2.5.0" @@ -2054,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" @@ -2297,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", @@ -2306,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", @@ -2324,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", @@ -2342,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", @@ -2357,7 +2567,7 @@ dependencies = [ "rustc-hash 2.1.3", "smallvec", "stringprep", - "zune-jpeg 0.5.15", + "zune-jpeg", ] [[package]] @@ -2742,14 +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]] @@ -2839,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" @@ -3002,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", @@ -3034,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", @@ -3140,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", @@ -3161,7 +3378,7 @@ dependencies = [ "tiny-skia-path 0.12.0", "xmp-writer", "yoke", - "zune-jpeg 0.5.15", + "zune-jpeg", ] [[package]] @@ -3200,6 +3417,12 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" +[[package]] +name = "lebe" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" + [[package]] name = "libc" version = "0.2.191" @@ -3243,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", @@ -3399,6 +3622,28 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "multiversion" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076" +dependencies = [ + "multiversion-macros", + "target-features", +] + +[[package]] +name = "multiversion-macros" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "target-features", +] + [[package]] name = "multiversion_no_op" version = "1.0.0" @@ -3926,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]] @@ -4349,21 +4594,21 @@ dependencies = [ "unarray", ] -[[package]] -name = "psd" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a25f9b8cfffd65d911baf31a033239f7a0facb755faa2481575b70db5dc9195" -dependencies = [ - "thiserror 1.0.69", -] - [[package]] name = "pxfm" version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" +[[package]] +name = "qoi" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001" +dependencies = [ + "bytemuck", +] + [[package]] name = "quick-error" version = "1.2.3" @@ -4448,7 +4693,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -4688,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]] @@ -4706,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", @@ -4714,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]] @@ -4826,7 +5068,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -4885,7 +5127,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5734,6 +5976,12 @@ dependencies = [ "xattr", ] +[[package]] +name = "target-features" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5" + [[package]] name = "tempfile" version = "3.27.0" @@ -5744,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]] @@ -5816,7 +6064,7 @@ dependencies = [ "half", "quick-error 2.0.1", "weezl 0.1.12", - "zune-jpeg 0.5.15", + "zune-jpeg", ] [[package]] @@ -6423,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", ] @@ -6452,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", @@ -6504,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", @@ -6515,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", @@ -6545,10 +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-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", @@ -6558,7 +6814,6 @@ dependencies = [ "log", "proptest", "rayon", - "roxmltree 0.21.2", "rustix 1.1.6", "ruzstd", "same-file", @@ -6566,6 +6821,7 @@ dependencies = [ "serde_json", "skrifa 0.47.0", "thiserror 2.0.21", + "tiff", "vectorcraft-affinity", "vectorcraft-apischema", "vectorcraft-brush", @@ -6585,10 +6841,11 @@ dependencies = [ "vectorcraft-svg", "vectorcraft-testkit", "vectorcraft-text", + "vectorcraft-three-d", "vectorcraft-tools", "vectorcraft-trace", "wat", - "zune-core 0.5.3", + "zune-core", "zune-jpegxl", ] @@ -6597,11 +6854,12 @@ name = "vectorcraft-eps" version = "0.24.1" dependencies = [ "craft-eps", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", "craft-pdf", + "craft-stream-codecs", "encoding_rs", "fax", "flate2", - "hayro-ccitt", "image", "kurbo 0.13.1", "memchr", @@ -6625,6 +6883,7 @@ dependencies = [ name = "vectorcraft-format" version = "0.24.1" dependencies = [ + "craft-gzip", "craft-vectorcraft-format", "flate2", "proptest", @@ -6674,6 +6933,7 @@ dependencies = [ name = "vectorcraft-mcp" version = "0.24.1" dependencies = [ + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", "image", "log", "proptest", @@ -6693,6 +6953,7 @@ dependencies = [ name = "vectorcraft-metafile" version = "0.24.1" dependencies = [ + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", "craft-metafile", "image", "kurbo 0.13.1", @@ -6733,7 +6994,10 @@ version = "0.24.1" dependencies = [ "aes", "chrono", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", "craft-pdf", + "craft-stream-codecs", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", "flate2", "getrandom 0.4.3", "image", @@ -6744,7 +7008,6 @@ dependencies = [ "md-5", "objc2-core-foundation", "objc2-core-graphics", - "roxmltree 0.21.2", "serde", "serde_json", "sha2", @@ -6759,15 +7022,14 @@ dependencies = [ "vectorcraft-geom 0.24.1", "vectorcraft-testkit", "vectorcraft-text", - "weezl 0.2.1", ] [[package]] name = "vectorcraft-plugins" version = "0.24.1" dependencies = [ + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", "craft-vectorcraft-format", - "image", "log", "serde", "serde_json", @@ -6785,16 +7047,17 @@ dependencies = [ name = "vectorcraft-render" version = "0.24.1" dependencies = [ + "craft-gif", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "craft-psd", + "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", - "png 0.18.1", "proptest", - "psd", "serde_json", - "tiff", "unicode-general-category", "vectorcraft-brush", "vectorcraft-color", @@ -6824,13 +7087,13 @@ name = "vectorcraft-svg" version = "0.24.1" dependencies = [ "craft-docpath", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", "craft-svg", "data-url", "flate2", "image", "kurbo 0.13.1", "proptest", - "resvg 0.45.1", "serde", "serde_json", "simplecss", @@ -6853,8 +7116,8 @@ dependencies = [ name = "vectorcraft-testkit" version = "0.24.1" dependencies = [ + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", "fax", - "image", "kurbo 0.13.1", "proptest", "serde_json", @@ -6892,6 +7155,7 @@ dependencies = [ name = "vectorcraft-three-d" version = "0.24.1" dependencies = [ + "proptest", "vectorcraft-geom 0.24.1", "vectorcraft-pathops 0.24.1", ] @@ -6900,7 +7164,7 @@ dependencies = [ name = "vectorcraft-tools" version = "0.24.1" dependencies = [ - "image", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", "kurbo 0.13.1", "serde", "serde_json", @@ -6917,6 +7181,7 @@ dependencies = [ name = "vectorcraft-trace" version = "0.24.1" dependencies = [ + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", "image", "kurbo 0.13.1", "serde", @@ -6931,6 +7196,7 @@ version = "0.24.1" dependencies = [ "bytemuck", "chrono", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", "craft-keymap", "craft-ui", "craft-update", @@ -7607,7 +7873,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -7885,7 +8151,7 @@ dependencies = [ [[package]] name = "winprint" version = "0.2.1" -source = "git+https://github.com/storytold/winprint.rs?rev=5f80b9baf6b58937c401656634e42d33f00ddf49#5f80b9baf6b58937c401656634e42d33f00ddf49" +source = "git+https://github.com/storytold/winprint.rs?rev=8ae097ef941b432b0e7671b1ec3a506800e65e57#8ae097ef941b432b0e7671b1ec3a506800e65e57" dependencies = [ "flate2", "fmt-derive", @@ -7900,6 +8166,7 @@ dependencies = [ "windows", "windows-core", "windows-implement", + "windows-numerics", "xml", ] @@ -8359,12 +8626,6 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" -[[package]] -name = "zune-core" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a" - [[package]] name = "zune-core" version = "0.5.3" @@ -8372,12 +8633,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" [[package]] -name = "zune-jpeg" -version = "0.4.21" +name = "zune-inflate" +version = "0.2.54" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29ce2c8a9384ad323cf564b67da86e21d3cfdff87908bc1223ed5c99bc792713" +checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02" dependencies = [ - "zune-core 0.4.12", + "simd-adler32", ] [[package]] @@ -8386,7 +8647,7 @@ 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]] @@ -8395,7 +8656,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cba11ecd07cc23351500e840ae03841b7e4997923ec8e4832ee3ae199ea0b6b4" dependencies = [ - "zune-core 0.5.3", + "zune-core", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 610e2b462c..89d6328ea7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,29 +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 = "e98299546f5c5c3c22388d16507f8b5e61a5f280" } +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 = "6d620e971e820b517b11a99cad040ebac670e1e2" } +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-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" } @@ -91,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. @@ -106,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 @@ -130,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" @@ -173,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/ROADMAP.md b/ROADMAP.md index 253c7ef45f..4358817b60 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -24,7 +24,7 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)). | | Value | Kind | |---|---|---| -| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 348/375 wired (92.8%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) | +| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 717/719 wired (99.7%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) | | **Feature depth** (weighted by use, scored by behaviour) | **~75%** | estimated | | **To beta** | **~170–270 h** one agent · ~50–80 h with 4–6 agents | estimated | | **To full parity** | **~360–590 h** one agent · ~95–165 h with 4–6 agents | estimated | @@ -102,14 +102,14 @@ Weights, evidence and the missing items per area: [target-app-parity.md](docs/ta | Arabic | `ar` | none (no right-to-left interface) | 0% | | French | `fr` | full | 100% | | Portuguese (Brazil) | `pt-br` | full | 100% | -| Indonesian | `id` | none | 0% | +| Indonesian | `id` | 6,947 catalog rows; status and error messages partial | most dialogs and tooltips | | Japanese | `ja` | full | 100% | | German | `de` | full | 98% | | Korean | `ko` | full | 100% | | Bosnian | `bs` | full (AI-assisted, native review pending) | 100% | | Vietnamese | `vi` | full | 100% | -Also shipped: Traditional Chinese (partial, 80%), Bulgarian, Finnish, Greek, Hungarian, Italian, Polish, Russian, Swedish, Ukrainian and Georgian (full), Catalan (full; AI-drafted, native review welcome), Czech (catalog complete; render-site gaps reduced; native review pending). +Also shipped: Traditional Chinese (partial, 80%), Bulgarian, Finnish, Greek, Hungarian, Italian, Polish, Russian, Swedish, Ukrainian, Georgian, Dutch, Danish and Turkish (full), Catalan (full; AI-drafted, native review welcome), Czech (catalog complete; render-site gaps reduced; native review pending). The Georgian catalog has had a native speaker's review; no other catalog has. Details: [localization-parity.md](docs/localization-parity.md). ## Upcoming @@ -131,8 +131,11 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged. - 2026-11-13: Banner Hems and Grommets in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): on the chosen sides of the selected art's bounds, or of each artboard, a hem line at a set depth inside the edge and grommet marks (a circle with a cross) at a set inset, one at each end of a side and the rest spread evenly at most a set spacing apart, stroked in a chosen swatch; a dialog with Preview, one undo step (`addon.cutting.banner`). A VectorCraft addition: headline numbers unchanged. - 2026-11-14: Nest Shapes in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): the selected objects move close together onto an artboard, a sheet of a set size or a roll of a set width, packed by their bounding boxes with a margin inside the edges and a spacing between them, optionally turning objects 90° to fit; objects that do not fit go in a column beside the sheet; a dialog with Preview, one undo step (`addon.cutting.nest`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-15: With Smart Guides and Snap to Tangent on, a circle drawn from its center with the Ellipse tool (Alt and Shift) snaps its radius so that the circle touches a nearby path (a straight segment, a curve, or another circle from outside or inside) when the radius comes within the snapping tolerance of that size, and the touch point shows the "tangent" label. A VectorCraft addition: headline numbers unchanged. - 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged. - 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged. +- 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). @@ -142,9 +145,12 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922). - 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925). - 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917). +- 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. +- 2026-11-15: Common Tangents in the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the straight lines that touch two selected convex closed paths (ellipses at any rotation and scale, or convex Bézier paths) without crossing either are added as open paths with the current stroke: external, internal or all, and the line joining the centers if asked; a path inside the other has none unless the two touch, and a message says why; a dialog with Preview, one undo step (`addon.pathtools.commonTangents`, #7845). A VectorCraft addition: headline numbers unchanged. +- 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged. - 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index b66c15070f..4711232643 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -238,10 +238,11 @@ fn main() -> ExitCode { /// A headless session that remembers what the user keeps between runs: the PDF presets saved, the /// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders /// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there -/// (`script.listInstalled`) and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and +/// (`script.listInstalled`), keeps File Info's metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and /// `VECTORCRAFT_CONFIG_DIR` apply as they do there. fn with_stores(mut h: Headless) -> Headless { prefs_dir::attach_scripts_dir(&mut h.session); + prefs_dir::attach_metadata_templates_dir(&mut h.session); prefs_dir::attach_new_doc_profiles(&mut h.session); prefs_dir::attach_profile_store(&mut h.session); prefs_dir::attach_color_settings(&mut h.session); diff --git a/apps/vectorcraft/src/clipboard.rs b/apps/vectorcraft/src/clipboard.rs index ec6256a114..3568b4683e 100644 --- a/apps/vectorcraft/src/clipboard.rs +++ b/apps/vectorcraft/src/clipboard.rs @@ -155,8 +155,18 @@ fn copied_file(paths: Vec, mimes: &[&'static str]) -> Option { copied_file_within(paths, mimes, MAX_BYTES) } +/// Whether a paste of one of `mimes` can take a copied file: one of them is not text. +#[cfg_attr(windows, allow(dead_code))] +fn takes_files(mimes: &[&'static str]) -> bool { + mimes.iter().any(|&m| m != TEXT) +} + /// [`copied_file`] with a file of more than `limit` bytes skipped. fn copied_file_within(paths: Vec, mimes: &[&'static str], limit: usize) -> Option { + // A list of more than MAX_URIS files (untrusted data) names none, before any file is looked at. + if paths.len() > MAX_URIS { + return None; + } paths.into_iter().find_map(|path| { // text/uri-list lines end in CRLF (RFC 2483), but arboard splits them on LF only. let path = match path.to_str() { @@ -197,6 +207,53 @@ fn read_rest(file: impl Read, mut data: Vec, limit: usize) -> Option (data.len() <= limit).then_some(data) } +/// The data `copy` takes off the clipboard, called only when `size` (what the clipboard reports +/// before the copy) is known and from 1 to `limit` bytes. `None` without a call otherwise, and +/// when the copy comes to more than `limit` bytes. +#[cfg_attr(not(any(windows, target_os = "macos")), allow(dead_code))] +fn copy_within(size: Option, limit: usize, copy: impl FnOnce() -> Option>) -> Option> { + size.filter(|&n| n > 0 && n <= limit)?; + copy().filter(|data| data.len() <= limit) +} + +/// The most bytes of UTF-8 that `utf16` bytes of UTF-16 text come to: a code unit (2 bytes) is at +/// most 3 bytes of UTF-8, and a surrogate pair (4 bytes) is 4. +#[cfg_attr(not(windows), allow(dead_code))] +fn utf8_most(utf16: usize) -> usize { + utf16.div_ceil(2).saturating_mul(3) +} + +/// Whether a Windows file list (`CF_HDROP`: a `DROPFILES` header, then file names each ended by a +/// NUL and the list by one more, in UTF-16 when the header's `fWide` is set) names at most `limit` +/// files. Counting stops at the first name past `limit`. A block too short for its header, or +/// whose names would start past its end, is not within. +#[cfg_attr(not(windows), allow(dead_code))] +fn drop_files_within(block: &[u8], limit: usize) -> bool { + let field = |at: usize| Some(u32::from_le_bytes(block.get(at..at.checked_add(4)?)?.try_into().ok()?)); + let (Some(start), Some(wide)) = (field(0), field(16)) else { + return false; + }; + let Some(names) = usize::try_from(start).ok().and_then(|start| block.get(start..)) else { + return false; + }; + let (mut count, mut in_name) = (0usize, false); + for unit in names.chunks_exact(if wide != 0 { 2 } else { 1 }) { + if unit.iter().all(|&b| b == 0) { + if !in_name { + break; + } + in_name = false; + } else if !in_name { + in_name = true; + count += 1; + if count > limit { + return false; + } + } + } + true +} + /// The most URIs a copied file list may hold, VectorCraft's own limit: a longer list (untrusted /// data) names no files. const MAX_URIS: usize = 1024; @@ -278,12 +335,13 @@ fn file_uri_path(uri: &str) -> Option { #[cfg(windows)] mod win { - use std::num::NonZeroU32; + use std::num::{NonZeroU32, NonZeroUsize}; use clipboard_win::{formats, options::NoClear, raw}; use super::{ - BITMAP, ClipboardRead, Cursor, Flavour, PNG, SVG, SystemClipboard, TEXT, copied_file, decode_png, dib_image, png_flavour, windows_formats, + BITMAP, ClipboardRead, Cursor, Flavour, MAX_BYTES, MAX_URIS, PNG, SVG, SystemClipboard, TEXT, copied_file, copy_within, decode_png, + dib_image, drop_files_within, png_flavour, utf8_most, windows_formats, }; /// The device-independent bitmaps, the one that carries alpha first. Each is there whenever the @@ -370,8 +428,11 @@ mod win { let mut files = vec![]; { let _open = clipboard_win::Clipboard::new_attempts(10).ok()?; - // None copied when the clipboard holds no file list. - let _ = raw::get_file_list_path(&mut files); + // None copied when the clipboard holds no file list, or one of more than MAX_BYTES + // or MAX_URIS files: the list is counted before its names are copied. + if copy_registered(formats::CF_HDROP, MAX_BYTES).is_some_and(|block| drop_files_within(&block, MAX_URIS)) { + let _ = raw::get_file_list_path(&mut files); + } } // The files are read with the clipboard closed again, not keeping other apps waiting. copied_file(files, mimes).map(ClipboardRead::Now).or_else(|| { @@ -390,44 +451,64 @@ mod win { } } - /// Read the first registered format of `mime` the clipboard holds into `data`. - fn read_registered(mime: &str, data: &mut Vec) -> bool { - formats_of(mime).filter(|id| raw::is_format_avail(*id)).any(|id| { - data.clear(); - raw::get_vec(id, data).is_ok() && !data.is_empty() + /// The size the clipboard reports for format `id`, while it is open. + fn size_of(id: u32) -> Option { + raw::size(id).map(NonZeroUsize::get) + } + + /// The data of format `id`, while the clipboard is open, copied only when its size is at most + /// `limit` bytes ([`copy_within`]). + fn copy_registered(id: u32, limit: usize) -> Option> { + copy_within(size_of(id), limit, || { + let mut data = vec![]; + raw::get_vec(id, &mut data).ok()?; + Some(data) }) } + /// The first registered format of `mime` the clipboard holds that is not empty and at most + /// [`MAX_BYTES`]; a larger one is skipped and the next tried. + fn read_registered(mime: &str) -> Option> { + formats_of(mime).filter(|id| raw::is_format_avail(*id)).find_map(|id| copy_registered(id, MAX_BYTES).filter(|data| !data.is_empty())) + } + /// A device-independent bitmap as a PNG flavour. fn dib_png(dib: &[u8]) -> Option { png_flavour(&dib_image(dib)?) } /// Copy both bitmap formats while the clipboard is open, then decode them in preference order. - pub(super) fn read_dibs(mut get: impl FnMut(u32) -> Option>) -> Option { - let dibs: Vec<_> = DIBS.into_iter().filter_map(&mut get).collect(); + /// `size` gives each format's size before `get` copies it, and a format of more than + /// [`MAX_BYTES`] is not copied ([`copy_within`]) and the next one is tried. + pub(super) fn read_dibs(mut size: impl FnMut(u32) -> Option, mut get: impl FnMut(u32) -> Option>) -> Option { + let dibs: Vec<_> = DIBS.into_iter().filter_map(|id| copy_within(size(id), MAX_BYTES, || get(id))).collect(); (!dibs.is_empty()).then_some(ClipboardRead::Later(Box::new(move || dibs.iter().find_map(|dib| dib_png(dib))))) } /// One flavour, while the clipboard is open. A device-independent bitmap is copied here, and - /// the work that comes back decodes each captured format in preference order. + /// the work that comes back decodes each captured format in preference order. Text whose + /// UTF-16 block could come to more than [`MAX_BYTES`] as UTF-8 ([`utf8_most`]) is not read. fn read_one(mime: &'static str) -> Option { - let mut data = vec![]; - let mime = match mime { - BITMAP if read_registered(PNG, &mut data) => PNG, - BITMAP => { - return read_dibs(|id| { - let mut dib = vec![]; - raw::get_vec(id, &mut dib).ok()?; - Some(dib) - }); - } + let (mime, mut data) = match mime { + BITMAP => match read_registered(PNG) { + Some(png) => (PNG, png), + None => { + return read_dibs(size_of, |id| { + let mut dib = vec![]; + raw::get_vec(id, &mut dib).ok()?; + Some(dib) + }); + } + }, TEXT => { - raw::get_string(&mut data).ok()?; - TEXT + let text = copy_within(size_of(formats::CF_UNICODETEXT).map(utf8_most), MAX_BYTES, || { + let mut text = vec![]; + raw::get_string(&mut text).ok()?; + Some(text) + })?; + (TEXT, text) } - m if read_registered(m, &mut data) => m, - _ => return None, + m => (m, read_registered(m)?), }; // Memory blocks can be longer than the data: SVG text ends at its first NUL. if mime == SVG @@ -727,7 +808,7 @@ mod portable { use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; - use super::{BITMAP, ClipboardRead, Flavour, PNG, SystemClipboard, TEXT, copied_file, decode_png, png_flavour, text_of}; + use super::{BITMAP, ClipboardRead, Flavour, PNG, SystemClipboard, TEXT, copied_file, decode_png, png_flavour, takes_files, text_of}; /// What our last write put on the clipboard. #[derive(Clone)] @@ -741,7 +822,7 @@ mod portable { } /// A read of arboard's clipboard. - #[derive(Clone, Copy, PartialEq, Eq)] + #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum Request { Text, Image, @@ -813,6 +894,19 @@ mod portable { } } + /// Whether a paste of one of `mimes` can take what `cb` holds: text that is not empty when one + /// of `mimes` is text (`text` reads it), else files copied in a file manager when one of `mimes` + /// is not text (`files` reads the list). The list is read only when the text doesn't do, and no + /// copied file is opened: Paste checks the files themselves. + fn arboard_has( + mimes: &[&'static str], + cb: &mut B, + text: impl FnOnce(&mut B) -> Result, + files: impl FnOnce(&mut B) -> Vec, + ) -> bool { + (mimes.contains(&TEXT) && text(cb).is_ok_and(|t| !t.is_empty())) || (takes_files(mimes) && !files(cb).is_empty()) + } + /// `request` read on `reads`' worker, waiting `wait` at most. #[cfg(test)] fn read_within(reads: &mut super::loads::Loads, request: Request, wait: Duration) -> Answer { @@ -1441,10 +1535,11 @@ mod portable { read } - /// Text, on macOS vector art or a bitmap (by the pasteboard's types), and on the Wayland - /// core protocol copied files, SVG, text or PNG (by the types offered, nothing read). + /// Text or files copied in a file manager (their list read, no file opened: + /// [`arboard_has`]), on macOS vector art or a bitmap (by the pasteboard's types), and on the + /// Wayland core protocol copied files, SVG, text or PNG (by the types offered, nothing read). /// arboard has no cheap way to ask for a bitmap (reading one costs as much as pasting it): - /// the paste keys take it, the menu item waits for text. + /// the paste keys take it, the menu item waits for text or copied files. fn has(&mut self, mimes: &[&'static str]) -> bool { #[cfg(target_os = "macos")] if super::mac::has(mimes) { @@ -1455,7 +1550,7 @@ mod portable { if let Backend::Wayland(wl) = cb { return wl.has(mimes); } - mimes.contains(&TEXT) && cb.get_text().is_ok_and(|t| !t.is_empty()) + arboard_has(mimes, cb, Backend::get_text, Backend::file_list) } } @@ -1619,6 +1714,40 @@ mod portable { assert!(Answer::Text(Ok("art.svg".into())).files().is_empty()); } + #[test] + fn paste_is_available_for_files_copied_in_a_file_manager() { + use vectorcraft_engine::cmd::clipboard::{PASTE_ORDER, SVG}; + /// What the clipboard holds, and which reads [`arboard_has`] made. + struct Held { + text: Option, + files: Vec, + reads: Vec, + } + fn has(mimes: &[&'static str], text: Option<&str>, files: &[&str]) -> (bool, Vec) { + let mut held = Held { text: text.map(String::from), files: files.iter().map(PathBuf::from).collect(), reads: vec![] }; + let text = |h: &mut Held| { + h.reads.push(Request::Text); + h.text.clone().ok_or_else(|| "no text".to_string()) + }; + let files = |h: &mut Held| { + h.reads.push(Request::Files); + h.files.clone() + }; + let has = arboard_has(mimes, &mut held, text, files); + (has, held.reads) + } + // Files a file manager copied, with no text: the Paste menu item is available. + assert_eq!(has(&PASTE_ORDER, None, &["/tmp/art.svg"]), (true, vec![Request::Text, Request::Files])); + assert_eq!(has(&PASTE_ORDER, Some(""), &["/tmp/art.svg"]), (true, vec![Request::Text, Request::Files])); + assert_eq!(has(&[SVG], None, &["/tmp/art.svg"]), (true, vec![Request::Files])); + // Text does, and the list is not read. + assert_eq!(has(&PASTE_ORDER, Some("hello"), &[]), (true, vec![Request::Text])); + // An empty list and no text: nothing to paste. + assert_eq!(has(&PASTE_ORDER, None, &[]), (false, vec![Request::Text, Request::Files])); + // A paste of text alone can't take copied files, and their list is not read. + assert_eq!(has(&[TEXT], None, &["/tmp/art.svg"]), (false, vec![Request::Text])); + } + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] #[test] fn arboards_reads_run_on_its_reader_and_wait_by_kind() { @@ -1925,7 +2054,7 @@ mod wayland { use wayland_client::{Connection, Dispatch, Proxy, QueueHandle, WEnum}; use super::loads::{Asker, GONE, LOAD_WAIT, Loads, wait_for_answer}; - use super::{BITMAP, Flavour, MAX_BYTES, PNG, PathBuf, SVG, TEXT, copied_file, gnome_copied_paths, uri_list_paths}; + use super::{BITMAP, Flavour, MAX_BYTES, PNG, PathBuf, SVG, TEXT, copied_file, gnome_copied_paths, takes_files, uri_list_paths}; /// The types text is offered under and read from, best first: `text/plain;charset=utf-8` (GTK /// and Qt apps), `UTF8_STRING` (X11 apps through XWayland) and `text/plain`. @@ -2016,11 +2145,6 @@ mod wayland { Some(first) } - /// Whether a paste of one of `mimes` can take a copied file: one of them is not text. - fn takes_files(mimes: &[&'static str]) -> bool { - mimes.iter().any(|&m| m != TEXT) - } - /// The first type among `offered` that lists copied files ([`FILE_LISTS`]), in any letter case. fn file_list_type(offered: &[String]) -> Option<&str> { FILE_LISTS.iter().find_map(|(list, _)| offered.iter().find(|o| o.eq_ignore_ascii_case(list))).map(String::as_str) @@ -3092,7 +3216,7 @@ mod mac { use objc2_app_kit::NSPasteboard; use objc2_foundation::{NSArray, NSString}; - use super::{Flavour, pasteboard_types}; + use super::{Flavour, MAX_BYTES, copy_within, pasteboard_types}; /// Does the pasteboard hold one of `mimes` ([`pasteboard_types`])? Asks for its types only. pub fn has(mimes: &[&'static str]) -> bool { @@ -3103,13 +3227,16 @@ mod mac { }) } - /// The pasteboard's data for `mime`, the first of its types held ([`pasteboard_types`]). + /// The pasteboard's data for `mime`, the first of its types held ([`pasteboard_types`]) that is + /// not empty and at most [`MAX_BYTES`]: its length is checked before it is copied, and a larger + /// type is skipped and the next tried. pub fn read(mime: &str) -> Option { autoreleasepool(|_| { let pasteboard = NSPasteboard::generalPasteboard(); pasteboard_types(mime).iter().find_map(|&(t, mime)| { - let data = pasteboard.dataForType(&NSString::from_str(t))?.to_vec(); - (!data.is_empty()).then_some(Flavour { mime, data }) + let held = pasteboard.dataForType(&NSString::from_str(t))?; + let data = copy_within(Some(held.len()), MAX_BYTES, || Some(held.to_vec()))?; + Some(Flavour { mime, data }) }) }) } @@ -3296,6 +3423,102 @@ mod tests { assert!(uri_list_paths(list(MAX_URIS + 1).as_bytes()).is_empty()); } + /// A copied file list of more than 1,024 files pastes none, before any file is looked at, + /// wherever the list came from; 1,024 files paste the first that is art. + #[test] + fn a_copied_file_list_longer_than_the_limit_pastes_no_file() { + let d = dir("many"); + let art = d.path().join("art.svg"); + std::fs::write(&art, "").unwrap(); + let missing = |n: usize| (0..n).map(|i| d.path().join(format!("gone{i}.png"))).collect::>(); + let last = [missing(MAX_URIS - 1), vec![art.clone()]].concat(); + assert_eq!(copied_file(last, &PASTE_ORDER).map(|f| f.mime), Some(SVG)); + // The art first: no file is opened past the count. + let first = [vec![art.clone()], missing(MAX_URIS)].concat(); + assert!(copied_file(first, &PASTE_ORDER).is_none()); + assert!(copied_file([missing(MAX_URIS), vec![art]].concat(), &PASTE_ORDER).is_none()); + } + + /// Clipboard data is copied only when the size the clipboard gives is from 1 byte to the limit, + /// and the copy is not asked for otherwise. + #[test] + fn clipboard_data_is_copied_only_when_its_size_fits() { + let copy = |size: Option, got: usize| { + let mut asked = false; + let data = copy_within(size, 8, || { + asked = true; + Some(vec![1; got]) + }); + (data.map(|d| d.len()), asked) + }; + assert_eq!(copy(Some(8), 8), (Some(8), true)); + assert_eq!(copy(Some(1), 1), (Some(1), true)); + for size in [None, Some(0), Some(9), Some(usize::MAX)] { + assert_eq!(copy(size, 1), (None, false), "{size:?}"); + } + // Data that comes to more than the limit after all is refused. + assert_eq!(copy(Some(8), 9), (None, true)); + assert_eq!(MAX_BYTES, 64 << 20); + } + + /// The UTF-8 that UTF-16 text comes to is bounded from the UTF-16 block's size alone, before + /// the text is converted: a block that could pass the limit as UTF-8 is not read. + #[test] + fn text_is_bounded_by_what_its_utf8_could_come_to() { + for text in ["", "a", "\u{20ac}\u{20ac}\u{20ac}", "\u{1f600}", "a\u{20ac}\u{1f600}\u{ffff}"] { + let utf16 = text.encode_utf16().count() * 2; + assert!(utf8_most(utf16) >= text.len(), "{text:?}"); + } + // Every code unit at 3 bytes of UTF-8: the bound is exact. + assert_eq!(utf8_most("\u{20ac}\u{20ac}".encode_utf16().count() * 2), "\u{20ac}\u{20ac}".len()); + let copied = |utf16: usize| copy_within(Some(utf8_most(utf16)), MAX_BYTES, || Some(vec![])).is_some(); + assert!(copied(MAX_BYTES / 3 * 2)); + assert!(!copied(MAX_BYTES / 3 * 2 + 2)); + assert!(!copied(MAX_BYTES)); + assert_eq!(utf8_most(usize::MAX), usize::MAX); + } + + /// A Windows file list (CF_HDROP) of `names`: a DROPFILES header, the names in UTF-16 or one + /// byte a character, each ended by a NUL, and one more NUL. + fn drop_files(names: &[&str], wide: bool) -> Vec { + let mut block = vec![]; + block.extend(20u32.to_le_bytes()); + block.extend([0u8; 12]); + block.extend(u32::from(wide).to_le_bytes()); + for name in names.iter().copied().chain([""]) { + for unit in name.encode_utf16().chain([0]) { + if wide { + block.extend(unit.to_le_bytes()); + } else { + block.push(unit as u8); + } + } + } + block + } + + #[test] + fn a_windows_file_list_is_counted_before_its_names_are_read() { + let names = |n: usize| (0..n).map(|i| format!("C:\\art\\{i}.svg")).collect::>(); + for wide in [true, false] { + let list = |n: usize| drop_files(&names(n).iter().map(String::as_str).collect::>(), wide); + assert!(drop_files_within(&list(MAX_URIS), MAX_URIS), "{wide}"); + assert!(!drop_files_within(&list(MAX_URIS + 1), MAX_URIS), "{wide}"); + assert!(drop_files_within(&list(0), MAX_URIS), "{wide}"); + // Names past the list's closing NUL are not counted. + let mut ended = list(2); + ended.extend(list(MAX_URIS + 1).get(20..).unwrap()); + assert!(drop_files_within(&ended, 2), "{wide}"); + // A list cut short counts the names it holds. + assert!(!drop_files_within(&list(3)[..list(3).len() - 4], 2), "{wide}"); + } + // A header cut short, or names that would start past the block's end. + assert!(!drop_files_within(&drop_files(&["a"], true)[..19], MAX_URIS)); + let mut past = drop_files(&["a"], true); + past[0..4].copy_from_slice(&u32::MAX.to_le_bytes()); + assert!(!drop_files_within(&past, MAX_URIS)); + } + #[test] fn gnome_files_list_names_its_files_after_copy_or_cut() { let paths = |list: &[u8]| gnome_copied_paths(list).into_iter().map(|p| p.to_string_lossy().into_owned()).collect::>(); @@ -3349,19 +3572,48 @@ mod tests { let valid = dib(40, 1, 1, 32, 0, &[], &bgra(&[RED])); let mut captured = Vec::new(); - let read = win::read_dibs(|id| { - captured.push(id); - match id { - CF_DIBV5 => Some(vec![40, 0, 0]), - CF_DIB => Some(valid.clone()), - _ => None, - } - }) + let get = |id: u32| match id { + CF_DIBV5 => Some(vec![40, 0, 0]), + CF_DIB => Some(valid.clone()), + _ => None, + }; + let read = win::read_dibs( + |id| get(id).map(|d| d.len()), + |id| { + captured.push(id); + get(id) + }, + ) .unwrap(); assert_eq!(captured, [CF_DIBV5, CF_DIB]); let flavour = read.flavour().unwrap(); assert_eq!(flavour.mime, PNG); assert_eq!(pixels(&decode_png(&flavour.data).unwrap()), [RED]); + // A bitmap larger than the limit is not copied, and the other one still pastes. + captured.clear(); + let read = win::read_dibs( + |id| if id == CF_DIBV5 { Some(MAX_BYTES + 1) } else { get(id).map(|d| d.len()) }, + |id| { + captured.push(id); + get(id) + }, + ) + .unwrap(); + assert_eq!(captured, [CF_DIB]); + assert_eq!(read.flavour().map(|f| f.mime), Some(PNG)); + // Each format has the limit to itself: a first one at the limit that doesn't decode + // leaves the second to paste. + captured.clear(); + let read = win::read_dibs( + |id| if id == CF_DIBV5 { Some(MAX_BYTES) } else { get(id).map(|d| d.len()) }, + |id| { + captured.push(id); + get(id) + }, + ) + .unwrap(); + assert_eq!(captured, [CF_DIBV5, CF_DIB]); + assert_eq!(read.flavour().map(|f| f.mime), Some(PNG)); } #[test] diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index c55785cfdf..8a892a381a 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -1,7 +1,8 @@ //! VectorCraft desktop app. //! //! Usage: `vectorcraft [--control [--automation-read-root ]... [--automation-write-root ]...] -//! [--in-window-menus] [--new-instance] [--safe-mode] [--] [files…]`, `vectorcraft --version`, `vectorcraft --help` (or `-h`) +//! [--in-window-menus] [--new-instance] [--safe-mode] [--present-mode ] [--frame-latency ] [--] [files…]`, +//! `vectorcraft --version`, `vectorcraft --help` (or `-h`) //! //! Any other argument starting with '-' (not `-` alone) is an error; after `--`, every argument is //! a file. @@ -19,6 +20,9 @@ //! `--automation-write-root` (or `VECTORCRAFT_AUTOMATION_READ_ROOT` / `_WRITE_ROOT`) confine the //! files its requests read and write (`vectorcraft_engine::file_access`); the person at the //! keyboard isn't confined. +//! +//! `--present-mode` and `--frame-latency` (or `VECTORCRAFT_PRESENT_MODE` / `_FRAME_LATENCY`) change +//! how the window's frames reach the display (`presentation`). #![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")] mod automation_args; @@ -59,6 +63,7 @@ mod portal_request; #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd", test))] mod portal_save; mod prefs_dir; +mod presentation; mod printing; #[cfg(not(any(target_os = "macos", windows)))] mod quit_windows; @@ -158,6 +163,14 @@ Options: --safe-mode Start without plug-ins: none loads or runs until VectorCraft starts normally (Help › Safe Mode); the files open in a new window, as with --new-instance + --present-mode How frames reach the display: fifo (vsync), + autovsync (the default; relaxed vsync where the + driver offers it) or novsync + (or VECTORCRAFT_PRESENT_MODE) + --frame-latency Frames the display may queue, 1 to 3 (the default + is 1) (or VECTORCRAFT_FRAME_LATENCY); with either + one set, the files open in a new window, as with + --new-instance --version Print the version and exit -h, --help Print this help and exit -- Treat every argument after it as a file @@ -177,13 +190,16 @@ struct CommandLine { safe_mode: bool, } -/// Reads the arguments after the program name. The automation roots and the control port go into -/// `roots_args` and `control`. `Err` is the exit code when the process ends here: `--version` and -/// `--help` print and succeed; a bad automation option or an unknown option prints an error and fails. +/// Reads the arguments after the program name. The automation roots, the control port and the +/// presentation overrides (with `VECTORCRAFT_PRESENT_MODE` and `VECTORCRAFT_FRAME_LATENCY` filling +/// what the flags leave unset) go into `roots_args`, `control` and `presentation`. `Err` is the exit code +/// when the process ends here: `--version` and `--help` print and succeed; a bad automation or +/// presentation option or an unknown option prints an error and fails. fn read_command_line( mut args: impl Iterator, control: &mut automation_args::ControlArg, roots_args: &mut automation_args::AutomationArgs, + presentation: &mut presentation::Overrides, ) -> Result { let mut files = Vec::new(); let mut in_window_menus = std::env::var_os("VECTORCRAFT_IN_WINDOW_MENUS").is_some_and(|v| !v.is_empty() && v != "0"); @@ -196,7 +212,11 @@ fn read_command_line( files.extend(args.by_ref()); break; } - match roots_args.consume(&a, &mut args).and_then(|root| if root { Ok(true) } else { control.consume(&a, &mut args) }) { + match roots_args + .consume(&a, &mut args) + .and_then(|root| if root { Ok(true) } else { control.consume(&a, &mut args) }) + .and_then(|taken| if taken { Ok(true) } else { presentation.consume(&a, &mut args) }) + { Ok(true) => continue, Ok(false) => {} Err(e) => { @@ -235,6 +255,14 @@ fn read_command_line( eprintln!("vectorcraft: unknown option {a}; see vectorcraft --help, or put -- before a file whose name starts with '-'"); return Err(std::process::ExitCode::FAILURE); } + // After the arguments: the flags, `--version` and `--help` win over a bad environment value. + match presentation.with_env(std::env::var_os("VECTORCRAFT_PRESENT_MODE"), std::env::var_os("VECTORCRAFT_FRAME_LATENCY")) { + Ok(overrides) => *presentation = overrides, + Err(e) => { + eprintln!("vectorcraft: {e}"); + return Err(std::process::ExitCode::FAILURE); + } + } Ok(CommandLine { files, in_window_menus, new_instance, safe_mode }) } @@ -253,8 +281,9 @@ fn main() -> std::process::ExitCode { let root_env = |name: &str| std::env::var_os(name).filter(|v| !v.is_empty()).map(std::path::PathBuf::from); let mut roots_args = automation_args::AutomationArgs::new(root_env("VECTORCRAFT_AUTOMATION_READ_ROOT"), root_env("VECTORCRAFT_AUTOMATION_WRITE_ROOT")); + let mut presentation = presentation::Overrides::default(); let CommandLine { files, in_window_menus, new_instance, safe_mode: safe_mode_flag } = - match read_command_line(std::env::args().skip(1), &mut control, &mut roots_args) { + match read_command_line(std::env::args().skip(1), &mut control, &mut roots_args, &mut presentation) { Ok(command_line) => command_line, Err(code) => return code, }; @@ -275,7 +304,8 @@ fn main() -> std::process::ExitCode { // Files opened from the file manager while VectorCraft runs open in its window (#4892). Before // the log file is attached: a launch that hands its files over leaves the running app's log be. #[cfg(not(target_os = "macos"))] - match single_instance::start(control_port.is_some(), new_instance, safe_mode_flag, &files) { + // A launch that sets the presentation runs as its own app: a running app keeps its own surface. + match single_instance::start(control_port.is_some(), new_instance || presentation.is_set(), safe_mode_flag, &files) { single_instance::Start::Forwarded => return std::process::ExitCode::SUCCESS, single_instance::Start::Running(primary) => single_instance::hold(primary), } @@ -427,7 +457,10 @@ fn main() -> std::process::ExitCode { let mut options = options; // One frame queued, not two: the canvas is rasterized on the CPU and the GPU only // composites it, so the window answers the pointer a frame sooner (#444). - options.wgpu_options.surface = eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY; + // `--present-mode` and `--frame-latency` change it for a launch (`presentation`). + options.wgpu_options.surface = presentation.apply(eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY); + // What the app asks for: the driver picks novsync's mode and may clamp the latency. + log::info!("requested window surface: {}", presentation::describe(&options.wgpu_options.surface, &presentation)); // Only adapters that can show the window, in the order `gpu` gives (#306, #502). if let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup { create.native_adapter_selector = Some(gpu::selector(power, displays, compositor, left_out.adapters.clone(), startup.clone())); @@ -458,6 +491,10 @@ fn main() -> std::process::ExitCode { } options }; + #[cfg(not(feature = "wgpu"))] + if presentation != presentation::Overrides::default() { + log::warn!("--present-mode and --frame-latency set the wgpu renderer's window surface: ignored without it"); + } #[cfg(feature = "wgpu")] gpu::watch_panics(); #[cfg(feature = "wgpu")] @@ -498,6 +535,8 @@ fn main() -> std::process::ExitCode { prefs_dir::attach_plugin_store(&mut session); // File › Scripts lists the scripts of the Scripts folder next to the preferences. prefs_dir::attach_scripts_dir(&mut session); + // File Info's metadata templates live in their own folder next to the preferences. + prefs_dir::attach_metadata_templates_dir(&mut session); prefs_dir::attach_new_doc_profiles(&mut session); let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone())); app.set_startup_update_check(true); diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index 11afcfe121..1a33352ffc 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -65,6 +65,14 @@ pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) { } } +/// Keep File Info's metadata templates in the `Metadata Templates` folder, which a saved template +/// makes. +pub fn attach_metadata_templates_dir(session: &mut vectorcraft_engine::Session) { + if let Some(dir) = store_dir("Metadata Templates") { + session.attach_metadata_templates_dir(dir); + } +} + /// Have File › New start each category's documents from its profile in the `New Document /// Profiles` folder, which `file.newProfiles.edit` makes. pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) { diff --git a/apps/vectorcraft/src/presentation.rs b/apps/vectorcraft/src/presentation.rs new file mode 100644 index 0000000000..3910984c93 --- /dev/null +++ b/apps/vectorcraft/src/presentation.rs @@ -0,0 +1,242 @@ +//! `--present-mode ` (or `VECTORCRAFT_PRESENT_MODE`) and `--frame-latency ` (or +//! `VECTORCRAFT_FRAME_LATENCY`) set how the window's frames reach the display for one launch. The +//! modes are `fifo` (vsync), `autovsync` (the default: wgpu picks relaxed vsync, which tears a late +//! frame, else vsync, by what the driver offers) and `novsync` (wgpu picks Immediate, else Mailbox, +//! else Fifo). A mode the driver may not offer is never requested. The latency is the number of +//! frames the swap chain may queue, 1 to 3. Unset, the app keeps its own surface settings. A flag +//! overrides its variable; a value that isn't one of these stops the app with a message, as +//! `--control` does. A launch that sets either one runs as its own app, as with `--new-instance`. +//! The surface the app asks for is logged at start-up. + +use std::ffi::OsString; + +/// A present mode the command line or the environment can ask for. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + Fifo, + AutoVsync, + NoVsync, +} + +/// The present mode and frame latency this launch asked for (`None`: the app's own setting). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Overrides { + pub mode: Option, + pub latency: Option, +} + +/// A present mode named by `name` (the flag or the variable): `fifo`, `autovsync` or `novsync`, any case. +fn mode(name: &str, value: Option<&str>) -> Result { + let need = format!("{name} needs fifo, autovsync or novsync"); + let Some(v) = value else { return Err(need) }; + match v.trim().to_ascii_lowercase().as_str() { + "fifo" => Ok(Mode::Fifo), + "autovsync" => Ok(Mode::AutoVsync), + "novsync" => Ok(Mode::NoVsync), + _ => Err(format!("{need}, not `{v}`")), + } +} + +/// A frame latency named by `name`: 1, 2 or 3. +fn latency(name: &str, value: Option<&str>) -> Result { + let need = format!("{name} needs 1, 2 or 3 frames"); + let Some(v) = value else { return Err(need) }; + v.trim().parse().ok().filter(|n| (1..=3).contains(n)).ok_or(format!("{need}, not `{v}`")) +} + +/// The value of `--flag ` or `--flag=` when `arg` is that flag; `None` when it isn't. +fn flag_value(flag: &str, arg: &str, args: &mut impl Iterator) -> Option> { + match arg.strip_prefix(flag)? { + "" => Some(args.next()), + rest => rest.strip_prefix('=').map(|v| Some(v.to_owned())), + } +} + +impl Overrides { + /// Whether a flag or a variable set the present mode or the frame latency. + pub fn is_set(&self) -> bool { + *self != Self::default() + } + + /// Returns whether this argument is `--present-mode` or `--frame-latency`. The next argument is + /// its value whatever it is, as with `--control`. + pub fn consume(&mut self, arg: &str, args: &mut impl Iterator) -> Result { + if let Some(value) = flag_value("--present-mode", arg, args) { + if self.mode.is_some() { + return Err("--present-mode given twice".into()); + } + self.mode = Some(mode("--present-mode", value.as_deref())?); + return Ok(true); + } + if let Some(value) = flag_value("--frame-latency", arg, args) { + if self.latency.is_some() { + return Err("--frame-latency given twice".into()); + } + self.latency = Some(latency("--frame-latency", value.as_deref())?); + return Ok(true); + } + Ok(false) + } + + /// Fills what the flags left unset from `VECTORCRAFT_PRESENT_MODE` and `VECTORCRAFT_FRAME_LATENCY`. + /// Unset or empty is no override; a variable is not read when its flag was given. + pub fn with_env(self, mode_var: Option, latency_var: Option) -> Result { + let set = |v: Option| v.filter(|v| !v.is_empty()).map(|v| v.to_string_lossy().into_owned()); + let mode = match (self.mode, set(mode_var)) { + (Some(m), _) => Some(m), + (None, Some(v)) => Some(mode("VECTORCRAFT_PRESENT_MODE", Some(&v))?), + (None, None) => None, + }; + let latency = match (self.latency, set(latency_var)) { + (Some(n), _) => Some(n), + (None, Some(v)) => Some(latency("VECTORCRAFT_FRAME_LATENCY", Some(&v))?), + (None, None) => None, + }; + Ok(Self { mode, latency }) + } + + /// `surface` with the overrides applied. + #[cfg(feature = "wgpu")] + pub fn apply(&self, surface: eframe::egui_wgpu::SurfaceConfig) -> eframe::egui_wgpu::SurfaceConfig { + use eframe::wgpu::PresentMode; + let present_mode = match self.mode { + Some(Mode::Fifo) => PresentMode::Fifo, + Some(Mode::AutoVsync) => PresentMode::AutoVsync, + Some(Mode::NoVsync) => PresentMode::AutoNoVsync, + None => surface.present_mode, + }; + eframe::egui_wgpu::SurfaceConfig { present_mode, desired_maximum_frame_latency: self.latency.or(surface.desired_maximum_frame_latency) } + } +} + +/// The present mode and frame latency `surface` asks for, for the start-up log: +/// "autovsync, frame latency 1", with "(override)" +/// after a value a flag or variable set. +#[cfg(feature = "wgpu")] +pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Overrides) -> String { + use eframe::wgpu::PresentMode; + let mode = match surface.present_mode { + PresentMode::AutoVsync => "autovsync", + PresentMode::AutoNoVsync => "novsync", + PresentMode::Fifo => "fifo", + PresentMode::FifoRelaxed => "fiforelaxed", + PresentMode::Immediate => "immediate", + PresentMode::Mailbox => "mailbox", + }; + let latency = surface.desired_maximum_frame_latency.map_or("default".to_string(), |n| n.to_string()); + let tag = |set: bool| if set { " (override)" } else { "" }; + format!("{mode}{}, frame latency {latency}{}", tag(overrides.mode.is_some()), tag(overrides.latency.is_some())) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(args: &[&str]) -> Result { + let mut overrides = Overrides::default(); + let mut args = args.iter().map(|a| a.to_string()); + while let Some(a) = args.next() { + assert!(overrides.consume(&a, &mut args)?, "{a}"); + } + Ok(overrides) + } + + #[test] + fn flags_take_the_three_modes_and_latencies_from_1_to_3() { + assert_eq!(parse(&[]), Ok(Overrides::default())); + assert_eq!(parse(&["--present-mode", "fifo"]).map(|o| o.mode), Ok(Some(Mode::Fifo))); + assert_eq!(parse(&["--present-mode=AutoVsync"]).map(|o| o.mode), Ok(Some(Mode::AutoVsync))); + assert_eq!(parse(&["--present-mode", " novsync "]).map(|o| o.mode), Ok(Some(Mode::NoVsync))); + for n in 1..=3 { + assert_eq!(parse(&["--frame-latency", &n.to_string()]).map(|o| o.latency), Ok(Some(n))); + } + assert_eq!(parse(&["--frame-latency=2", "--present-mode", "fifo"]), Ok(Overrides { mode: Some(Mode::Fifo), latency: Some(2) })); + } + + #[test] + fn bad_flag_values_are_errors() { + let modes = "--present-mode needs fifo, autovsync or novsync"; + assert_eq!(parse(&["--present-mode"]), Err(modes.into())); + for bad in ["mailbox", "immediate", "vsync", "fast", ""] { + assert_eq!(parse(&["--present-mode", bad]), Err(format!("{modes}, not `{bad}`"))); + assert_eq!(parse(&[&format!("--present-mode={bad}")]), Err(format!("{modes}, not `{bad}`"))); + } + assert_eq!(parse(&["--present-mode", "--frame-latency"]), Err(format!("{modes}, not `--frame-latency`"))); + let frames = "--frame-latency needs 1, 2 or 3 frames"; + assert_eq!(parse(&["--frame-latency"]), Err(frames.into())); + for bad in ["0", "4", "-1", "one", "1.5", "99999999999", ""] { + assert_eq!(parse(&["--frame-latency", bad]), Err(format!("{frames}, not `{bad}`"))); + } + assert_eq!(parse(&["--present-mode", "fifo", "--present-mode=novsync"]), Err("--present-mode given twice".into())); + assert_eq!(parse(&["--frame-latency=1", "--frame-latency", "2"]), Err("--frame-latency given twice".into())); + } + + #[test] + fn other_arguments_are_not_presentation_flags() { + let mut overrides = Overrides::default(); + let mut args = ["fifo".to_owned()].into_iter(); + for other in ["--present-modes", "--present", "--frame-latency-2", "drawing.svg", "--control"] { + assert!(!overrides.consume(other, &mut args).unwrap(), "{other}"); + } + assert_eq!(args.next().as_deref(), Some("fifo")); + assert_eq!(overrides, Overrides::default()); + } + + #[test] + fn variables_fill_what_the_flags_leave_unset_and_bad_values_are_errors() { + let none = Overrides::default(); + assert_eq!(none.with_env(None, None), Ok(none)); + assert_eq!(none.with_env(Some("".into()), Some("".into())), Ok(none)); + assert_eq!(none.with_env(Some("FIFO".into()), Some("2".into())), Ok(Overrides { mode: Some(Mode::Fifo), latency: Some(2) })); + assert_eq!( + none.with_env(Some("mailbox".into()), None), + Err("VECTORCRAFT_PRESENT_MODE needs fifo, autovsync or novsync, not `mailbox`".into()) + ); + assert_eq!(none.with_env(None, Some("0".into())), Err("VECTORCRAFT_FRAME_LATENCY needs 1, 2 or 3 frames, not `0`".into())); + // A flag wins, and its variable is not read, so a bad value there doesn't stop the app. + let flags = Overrides { mode: Some(Mode::NoVsync), latency: Some(3) }; + assert_eq!(flags.with_env(Some("bad".into()), Some("9".into())), Ok(flags)); + let mode_only = Overrides { mode: Some(Mode::AutoVsync), latency: None }; + assert_eq!(mode_only.with_env(Some("bad".into()), Some("1".into())), Ok(Overrides { mode: Some(Mode::AutoVsync), latency: Some(1) })); + // Either value set makes the launch run as its own app. + assert!(!none.is_set()); + assert!(mode_only.is_set()); + assert!(Overrides { mode: None, latency: Some(1) }.is_set()); + } + + /// `--help` states the app's own surface as the default, so it changes with it. + #[cfg(feature = "wgpu")] + #[test] + fn the_usage_names_the_app_surface_as_the_default() { + let app = eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY; + let usage = crate::USAGE.split_whitespace().collect::>().join(" "); + assert_eq!(app.present_mode, eframe::wgpu::PresentMode::AutoVsync, "the usage calls autovsync the default"); + assert!(usage.contains("autovsync (the default"), "{usage}"); + let Some(frames) = app.desired_maximum_frame_latency else { panic!("the usage gives a default frame latency") }; + assert!(usage.contains(&format!("(the default is {frames})")), "{usage}"); + } + + #[cfg(feature = "wgpu")] + #[test] + fn overrides_change_only_what_they_set_on_the_app_surface() { + use eframe::egui_wgpu::SurfaceConfig; + use eframe::wgpu::PresentMode; + let app = SurfaceConfig::LOW_LATENCY; + // No override: the surface the app asks for is unchanged. + assert_eq!(Overrides::default().apply(app), app); + let latency = Overrides { mode: None, latency: Some(2) }; + let s = latency.apply(app); + assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoVsync, Some(2))); + assert_eq!(describe(&s, &latency), "autovsync, frame latency 2 (override)"); + let fifo = Overrides { mode: Some(Mode::Fifo), latency: None }; + let s = fifo.apply(app); + assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::Fifo, app.desired_maximum_frame_latency)); + // Never a mode the driver may lack: no vsync lets wgpu fall back by support. + let novsync = Overrides { mode: Some(Mode::NoVsync), latency: Some(3) }; + let s = novsync.apply(app); + assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoNoVsync, Some(3))); + assert_eq!(describe(&s, &novsync), "novsync (override), frame latency 3 (override)"); + let unset = SurfaceConfig { present_mode: PresentMode::Fifo, desired_maximum_frame_latency: None }; + assert_eq!(describe(&unset, &Overrides::default()), "fifo, frame latency default"); + } +} diff --git a/apps/vectorcraft/tests/it/help.rs b/apps/vectorcraft/tests/it/help.rs index d82475b9ff..5f53f920b4 100644 --- a/apps/vectorcraft/tests/it/help.rs +++ b/apps/vectorcraft/tests/it/help.rs @@ -52,7 +52,17 @@ fn prints_usage(args: &[&str], env: &[(&str, &str)]) { assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr)); assert!(out.stderr.is_empty(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr)); assert!(stdout.starts_with("Usage: vectorcraft "), "{args:?}: {stdout}"); - for flag in ["--control", "--automation-read-root", "--automation-write-root", "--in-window-menus", "--safe-mode", "--version", "--help"] { + for flag in [ + "--control", + "--automation-read-root", + "--automation-write-root", + "--in-window-menus", + "--safe-mode", + "--present-mode", + "--frame-latency", + "--version", + "--help", + ] { assert!(stdout.contains(flag), "{args:?}: usage doesn't mention {flag}: {stdout}"); } // Headless work is the CLI's: the usage says where to go. @@ -73,6 +83,32 @@ fn help_wins_over_a_bad_control_port_variable() { prints_usage(&["--help"], &[("VECTORCRAFT_CONTROL_PORT", "abc")]); } +/// A bad presentation variable stops the app with a message before it starts; `--help` and the +/// matching flag win over it. A run that gets past it stops at the control port `run` makes fail. +#[test] +fn a_bad_presentation_variable_is_an_error_unless_help_or_its_flag_is_given() { + for (var, value, need) in [ + ("VECTORCRAFT_FRAME_LATENCY", "0", "needs 1, 2 or 3 frames, not `0`"), + ("VECTORCRAFT_PRESENT_MODE", "mailbox", "needs fifo, autovsync or novsync, not `mailbox`"), + ] { + let out = run(&[], &[(var, value)]); + assert!(!out.status.success(), "{var}"); + assert_eq!(String::from_utf8(out.stderr).unwrap(), format!("vectorcraft: {var} {need}\n")); + prints_usage(&["--help"], &[(var, value)]); + } + for (args, env) in [ + (&["--frame-latency", "2"][..], ("VECTORCRAFT_FRAME_LATENCY", "0")), + (&["--present-mode=fifo"], ("VECTORCRAFT_PRESENT_MODE", "mailbox")), + (&[], ("VECTORCRAFT_FRAME_LATENCY", "3")), + ] { + let stderr = String::from_utf8(run(args, &[env]).stderr).unwrap(); + assert!(stderr.contains("VECTORCRAFT_CONTROL_PORT") && !stderr.contains(env.0), "{args:?}: {stderr}"); + } + let out = run(&["--frame-latency", "4"], &[]); + assert!(!out.status.success()); + assert_eq!(String::from_utf8(out.stderr).unwrap(), "vectorcraft: --frame-latency needs 1, 2 or 3 frames, not `4`\n"); +} + /// An option the app doesn't know (a typo of `--safe-mode`) is an error, not a file to open with /// plug-ins; a later `--help` still wins. #[test] 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 e529e1d4e2..f2f9158730 100644 --- a/crates/cad/Cargo.toml +++ b/crates/cad/Cargo.toml @@ -3,7 +3,7 @@ name = "vectorcraft-cad" version.workspace = true edition.workspace = true license.workspace = true -description = "VectorCraft CAD interchange: a hand-written ASCII DXF writer (R12 to 2018) and an HP-GL/2 plot file reader and writer" +description = "VectorCraft CAD interchange: DXF export through craft-dxf and an HP-GL/2 plot file reader and writer" [lints] workspace = true @@ -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/lib.rs b/crates/cad/src/lib.rs index bb752267aa..eafb4616f1 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -1,4 +1,4 @@ -//! CAD interchange: a hand-written ASCII DXF writer (versions R12 to 2018) and a reader on +//! CAD interchange: a DXF writer (versions R12 to 2018) on `craft_dxf::drawing` and a reader on //! `craft_dxf::model`, and an HP-GL/2 plot file reader and writer. //! //! [`export`] writes the visible art of a document into one DXF drawing: each layer becomes a DXF @@ -15,7 +15,7 @@ //! [`hpgl::import`] reads an HP-GL plotter file, and [`hpgl::export`] writes one: see [`hpgl`]. //! //! - `aci`: the 256-colour index palette and the nearest index of a colour. -//! - `writer`: group codes, handles and the file's sections, tables and objects. +//! - The ASCII file around those entities is written by `craft_dxf::drawing`. //! - `scene`: the document walk that turns objects into entities. //! - `import`: the reader, entities to art, blocks to symbols. //! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves. @@ -24,7 +24,6 @@ mod aci; pub mod hpgl; pub mod import; mod scene; -mod writer; use vectorcraft_doc::{Document, Unit}; use vectorcraft_geom::Rect; @@ -136,11 +135,27 @@ impl DxfVersion { self >= Self::R2004 } /// Text is UTF-8 (earlier versions escape what isn't ASCII as `\U+XXXX`). - fn utf8(self) -> bool { + pub fn utf8(self) -> bool { self >= Self::R2007 } } +impl From for craft_dxf::drawing::Format { + fn from(v: DxfVersion) -> Self { + match v { + DxfVersion::R12 => Self::R12, + DxfVersion::R13 => Self::R13, + DxfVersion::R14 => Self::R14, + DxfVersion::R2000 => Self::R2000, + DxfVersion::R2004 => Self::R2004, + DxfVersion::R2007 => Self::R2007, + DxfVersion::R2010 => Self::R2010, + DxfVersion::R2013 => Self::R2013, + DxfVersion::R2018 => Self::R2018, + } + } +} + /// How many colours entities may use: indexed colours of the 256-colour palette, or true colour /// (with the nearest index for apps that read only the index). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -429,8 +444,8 @@ pub fn export(doc: &Document, opts: &DxfOptions) -> Result { return Err("the export region is not finite".into()); } // Symbols' art is placed without clipping, as the scene places it. - let baked = - vectorcraft_effects::bake_document_placing_symbols(doc, false, vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true }); + let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, false, layers); let doc = baked.as_ref().unwrap_or(doc); Ok(scene::Scene::new(doc, opts).run()) } diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs index ea3c962053..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; @@ -14,8 +13,8 @@ use vectorcraft_effects::stroke; use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Vec2}; use crate::aci::nearest_aci; -use crate::writer::{Codes, Drawing, EntityStyle, Handle, ImageDef, Layer, LineType, fixed}; use crate::{CAP_HEIGHT, ColorDepth, DxfImage, DxfOptions, DxfOutput, MAX_NEST, Preserve, RasterFormat}; +use craft_dxf::drawing::{Codes, Drawing, EntityStyle, Handle, ImageDef, Layer, LineType, STANDARD_STYLE, fixed}; /// Curves are flattened to within this distance (points) where DXF needs straight segments /// (hatch boundaries, R12 polylines). @@ -543,7 +542,7 @@ impl<'a> Scene<'a> { o, to_dxf: Affine::new([k, 0.0, 0.0, -k, -r.x0 * k, r.y1 * k]), k, - e: Codes::new(o.version), + e: Codes::new(o.version.into()), next: fixed::FIRST_FREE, layers: vec![], layer_names: Names::with(&["0", "Defpoints"]), @@ -551,7 +550,7 @@ impl<'a> Scene<'a> { flags: LayerFlags { off: false, locked: false, plot: true }, linetypes: vec![], styles: vec![], - style_names: Names::with(&[crate::writer::STANDARD_STYLE]), + style_names: Names::with(&[STANDARD_STYLE]), images: vec![], files: vec![], by_key: HashMap::new(), @@ -579,7 +578,7 @@ impl<'a> Scene<'a> { let one = (self.o.scale - 1.0).abs() < 1e-12; let insunits = if one { crate::insunits_code(self.o.unit).unwrap_or(0) } else { 0 }; let drawing = Drawing { - version: self.o.version, + version: self.o.version.into(), layers: self.layers, linetypes: self.linetypes, styles: self.styles, @@ -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 84e547709d..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(), @@ -1451,3 +1473,23 @@ fn symbols_fanning_out_into_empty_symbols_stop_at_the_symbol_budget() { assert!(entities(&out).is_empty()); assert!(out.warnings.iter().any(|w| w.contains("symbols placed inside symbols")), "{:?}", out.warnings); } + +#[test] +fn export_bytes_match_shared_writer_goldens() { + use std::path::PathBuf; + let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data"); + let cases: [(&str, DxfVersion, Document); 2] = + [("shapes_r12.dxf", DxfVersion::R12, shapes_doc()), ("shapes_r2018.dxf", DxfVersion::R2018, shapes_doc())]; + for (name, version, doc) in cases { + let out = export(&doc, &DxfOptions { version, ..opts(&doc) }).unwrap(); + let got = std::str::from_utf8(&out.bytes).expect("UTF-8 DXF"); + let path = dir.join(name); + if std::env::var_os("WRITE_DXF_GOLDENS").is_some() { + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(&path, got).unwrap(); + continue; + } + let expected = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display())); + assert_eq!(got, expected, "DXF bytes changed versus {}", path.display()); + } +} diff --git a/crates/cad/src/writer.rs b/crates/cad/src/writer.rs deleted file mode 100644 index 6ba7e5a35d..0000000000 --- a/crates/cad/src/writer.rs +++ /dev/null @@ -1,674 +0,0 @@ -//! The ASCII DXF file: group codes, handles, and the sections, tables and objects around the -//! entities. DXF R13 and later give every object a handle and subclass markers; R2000 and later -//! add layouts and plot styles, which CAD apps expect to find. - -use std::fmt::Write as _; - -use crate::DxfVersion; - -/// An object handle (written in hex). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct Handle(pub u32); - -/// The handles of the fixed objects every drawing has. Entities and table entries count up from -/// [`FIRST_FREE`]. -pub(crate) mod fixed { - use super::Handle; - pub const LAYER_TABLE: Handle = Handle(0x1); - pub const LTYPE_TABLE: Handle = Handle(0x2); - pub const APPID_TABLE: Handle = Handle(0x3); - pub const DIMSTYLE_TABLE: Handle = Handle(0x4); - pub const STYLE_TABLE: Handle = Handle(0x5); - pub const UCS_TABLE: Handle = Handle(0x6); - pub const VIEW_TABLE: Handle = Handle(0x7); - pub const VPORT_TABLE: Handle = Handle(0x8); - pub const BLOCK_RECORD_TABLE: Handle = Handle(0x9); - pub const ROOT: Handle = Handle(0xA); - pub const GROUPS: Handle = Handle(0xB); - pub const LAYOUTS: Handle = Handle(0xC); - pub const MODEL_RECORD: Handle = Handle(0xD); - pub const PAPER_RECORD: Handle = Handle(0xE); - pub const MODEL_BLOCK: Handle = Handle(0xF); - pub const MODEL_END: Handle = Handle(0x10); - pub const PAPER_BLOCK: Handle = Handle(0x11); - pub const PAPER_END: Handle = Handle(0x12); - pub const MODEL_LAYOUT: Handle = Handle(0x13); - pub const PAPER_LAYOUT: Handle = Handle(0x14); - pub const ACTIVE_VPORT: Handle = Handle(0x15); - pub const ACAD_APPID: Handle = Handle(0x16); - pub const STANDARD_DIMSTYLE: Handle = Handle(0x17); - pub const IMAGE_DICT: Handle = Handle(0x18); - pub const IMAGE_VARS: Handle = Handle(0x19); - pub const PLOT_STYLES: Handle = Handle(0x1A); - pub const PLOT_NORMAL: Handle = Handle(0x1B); - pub const FIRST_FREE: u32 = 0x30; -} - -/// A number as DXF writes it: up to 6 decimals, no trailing zeros, 0 for anything not finite. -pub(crate) fn num(v: f64) -> String { - if !v.is_finite() { - return "0".into(); - } - let s = format!("{v:.6}"); - let s = s.trim_end_matches('0').trim_end_matches('.'); - if s == "-0" || s.is_empty() { "0".into() } else { s.into() } -} - -/// Text as a DXF string value: one line, `^` escaped, and before DXF 2007 (which reads UTF-8) -/// every character outside ASCII as `\U+XXXX`. -pub(crate) fn text(s: &str, utf8: bool) -> String { - let mut out = String::with_capacity(s.len()); - for c in s.chars() { - match c { - '\r' | '\n' | '\t' => out.push(' '), - c if c.is_control() => {} - '^' => out.push_str("^ "), - c if !utf8 && !c.is_ascii() => match u16::try_from(u32::from(c)) { - Ok(u) => _ = write!(out, "\\U+{u:04X}"), - Err(_) => out.push('?'), - }, - c => out.push(c), - } - } - out -} - -/// Group-code/value pairs in the order they are written. -pub(crate) struct Codes { - pub v: DxfVersion, - out: String, -} - -impl Codes { - pub fn new(v: DxfVersion) -> Self { - Self { v, out: String::new() } - } - - pub fn into_string(self) -> String { - self.out - } - - pub fn append(&mut self, other: &str) { - self.out.push_str(other); - } - - /// A value written as it is (names and keywords the writer itself chose). - pub fn raw(&mut self, code: u16, value: &str) { - _ = writeln!(self.out, "{code:>3}\n{value}"); - } - - /// Text from the document, encoded for the version (see [`text`]). - pub fn str(&mut self, code: u16, value: &str) { - let t = text(value, self.v.utf8()); - self.raw(code, &t); - } - - pub fn int(&mut self, code: u16, value: i64) { - _ = writeln!(self.out, "{code:>3}\n{value}"); - } - - pub fn num(&mut self, code: u16, value: f64) { - _ = writeln!(self.out, "{code:>3}\n{}", num(value)); - } - - pub fn handle(&mut self, code: u16, h: Handle) { - _ = writeln!(self.out, "{code:>3}\n{:X}", h.0); - } - - /// A 2D point at `code` (x), `code + 10` (y). - pub fn xy(&mut self, code: u16, x: f64, y: f64) { - self.num(code, x); - self.num(code + 10, y); - } - - /// A 3D point at `code`, `code + 10`, `code + 20` (z = 0). - pub fn xyz(&mut self, code: u16, x: f64, y: f64) { - self.xy(code, x, y); - self.num(code + 20, 0.0); - } - - /// The extrusion direction of planar entities: the z axis. - pub fn normal(&mut self) { - self.num(210, 0.0); - self.num(220, 0.0); - self.num(230, 1.0); - } - - /// The start of an object: its type, and from R13 its handle, owner and first subclass. - fn object(&mut self, kind: &str, h: Handle, owner: Handle, subclass: &str) { - self.raw(0, kind); - if self.v.handles() { - self.handle(if kind == "DIMSTYLE" { 105 } else { 5 }, h); - self.handle(330, owner); - self.raw(100, subclass); - } - } - - /// A table entry: the shared record subclass, then the table's own (from R13). - fn record(&mut self, kind: &str, h: Handle, table: Handle, subclass: &str) { - self.object(kind, h, table, "AcDbSymbolTableRecord"); - if self.v.handles() { - self.raw(100, subclass); - } - } - - fn section(&mut self, name: &str) { - self.raw(0, "SECTION"); - self.raw(2, name); - } - - fn end_section(&mut self) { - self.raw(0, "ENDSEC"); - } - - fn table(&mut self, name: &str, h: Handle, count: usize) { - self.raw(0, "TABLE"); - self.raw(2, name); - if self.v.handles() { - self.handle(5, h); - self.raw(330, "0"); - self.raw(100, "AcDbSymbolTable"); - } - self.int(70, count as i64); - if name == "DIMSTYLE" && self.v.r2000() { - self.raw(100, "AcDbDimStyleTable"); - } - } - - fn end_table(&mut self) { - self.raw(0, "ENDTAB"); - } -} - -/// How an entity is drawn: its colour index, true colour, lineweight, linetype and transparency. -#[derive(Clone, Debug, Default)] -pub(crate) struct EntityStyle { - pub aci: u8, - /// `0xRRGGBB` (DXF 2004 and later). - pub rgb: Option, - /// Hundredths of a millimetre (DXF 2000 and later). - pub lineweight: Option, - pub linetype: Option, - /// Opacity 0–255 (DXF 2004 and later; opaque is left out). - pub alpha: Option, -} - -impl Codes { - /// The start of an entity of `kind` owned by `owner` (model space, or a polyline for its - /// vertices) on `layer` with its style, ending with `subclass` (none when empty). - pub fn entity(&mut self, kind: &str, h: Handle, owner: Handle, layer: &str, style: &EntityStyle, subclass: &str) { - self.object(kind, h, owner, "AcDbEntity"); - self.str(8, layer); - if let Some(lt) = &style.linetype { - self.str(6, lt); - } - self.int(62, i64::from(style.aci.max(1))); - if self.v.r2000() - && let Some(lw) = style.lineweight - { - self.int(370, i64::from(lw)); - } - if self.v.true_color() { - if let Some(rgb) = style.rgb { - self.int(420, i64::from(rgb)); - } - if let Some(a) = style.alpha { - self.int(440, 0x0200_0000 | i64::from(a)); - } - } - if self.v.handles() && !subclass.is_empty() { - self.raw(100, subclass); - } - } -} - -/// A DXF layer. -#[derive(Clone, Debug)] -pub(crate) struct Layer { - pub name: String, - pub aci: u8, - /// Switched off (a hidden layer). - pub off: bool, - pub locked: bool, - /// Plotted (printable). - pub plot: bool, -} - -/// A dash pattern: dash, gap, dash… lengths in drawing units. -#[derive(Clone, Debug)] -pub(crate) struct LineType { - pub name: String, - pub pattern: Vec, -} - -/// A placed image file and the image entities that show it. -#[derive(Clone, Debug)] -pub(crate) struct ImageDef { - pub name: String, - pub size: (u32, u32), - pub handle: Handle, - /// `(reactor, image entity)` per image entity. - pub reactors: Vec<(Handle, Handle)>, -} - -/// Everything around the entities, collected while they were written. -pub(crate) struct Drawing { - pub version: DxfVersion, - pub layers: Vec, - pub linetypes: Vec, - /// Text styles: (style name, font family). - pub styles: Vec<(String, String)>, - pub images: Vec, - /// The entities' group codes. - pub entities: String, - /// `[x0, y0, x1, y1]` of everything written (drawing units). - pub extents: [f64; 4], - /// The export region (drawing units). - pub limits: [f64; 4], - /// `$INSUNITS`. - pub insunits: u8, - pub metric: bool, - /// The next free handle. - pub next: u32, -} - -/// The text style every drawing has. -pub(crate) const STANDARD_STYLE: &str = "Standard"; - -impl Drawing { - /// The whole file. - pub fn write(self) -> String { - let v = self.version; - let mut c = Codes::new(v); - // Table entries get the handles after the entities'. - let mut next = self.next; - let mut take = |n: usize| { - let start = next; - next = next.saturating_add(u32::try_from(n).unwrap_or(u32::MAX)); - start - }; - let ltype_base = take(3 + self.linetypes.len()); - let layer_base = take(1 + self.layers.len()); - let style_base = take(1 + self.styles.len()); - self.header(&mut c, next); - if v.handles() { - self.classes(&mut c); - } - c.section("TABLES"); - self.vport(&mut c); - self.ltypes(&mut c, ltype_base); - self.layer_table(&mut c, layer_base); - self.style_table(&mut c, style_base); - if v.handles() { - for (name, h) in [("VIEW", fixed::VIEW_TABLE), ("UCS", fixed::UCS_TABLE)] { - c.table(name, h, 0); - c.end_table(); - } - c.table("APPID", fixed::APPID_TABLE, 1); - c.record("APPID", fixed::ACAD_APPID, fixed::APPID_TABLE, "AcDbRegAppTableRecord"); - c.raw(2, "ACAD"); - c.int(70, 0); - c.end_table(); - c.table("DIMSTYLE", fixed::DIMSTYLE_TABLE, 1); - c.record("DIMSTYLE", fixed::STANDARD_DIMSTYLE, fixed::DIMSTYLE_TABLE, "AcDbDimStyleTableRecord"); - c.raw(2, "Standard"); - c.int(70, 0); - c.end_table(); - c.table("BLOCK_RECORD", fixed::BLOCK_RECORD_TABLE, 2); - for (name, h, layout) in - [("*Model_Space", fixed::MODEL_RECORD, fixed::MODEL_LAYOUT), ("*Paper_Space", fixed::PAPER_RECORD, fixed::PAPER_LAYOUT)] - { - c.record("BLOCK_RECORD", h, fixed::BLOCK_RECORD_TABLE, "AcDbBlockTableRecord"); - c.raw(2, name); - if v.r2000() { - c.handle(340, layout); - c.int(70, 0); - c.int(280, 1); - c.int(281, 0); - } - } - c.end_table(); - } - c.end_section(); - if v.handles() { - c.section("BLOCKS"); - for (name, record, begin, end) in [ - ("*Model_Space", fixed::MODEL_RECORD, fixed::MODEL_BLOCK, fixed::MODEL_END), - ("*Paper_Space", fixed::PAPER_RECORD, fixed::PAPER_BLOCK, fixed::PAPER_END), - ] { - c.object("BLOCK", begin, record, "AcDbEntity"); - c.raw(8, "0"); - c.raw(100, "AcDbBlockBegin"); - c.raw(2, name); - c.int(70, 0); - c.xyz(10, 0.0, 0.0); - c.raw(3, name); - c.raw(1, ""); - c.object("ENDBLK", end, record, "AcDbEntity"); - c.raw(8, "0"); - c.raw(100, "AcDbBlockEnd"); - } - c.end_section(); - } - c.section("ENTITIES"); - c.append(&self.entities); - c.end_section(); - if v.handles() { - self.objects(&mut c); - } - c.raw(0, "EOF"); - c.into_string() - } - - fn header(&self, c: &mut Codes, handseed: u32) { - let v = self.version; - let var = |c: &mut Codes, name: &str| c.raw(9, name); - c.section("HEADER"); - var(c, "$ACADVER"); - c.raw(1, v.acadver()); - var(c, "$DWGCODEPAGE"); - c.raw(3, "ANSI_1252"); - var(c, "$INSBASE"); - c.xyz(10, 0.0, 0.0); - let [x0, y0, x1, y1] = self.extents; - var(c, "$EXTMIN"); - c.xyz(10, x0, y0); - var(c, "$EXTMAX"); - c.xyz(10, x1, y1); - let [lx0, ly0, lx1, ly1] = self.limits; - var(c, "$LIMMIN"); - c.xy(10, lx0, ly0); - var(c, "$LIMMAX"); - c.xy(10, lx1, ly1); - if v.r2000() { - var(c, "$LWDISPLAY"); - c.int(290, 1); - var(c, "$INSUNITS"); - c.int(70, i64::from(self.insunits)); - var(c, "$MEASUREMENT"); - c.int(70, i64::from(self.metric)); - } - if v.handles() { - var(c, "$HANDSEED"); - c.handle(5, Handle(handseed)); - } - c.end_section(); - } - - fn classes(&self, c: &mut Codes) { - let mut classes: Vec<(&str, &str, &str, i64, bool)> = vec![]; - if self.version.r2000() { - classes.extend([ - ("ACDBDICTIONARYWDFLT", "AcDbDictionaryWithDefault", "ObjectDBX Classes", 0, false), - ("ACDBPLACEHOLDER", "AcDbPlaceHolder", "ObjectDBX Classes", 0, false), - ("LAYOUT", "AcDbLayout", "ObjectDBX Classes", 0, false), - ]); - } - if !self.images.is_empty() { - classes.extend([ - ("RASTERVARIABLES", "AcDbRasterVariables", "ISM", 0, false), - ("IMAGE", "AcDbRasterImage", "ISM", 2175, true), - ("IMAGEDEF", "AcDbRasterImageDef", "ISM", 0, false), - ("IMAGEDEF_REACTOR", "AcDbRasterImageDefReactor", "ISM", 1, false), - ]); - } - c.section("CLASSES"); - for (name, cpp, app, flags, entity) in classes { - c.raw(0, "CLASS"); - c.raw(1, name); - c.raw(2, cpp); - c.raw(3, app); - c.int(90, flags); - if self.version.true_color() { - c.int(91, 0); - } - c.int(280, 0); - c.int(281, i64::from(entity)); - } - c.end_section(); - } - - /// The active viewport, zoomed to the drawing's extents. - fn vport(&self, c: &mut Codes) { - let [x0, y0, x1, y1] = self.extents; - c.table("VPORT", fixed::VPORT_TABLE, 1); - c.record("VPORT", fixed::ACTIVE_VPORT, fixed::VPORT_TABLE, "AcDbViewportTableRecord"); - c.raw(2, if self.version.handles() { "*Active" } else { "*ACTIVE" }); - c.int(70, 0); - c.xy(10, 0.0, 0.0); - c.xy(11, 1.0, 1.0); - c.xy(12, (x0 + x1) / 2.0, (y0 + y1) / 2.0); - c.xy(13, 0.0, 0.0); - c.xy(14, 1.0, 1.0); - c.xy(15, 10.0, 10.0); - // The view direction looks down the z axis: (0, 0, 1), each code once. - c.xy(16, 0.0, 0.0); - c.num(36, 1.0); - c.xyz(17, 0.0, 0.0); - let (w, h) = ((x1 - x0).abs(), (y1 - y0).abs()); - // The view's height, with a margin; its width follows from the aspect ratio. - c.num(40, (h.max(w / 1.5) * 1.1).max(1.0)); - c.num(41, 1.5); - c.num(42, 50.0); - c.num(43, 0.0); - c.num(44, 0.0); - c.num(50, 0.0); - c.num(51, 0.0); - for (code, value) in [(71, 0), (72, 1000), (73, 1), (74, 3), (75, 0), (76, 0), (77, 0), (78, 0)] { - c.int(code, value); - } - if self.version.r2000() { - c.int(281, 0); - c.int(65, 0); - c.num(146, 0.0); - } - c.end_table(); - } - - fn ltypes(&self, c: &mut Codes, base: u32) { - c.table("LTYPE", fixed::LTYPE_TABLE, 3 + self.linetypes.len()); - let solid = [("ByBlock", ""), ("ByLayer", ""), ("Continuous", "Solid line")]; - let rows = solid.iter().map(|(n, d)| (*n, *d, &[][..])).chain(self.linetypes.iter().map(|l| (l.name.as_str(), "", l.pattern.as_slice()))); - for (i, (name, desc, pattern)) in rows.enumerate() { - c.record("LTYPE", Handle(base.saturating_add(i as u32)), fixed::LTYPE_TABLE, "AcDbLinetypeTableRecord"); - c.str(2, name); - c.int(70, 0); - c.str(3, if pattern.is_empty() { desc } else { "Dashed" }); - c.int(72, 65); - c.int(73, pattern.len() as i64); - c.num(40, pattern.iter().map(|v| v.abs()).sum()); - for v in pattern { - c.num(49, *v); - if self.version.handles() { - c.int(74, 0); - } - } - } - c.end_table(); - } - - fn layer_table(&self, c: &mut Codes, base: u32) { - let zero = Layer { name: "0".into(), aci: 7, off: false, locked: false, plot: true }; - c.table("LAYER", fixed::LAYER_TABLE, 1 + self.layers.len()); - for (i, l) in std::iter::once(&zero).chain(&self.layers).enumerate() { - c.record("LAYER", Handle(base.saturating_add(i as u32)), fixed::LAYER_TABLE, "AcDbLayerTableRecord"); - c.str(2, &l.name); - c.int(70, if l.locked { 4 } else { 0 }); - // A negative colour switches the layer off. - let aci = i64::from(l.aci.max(1)); - c.int(62, if l.off { -aci } else { aci }); - c.raw(6, "Continuous"); - if self.version.r2000() { - c.int(290, i64::from(l.plot)); - c.int(370, -3); - c.handle(390, fixed::PLOT_NORMAL); - } - } - c.end_table(); - } - - fn style_table(&self, c: &mut Codes, base: u32) { - c.table("STYLE", fixed::STYLE_TABLE, 1 + self.styles.len()); - let standard = (STANDARD_STYLE.to_string(), String::new()); - for (i, (name, family)) in std::iter::once(&standard).chain(&self.styles).enumerate() { - c.record("STYLE", Handle(base.saturating_add(i as u32)), fixed::STYLE_TABLE, "AcDbTextStyleTableRecord"); - c.str(2, name); - c.int(70, 0); - c.num(40, 0.0); - c.num(41, 1.0); - c.num(50, 0.0); - c.int(71, 0); - c.num(42, 2.5); - // The font file; from 2000 the family name too, which is how CAD apps find a TrueType font. - if family.is_empty() { - c.raw(3, "txt"); - } else { - c.str(3, &format!("{family}.ttf")); - } - c.raw(4, ""); - if self.version.r2000() && !family.is_empty() { - c.raw(1001, "ACAD"); - c.str(1000, family); - c.int(1071, 0); - } - } - c.end_table(); - } - - fn objects(&self, c: &mut Codes) { - let v = self.version; - let images = !self.images.is_empty(); - c.section("OBJECTS"); - let dict = |c: &mut Codes, h: Handle, owner: Handle, entries: &[(&str, Handle)]| { - c.object("DICTIONARY", h, owner, "AcDbDictionary"); - c.int(281, 1); - for (name, e) in entries { - c.str(3, name); - c.handle(350, *e); - } - }; - let mut root = vec![("ACAD_GROUP", fixed::GROUPS)]; - if images { - root.extend([("ACAD_IMAGE_DICT", fixed::IMAGE_DICT), ("ACAD_IMAGE_VARS", fixed::IMAGE_VARS)]); - } - if v.r2000() { - root.extend([("ACAD_LAYOUT", fixed::LAYOUTS), ("ACAD_PLOTSTYLENAME", fixed::PLOT_STYLES)]); - } - dict(c, fixed::ROOT, Handle(0), &root); - dict(c, fixed::GROUPS, fixed::ROOT, &[]); - if v.r2000() { - dict(c, fixed::LAYOUTS, fixed::ROOT, &[("Layout1", fixed::PAPER_LAYOUT), ("Model", fixed::MODEL_LAYOUT)]); - c.object("ACDBDICTIONARYWDFLT", fixed::PLOT_STYLES, fixed::ROOT, "AcDbDictionary"); - c.int(281, 1); - c.raw(3, "Normal"); - c.handle(350, fixed::PLOT_NORMAL); - c.raw(100, "AcDbDictionaryWithDefault"); - c.handle(340, fixed::PLOT_NORMAL); - // A placeholder has no data and no subclass marker of its own. - c.raw(0, "ACDBPLACEHOLDER"); - c.handle(5, fixed::PLOT_NORMAL); - c.handle(330, fixed::PLOT_STYLES); - self.layout(c, fixed::MODEL_LAYOUT, "Model", 0, fixed::MODEL_RECORD); - self.layout(c, fixed::PAPER_LAYOUT, "Layout1", 1, fixed::PAPER_RECORD); - } - if images { - c.object("RASTERVARIABLES", fixed::IMAGE_VARS, fixed::ROOT, "AcDbRasterVariables"); - c.int(90, 0); - c.int(70, 0); - c.int(71, 1); - c.int(72, 0); - let entries: Vec<(&str, Handle)> = self.images.iter().map(|i| (i.name.as_str(), i.handle)).collect(); - dict(c, fixed::IMAGE_DICT, fixed::ROOT, &entries); - for img in &self.images { - c.raw(0, "IMAGEDEF"); - c.handle(5, img.handle); - c.raw(102, "{ACAD_REACTORS"); - c.handle(330, fixed::IMAGE_DICT); - for (reactor, _) in &img.reactors { - c.handle(330, *reactor); - } - c.raw(102, "}"); - c.handle(330, fixed::IMAGE_DICT); - c.raw(100, "AcDbRasterImageDef"); - c.int(90, 0); - c.str(1, &img.name); - c.xy(10, f64::from(img.size.0), f64::from(img.size.1)); - c.xy(11, 1.0, 1.0); - c.int(280, 1); - c.int(281, 0); - for (reactor, image) in &img.reactors { - c.object("IMAGEDEF_REACTOR", *reactor, *image, "AcDbRasterImageDefReactor"); - c.int(90, 2); - c.handle(330, *image); - } - } - } - c.end_section(); - } - - /// A layout (DXF 2000 and later): its plot settings, then the layout itself. - fn layout(&self, c: &mut Codes, h: Handle, name: &str, tab: i64, record: Handle) { - let [x0, y0, x1, y1] = self.extents; - c.object("LAYOUT", h, fixed::LAYOUTS, "AcDbPlotSettings"); - c.raw(1, ""); - c.raw(2, "none_device"); - c.raw(4, ""); - c.raw(6, ""); - for code in 40..=49 { - c.num(code, 0.0); - } - c.num(140, 0.0); - c.num(141, 0.0); - c.num(142, 1.0); - c.num(143, 1.0); - // Plot flags; 1024 marks the model space layout. - c.int(70, if record == fixed::MODEL_RECORD { 688 | 1024 } else { 688 }); - c.int(72, 1); - c.int(73, 0); - c.int(74, 5); - c.raw(7, ""); - c.int(75, 16); - if self.version.true_color() { - // Shade plot mode (as displayed), resolution level (normal) and custom DPI. - c.int(76, 0); - c.int(77, 2); - c.int(78, 300); - } - c.num(147, 1.0); - // The paper image origin is 148 (x) and 149 (y), not a point at 148 and 158. - c.num(148, 0.0); - c.num(149, 0.0); - c.raw(100, "AcDbLayout"); - c.raw(1, name); - c.int(70, 1); - c.int(71, tab); - let [lx0, ly0, lx1, ly1] = self.limits; - c.xy(10, lx0, ly0); - c.xy(11, lx1, ly1); - c.xyz(12, 0.0, 0.0); - c.xyz(14, x0, y0); - c.xyz(15, x1, y1); - c.num(146, 0.0); - c.xyz(13, 0.0, 0.0); - c.xyz(16, 1.0, 0.0); - c.xyz(17, 0.0, 1.0); - c.int(76, 1); - c.handle(330, record); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn numbers_and_text_are_written_plainly() { - assert_eq!(num(1.5), "1.5"); - assert_eq!(num(-0.0000001), "0"); - assert_eq!(num(2.0), "2"); - assert_eq!(num(f64::NAN), "0"); - assert_eq!(text("a^b\nc", true), "a^ b c"); - assert_eq!(text("Größe 😀", false), "Gr\\U+00F6\\U+00DFe ?"); - assert_eq!(text("Größe", true), "Größe"); - } -} diff --git a/crates/cad/tests/data/shapes_r12.dxf b/crates/cad/tests/data/shapes_r12.dxf new file mode 100644 index 0000000000..96ea7b638e --- /dev/null +++ b/crates/cad/tests/data/shapes_r12.dxf @@ -0,0 +1,448 @@ + 0 +SECTION + 2 +HEADER + 9 +$ACADVER + 1 +AC1009 + 9 +$DWGCODEPAGE + 3 +ANSI_1252 + 9 +$INSBASE + 10 +0 + 20 +0 + 30 +0 + 9 +$EXTMIN + 10 +10 + 20 +20 + 30 +0 + 9 +$EXTMAX + 10 +180 + 20 +90 + 30 +0 + 9 +$LIMMIN + 10 +0 + 20 +0 + 9 +$LIMMAX + 10 +200 + 20 +100 + 0 +ENDSEC + 0 +SECTION + 2 +TABLES + 0 +TABLE + 2 +VPORT + 70 +1 + 0 +VPORT + 2 +*ACTIVE + 70 +0 + 10 +0 + 20 +0 + 11 +1 + 21 +1 + 12 +95 + 22 +55 + 13 +0 + 23 +0 + 14 +1 + 24 +1 + 15 +10 + 25 +10 + 16 +0 + 26 +0 + 36 +1 + 17 +0 + 27 +0 + 37 +0 + 40 +124.666667 + 41 +1.5 + 42 +50 + 43 +0 + 44 +0 + 50 +0 + 51 +0 + 71 +0 + 72 +1000 + 73 +1 + 74 +3 + 75 +0 + 76 +0 + 77 +0 + 78 +0 + 0 +ENDTAB + 0 +TABLE + 2 +LTYPE + 70 +3 + 0 +LTYPE + 2 +ByBlock + 70 +0 + 3 + + 72 +65 + 73 +0 + 40 +0 + 0 +LTYPE + 2 +ByLayer + 70 +0 + 3 + + 72 +65 + 73 +0 + 40 +0 + 0 +LTYPE + 2 +Continuous + 70 +0 + 3 +Solid line + 72 +65 + 73 +0 + 40 +0 + 0 +ENDTAB + 0 +TABLE + 2 +LAYER + 70 +2 + 0 +LAYER + 2 +0 + 70 +0 + 62 +7 + 6 +Continuous + 0 +LAYER + 2 +LAYER_1 + 70 +0 + 62 +171 + 6 +Continuous + 0 +ENDTAB + 0 +TABLE + 2 +STYLE + 70 +1 + 0 +STYLE + 2 +Standard + 70 +0 + 40 +0 + 41 +1 + 50 +0 + 71 +0 + 42 +2.5 + 3 +txt + 4 + + 0 +ENDTAB + 0 +ENDSEC + 0 +SECTION + 2 +ENTITIES + 0 +POLYLINE + 8 +LAYER_1 + 62 +1 + 66 +1 + 10 +0 + 20 +0 + 30 +0 + 70 +1 + 0 +VERTEX + 8 +LAYER_1 + 62 +1 + 10 +10 + 20 +90 + 30 +0 + 0 +VERTEX + 8 +LAYER_1 + 62 +1 + 10 +110 + 20 +90 + 30 +0 + 0 +VERTEX + 8 +LAYER_1 + 62 +1 + 10 +110 + 20 +40 + 30 +0 + 0 +VERTEX + 8 +LAYER_1 + 62 +1 + 10 +10 + 20 +40 + 30 +0 + 0 +SEQEND + 8 +LAYER_1 + 62 +1 + 0 +POLYLINE + 8 +LAYER_1 + 62 +7 + 66 +1 + 10 +0 + 20 +0 + 30 +0 + 70 +1 + 40 +1 + 41 +1 + 0 +VERTEX + 8 +LAYER_1 + 62 +7 + 10 +10 + 20 +90 + 30 +0 + 0 +VERTEX + 8 +LAYER_1 + 62 +7 + 10 +110 + 20 +90 + 30 +0 + 0 +VERTEX + 8 +LAYER_1 + 62 +7 + 10 +110 + 20 +40 + 30 +0 + 0 +VERTEX + 8 +LAYER_1 + 62 +7 + 10 +10 + 20 +40 + 30 +0 + 0 +SEQEND + 8 +LAYER_1 + 62 +7 + 0 +POLYLINE + 8 +LAYER_1 + 62 +5 + 66 +1 + 10 +0 + 20 +0 + 30 +0 + 70 +1 + 40 +2 + 41 +2 + 0 +VERTEX + 8 +LAYER_1 + 62 +5 + 10 +120 + 20 +50 + 30 +0 + 42 +-2.414214 + 0 +VERTEX + 8 +LAYER_1 + 62 +5 + 10 +150 + 20 +20 + 30 +0 + 42 +-0.414214 + 0 +SEQEND + 8 +LAYER_1 + 62 +5 + 0 +ENDSEC + 0 +EOF diff --git a/crates/cad/tests/data/shapes_r2018.dxf b/crates/cad/tests/data/shapes_r2018.dxf new file mode 100644 index 0000000000..c29b89a037 --- /dev/null +++ b/crates/cad/tests/data/shapes_r2018.dxf @@ -0,0 +1,1146 @@ + 0 +SECTION + 2 +HEADER + 9 +$ACADVER + 1 +AC1032 + 9 +$DWGCODEPAGE + 3 +ANSI_1252 + 9 +$INSBASE + 10 +0 + 20 +0 + 30 +0 + 9 +$EXTMIN + 10 +10 + 20 +20 + 30 +0 + 9 +$EXTMAX + 10 +180 + 20 +90 + 30 +0 + 9 +$LIMMIN + 10 +0 + 20 +0 + 9 +$LIMMAX + 10 +200 + 20 +100 + 9 +$LWDISPLAY +290 +1 + 9 +$INSUNITS + 70 +0 + 9 +$MEASUREMENT + 70 +0 + 9 +$HANDSEED + 5 +3A + 0 +ENDSEC + 0 +SECTION + 2 +CLASSES + 0 +CLASS + 1 +ACDBDICTIONARYWDFLT + 2 +AcDbDictionaryWithDefault + 3 +ObjectDBX Classes + 90 +0 + 91 +0 +280 +0 +281 +0 + 0 +CLASS + 1 +ACDBPLACEHOLDER + 2 +AcDbPlaceHolder + 3 +ObjectDBX Classes + 90 +0 + 91 +0 +280 +0 +281 +0 + 0 +CLASS + 1 +LAYOUT + 2 +AcDbLayout + 3 +ObjectDBX Classes + 90 +0 + 91 +0 +280 +0 +281 +0 + 0 +ENDSEC + 0 +SECTION + 2 +TABLES + 0 +TABLE + 2 +VPORT + 5 +8 +330 +0 +100 +AcDbSymbolTable + 70 +1 + 0 +VPORT + 5 +15 +330 +8 +100 +AcDbSymbolTableRecord +100 +AcDbViewportTableRecord + 2 +*Active + 70 +0 + 10 +0 + 20 +0 + 11 +1 + 21 +1 + 12 +95 + 22 +55 + 13 +0 + 23 +0 + 14 +1 + 24 +1 + 15 +10 + 25 +10 + 16 +0 + 26 +0 + 36 +1 + 17 +0 + 27 +0 + 37 +0 + 40 +124.666667 + 41 +1.5 + 42 +50 + 43 +0 + 44 +0 + 50 +0 + 51 +0 + 71 +0 + 72 +1000 + 73 +1 + 74 +3 + 75 +0 + 76 +0 + 77 +0 + 78 +0 +281 +0 + 65 +0 +146 +0 + 0 +ENDTAB + 0 +TABLE + 2 +LTYPE + 5 +2 +330 +0 +100 +AcDbSymbolTable + 70 +3 + 0 +LTYPE + 5 +34 +330 +2 +100 +AcDbSymbolTableRecord +100 +AcDbLinetypeTableRecord + 2 +ByBlock + 70 +0 + 3 + + 72 +65 + 73 +0 + 40 +0 + 0 +LTYPE + 5 +35 +330 +2 +100 +AcDbSymbolTableRecord +100 +AcDbLinetypeTableRecord + 2 +ByLayer + 70 +0 + 3 + + 72 +65 + 73 +0 + 40 +0 + 0 +LTYPE + 5 +36 +330 +2 +100 +AcDbSymbolTableRecord +100 +AcDbLinetypeTableRecord + 2 +Continuous + 70 +0 + 3 +Solid line + 72 +65 + 73 +0 + 40 +0 + 0 +ENDTAB + 0 +TABLE + 2 +LAYER + 5 +1 +330 +0 +100 +AcDbSymbolTable + 70 +2 + 0 +LAYER + 5 +37 +330 +1 +100 +AcDbSymbolTableRecord +100 +AcDbLayerTableRecord + 2 +0 + 70 +0 + 62 +7 + 6 +Continuous +290 +1 +370 +-3 +390 +1B + 0 +LAYER + 5 +38 +330 +1 +100 +AcDbSymbolTableRecord +100 +AcDbLayerTableRecord + 2 +Layer 1 + 70 +0 + 62 +171 + 6 +Continuous +290 +1 +370 +-3 +390 +1B + 0 +ENDTAB + 0 +TABLE + 2 +STYLE + 5 +5 +330 +0 +100 +AcDbSymbolTable + 70 +1 + 0 +STYLE + 5 +39 +330 +5 +100 +AcDbSymbolTableRecord +100 +AcDbTextStyleTableRecord + 2 +Standard + 70 +0 + 40 +0 + 41 +1 + 50 +0 + 71 +0 + 42 +2.5 + 3 +txt + 4 + + 0 +ENDTAB + 0 +TABLE + 2 +VIEW + 5 +7 +330 +0 +100 +AcDbSymbolTable + 70 +0 + 0 +ENDTAB + 0 +TABLE + 2 +UCS + 5 +6 +330 +0 +100 +AcDbSymbolTable + 70 +0 + 0 +ENDTAB + 0 +TABLE + 2 +APPID + 5 +3 +330 +0 +100 +AcDbSymbolTable + 70 +1 + 0 +APPID + 5 +16 +330 +3 +100 +AcDbSymbolTableRecord +100 +AcDbRegAppTableRecord + 2 +ACAD + 70 +0 + 0 +ENDTAB + 0 +TABLE + 2 +DIMSTYLE + 5 +4 +330 +0 +100 +AcDbSymbolTable + 70 +1 +100 +AcDbDimStyleTable + 0 +DIMSTYLE +105 +17 +330 +4 +100 +AcDbSymbolTableRecord +100 +AcDbDimStyleTableRecord + 2 +Standard + 70 +0 + 0 +ENDTAB + 0 +TABLE + 2 +BLOCK_RECORD + 5 +9 +330 +0 +100 +AcDbSymbolTable + 70 +2 + 0 +BLOCK_RECORD + 5 +D +330 +9 +100 +AcDbSymbolTableRecord +100 +AcDbBlockTableRecord + 2 +*Model_Space +340 +13 + 70 +0 +280 +1 +281 +0 + 0 +BLOCK_RECORD + 5 +E +330 +9 +100 +AcDbSymbolTableRecord +100 +AcDbBlockTableRecord + 2 +*Paper_Space +340 +14 + 70 +0 +280 +1 +281 +0 + 0 +ENDTAB + 0 +ENDSEC + 0 +SECTION + 2 +BLOCKS + 0 +BLOCK + 5 +F +330 +D +100 +AcDbEntity + 8 +0 +100 +AcDbBlockBegin + 2 +*Model_Space + 70 +0 + 10 +0 + 20 +0 + 30 +0 + 3 +*Model_Space + 1 + + 0 +ENDBLK + 5 +10 +330 +D +100 +AcDbEntity + 8 +0 +100 +AcDbBlockEnd + 0 +BLOCK + 5 +11 +330 +E +100 +AcDbEntity + 8 +0 +100 +AcDbBlockBegin + 2 +*Paper_Space + 70 +0 + 10 +0 + 20 +0 + 30 +0 + 3 +*Paper_Space + 1 + + 0 +ENDBLK + 5 +12 +330 +E +100 +AcDbEntity + 8 +0 +100 +AcDbBlockEnd + 0 +ENDSEC + 0 +SECTION + 2 +ENTITIES + 0 +LWPOLYLINE + 5 +30 +330 +D +100 +AcDbEntity + 8 +Layer 1 + 62 +1 +420 +16711680 +100 +AcDbPolyline + 90 +4 + 70 +1 + 10 +10 + 20 +90 + 10 +110 + 20 +90 + 10 +110 + 20 +40 + 10 +10 + 20 +40 + 0 +HATCH + 5 +31 +330 +D +100 +AcDbEntity + 8 +Layer 1 + 62 +1 +420 +16711680 +100 +AcDbHatch + 10 +0 + 20 +0 + 30 +0 +210 +0 +220 +0 +230 +1 + 2 +SOLID + 70 +1 + 71 +0 + 91 +1 + 92 +3 + 72 +0 + 73 +1 + 93 +4 + 10 +10 + 20 +90 + 10 +110 + 20 +90 + 10 +110 + 20 +40 + 10 +10 + 20 +40 + 97 +0 + 75 +0 + 76 +1 + 98 +0 + 0 +LWPOLYLINE + 5 +32 +330 +D +100 +AcDbEntity + 8 +Layer 1 + 62 +7 +370 +35 +420 +0 +100 +AcDbPolyline + 90 +4 + 70 +1 + 10 +10 + 20 +90 + 10 +110 + 20 +90 + 10 +110 + 20 +40 + 10 +10 + 20 +40 + 0 +CIRCLE + 5 +33 +330 +D +100 +AcDbEntity + 8 +Layer 1 + 62 +5 +370 +70 +420 +255 +100 +AcDbCircle + 10 +150 + 20 +50 + 30 +0 + 40 +30 +210 +0 +220 +0 +230 +1 + 0 +ENDSEC + 0 +SECTION + 2 +OBJECTS + 0 +DICTIONARY + 5 +A +330 +0 +100 +AcDbDictionary +281 +1 + 3 +ACAD_GROUP +350 +B + 3 +ACAD_LAYOUT +350 +C + 3 +ACAD_PLOTSTYLENAME +350 +1A + 0 +DICTIONARY + 5 +B +330 +A +100 +AcDbDictionary +281 +1 + 0 +DICTIONARY + 5 +C +330 +A +100 +AcDbDictionary +281 +1 + 3 +Layout1 +350 +14 + 3 +Model +350 +13 + 0 +ACDBDICTIONARYWDFLT + 5 +1A +330 +A +100 +AcDbDictionary +281 +1 + 3 +Normal +350 +1B +100 +AcDbDictionaryWithDefault +340 +1B + 0 +ACDBPLACEHOLDER + 5 +1B +330 +1A + 0 +LAYOUT + 5 +13 +330 +C +100 +AcDbPlotSettings + 1 + + 2 +none_device + 4 + + 6 + + 40 +0 + 41 +0 + 42 +0 + 43 +0 + 44 +0 + 45 +0 + 46 +0 + 47 +0 + 48 +0 + 49 +0 +140 +0 +141 +0 +142 +1 +143 +1 + 70 +1712 + 72 +1 + 73 +0 + 74 +5 + 7 + + 75 +16 + 76 +0 + 77 +2 + 78 +300 +147 +1 +148 +0 +149 +0 +100 +AcDbLayout + 1 +Model + 70 +1 + 71 +0 + 10 +0 + 20 +0 + 11 +200 + 21 +100 + 12 +0 + 22 +0 + 32 +0 + 14 +10 + 24 +20 + 34 +0 + 15 +180 + 25 +90 + 35 +0 +146 +0 + 13 +0 + 23 +0 + 33 +0 + 16 +1 + 26 +0 + 36 +0 + 17 +0 + 27 +1 + 37 +0 + 76 +1 +330 +D + 0 +LAYOUT + 5 +14 +330 +C +100 +AcDbPlotSettings + 1 + + 2 +none_device + 4 + + 6 + + 40 +0 + 41 +0 + 42 +0 + 43 +0 + 44 +0 + 45 +0 + 46 +0 + 47 +0 + 48 +0 + 49 +0 +140 +0 +141 +0 +142 +1 +143 +1 + 70 +688 + 72 +1 + 73 +0 + 74 +5 + 7 + + 75 +16 + 76 +0 + 77 +2 + 78 +300 +147 +1 +148 +0 +149 +0 +100 +AcDbLayout + 1 +Layout1 + 70 +1 + 71 +1 + 10 +0 + 20 +0 + 11 +200 + 21 +100 + 12 +0 + 22 +0 + 32 +0 + 14 +10 + 24 +20 + 34 +0 + 15 +180 + 25 +90 + 35 +0 +146 +0 + 13 +0 + 23 +0 + 33 +0 + 16 +1 + 26 +0 + 36 +0 + 17 +0 + 27 +1 + 37 +0 + 76 +1 +330 +E + 0 +ENDSEC + 0 +EOF 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 6339f0a4ca..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 @@ -664,9 +653,6 @@ pub fn jpeg_with_icc(bytes: &[u8], icc: &[u8]) -> Option> { const CHUNK: usize = 0xFFFF - 2 - ICC_SEGMENT.len() - 2; let chunks: Vec<&[u8]> = icc.chunks(CHUNK).collect(); let count = u8::try_from(chunks.len()).ok().filter(|n| *n > 0)?; - if !bytes.starts_with(&[0xFF, 0xD8]) { - return None; - } let mut segments = Vec::with_capacity(icc.len() + 18 * chunks.len()); for (i, chunk) in chunks.iter().enumerate() { let len = u16::try_from(chunk.len() + 2 + ICC_SEGMENT.len() + 2).ok()?; @@ -676,6 +662,23 @@ pub fn jpeg_with_icc(bytes: &[u8], icc: &[u8]) -> Option> { segments.extend_from_slice(&[u8::try_from(i + 1).ok()?, count]); segments.extend_from_slice(chunk); } + with_icc_segments(bytes, segments) +} + +/// JPEG `bytes` without the ICC profile they carry: every `ICC_PROFILE` APP2 segment before the +/// scan taken out, and the other segments and the scan as they are. `None` for bytes whose +/// segments before the scan can't be read. +pub fn jpeg_without_icc(bytes: &[u8]) -> Option> { + with_icc_segments(bytes, vec![]) +} + +/// JPEG `bytes` with every `ICC_PROFILE` APP2 segment before the scan taken out and `segments` +/// written after the leading application segments; `None` when the bytes don't start a JPEG or +/// their segments before the scan can't be read. +fn with_icc_segments(bytes: &[u8], segments: Vec) -> Option> { + if !bytes.starts_with(&[0xFF, 0xD8]) { + return None; + } let mut out = Vec::with_capacity(bytes.len() + segments.len()); out.extend_from_slice(&[0xFF, 0xD8]); let mut icc_segments = Some(segments); @@ -837,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()) } @@ -918,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 @@ -1093,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, @@ -1110,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()?; @@ -1129,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 { @@ -1168,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; } } @@ -2195,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/graph.rs b/crates/doc/src/graph.rs index 58b52dd651..36fe29a8f2 100644 --- a/crates/doc/src/graph.rs +++ b/crates/doc/src/graph.rs @@ -140,7 +140,7 @@ impl crate::Document { /// the text in graphs): the value axis numbers, the category labels (category axis, radar spokes, pie names) and the /// legend labels (beside or across the top, or in pie wedges). `None` draws the default 9 pt black. The `*_para` /// fields are the paragraph attributes each kind keeps the same way (`None`: the defaults); the graph still sets each -/// label's alignment. +/// label's alignment. [`Self::axis_rows`] and [`Self::ring_rows`] are the rows the graph's lines keep the same way. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct LabelStyles { @@ -180,6 +180,14 @@ pub struct LabelStyles { /// The object fill and stroke rows the legend labels keep, as [`Self::values_rows`]. #[serde(skip_serializing_if = "Option::is_none")] pub legend_rows: Option, + /// The object rows the axis lines and tick marks keep once set with the paint, stroke or Appearance controls + /// ([`LabelRows`]). They replace the default 0.5 pt black stroke; kept rows without paint draw none. `None`: the + /// default stroke. + #[serde(skip_serializing_if = "Option::is_none")] + pub axis_rows: Option, + /// The object rows the rings of a radar graph keep, as [`Self::axis_rows`]. `None`: the default 0.25 pt gray stroke. + #[serde(skip_serializing_if = "Option::is_none")] + pub ring_rows: Option, } impl LabelStyles { @@ -483,6 +491,10 @@ pub struct GraphSpec { pub first_column_in_front: bool, #[serde(skip_serializing_if = "std::ops::Not::not")] pub filled_lines: bool, + /// Graph Type › Line Width: how wide Draw Filled Lines draws a line, in points. `None` draws + /// [`DEFAULT_FILLED_LINE_WIDTH`]; see [`Self::filled_line_width`]. + #[serde(skip_serializing_if = "Option::is_none")] + pub line_width: Option, /// Graph Type › Add Drop Shadow (behind columns, bars, lines and pie wedges) and Add Legend Across Top (the /// legend in rows above the plot instead of a column on its right). #[serde(skip_serializing_if = "std::ops::Not::not")] @@ -557,6 +569,24 @@ fn is_zero(n: &usize) -> bool { *n == 0 } +/// Graph Type › Line Width: the width Draw Filled Lines draws a line at when the graph sets none, and the least and +/// greatest widths a graph takes, in points. +pub const DEFAULT_FILLED_LINE_WIDTH: f64 = 3.0; +pub const MIN_FILLED_LINE_WIDTH: f64 = 0.01; +pub const MAX_FILLED_LINE_WIDTH: f64 = 1000.0; + +/// The weight of the black outline Draw Filled Lines draws around each band, in points. +pub const FILLED_LINE_OUTLINE_WIDTH: f64 = 0.25; + +impl GraphSpec { + /// How wide Draw Filled Lines draws a line, in points: [`Self::line_width`], else [`DEFAULT_FILLED_LINE_WIDTH`]. A + /// width a file gives outside [`MIN_FILLED_LINE_WIDTH`] to [`MAX_FILLED_LINE_WIDTH`], or not finite, draws the + /// default. + pub fn filled_line_width(&self) -> f64 { + self.line_width.filter(|w| (MIN_FILLED_LINE_WIDTH..=MAX_FILLED_LINE_WIDTH).contains(w)).unwrap_or(DEFAULT_FILLED_LINE_WIDTH) + } +} + /// Edge-to-Edge Lines for a graph saved before the option existed: on, as it was drawn then. fn edge_to_edge_before_the_option() -> bool { true @@ -696,6 +726,7 @@ impl Default for GraphSpec { first_row_in_front: false, first_column_in_front: false, filled_lines: false, + line_width: None, drop_shadow: false, legend_across_top: false, pie_legend_in_wedges: false, diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index d49776b2cb..ab571e50b2 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -239,6 +239,190 @@ thread_local! { static LIVE_EVALUATED: std::cell::Cell = const { std::cell::Cell::new(0) }; } +/// The art an object draws in Preview with the geometry effects in it applied, at every depth, as +/// plain art whose objects keep the ids of the objects they are drawn from: `None` when no geometry +/// effect in it changes what it draws. Effects are evaluated above this crate, so the engine +/// registers one with [`set_drawn_art`]. +pub type DrawnArt = fn(&SymbolBoxes<'_>, &Node) -> Option; + +static DRAWN_ART: OnceLock = OnceLock::new(); + +/// Register how the art an object draws with its geometry effects is found, for clicks and +/// marquees (the first registration stays). +pub fn set_drawn_art(f: DrawnArt) { + // Already set: the same engine, registered by another session. + let _ = DRAWN_ART.set(f); +} + +/// The art of an object found by [`drawn`] (none, or one object), with what it was found from, and +/// the box round everything that art can paint. +struct EvaluatedDrawn { + of: EvaluatedLive, + reach: Option, +} + +/// How many objects' drawn art [`drawn`] keeps on each thread. Every pointer move measures every +/// object with effects that it passes, so the art of all of a document's objects with effects is +/// kept, within [`LIVE_KEPT_SIZE`], not only the latest few as with live objects. +const DRAWN_KEPT: usize = 4096; + +thread_local! { + /// The drawn art [`drawn`] keeps, by object, and the sum of their sizes. + static DRAWN: RefCell<(HashMap, usize)> = RefCell::new((HashMap::new(), 0)); + /// Whether [`drawn`] gives no art: set while art it gave is tested ([`DrawnOff`]). + static DRAWN_OFF: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +#[cfg(test)] +thread_local! { + /// How many objects' drawn art [`drawn`] evaluated on this thread. + static DRAWN_EVALUATED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// While a guard lives, [`drawn`] gives no art: the art it gave already has every geometry effect +/// in it applied, and is tested as it is. +struct DrawnOff { + was: bool, +} + +impl DrawnOff { + fn set() -> Self { + Self { was: DRAWN_OFF.replace(true) } + } +} + +impl Drop for DrawnOff { + fn drop(&mut self) { + DRAWN_OFF.set(self.was); + } +} + +/// `f()`, with `mask` under a [`DrawnOff`] guard: the clipping path of a clip group or of a +/// clipping layer is clicked and touched by its own geometry, whatever its geometry effects do to +/// the region it clips to. +fn plain(mask: bool, f: impl FnOnce() -> T) -> T { + let _off = mask.then(DrawnOff::set); + f() +} + +/// The art object `n` draws with the geometry effects in it applied ([`set_drawn_art`]), empty when +/// none changes what it draws, and the box round everything that art can paint. `None` while +/// nothing is registered, while a [`DrawnOff`] guard lives, for objects whose art is not evaluated +/// ([`evaluates`]), and when nothing in `n`, nor the art of a symbol an instance in it shows, has a +/// visible effect ([`draws_effects`]). The art is evaluated again when `n`, a symbol of the +/// document, its patterns, swatches or color groups, or the [`LiveInputs`] have changed since, and +/// on every call while it holds a placed document ([`holds_placed`]). When the art kept is full, new +/// art replaces as much other art as it needs room for, and art larger than [`LIVE_KEPT_SIZE`] is +/// kept alone. +fn drawn(symbols: &SymbolBoxes, n: &Node) -> Option<(Rc>, Option)> { + let f = DRAWN_ART.get()?; + if DRAWN_OFF.get() || !evaluates(n) || !(has_own_effects(n) || draws_effects(symbols, n)) { + return None; + } + let doc = symbols.document(); + let inputs = live_inputs(); + let kept = DRAWN.with_borrow(|(kept, _)| kept.get(&n.id).filter(|e| e.of.is_of(doc, n, inputs)).map(|e| (e.of.art.clone(), e.reach))); + if kept.is_some() { + return kept; + } + #[cfg(test)] + DRAWN_EVALUATED.with(|c| c.set(c.get() + 1)); + let art = f(symbols, n); + let reach = art.as_ref().and_then(|a| a.reach_bounds_with(symbols)); + let art = Rc::new(art.into_iter().collect::>()); + let size = art_size(&art).saturating_add(art_size(std::slice::from_ref(n))); + if !holds_placed(doc, n) { + let of = EvaluatedLive { + node: n.clone(), + symbols: doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(), + patterns: doc.patterns.clone(), + swatches: doc.swatches.clone(), + swatch_groups: doc.swatch_groups.clone(), + inputs, + art: art.clone(), + size, + }; + DRAWN.with_borrow_mut(|(kept, total)| { + if let Some(old) = kept.remove(&n.id) { + *total = total.saturating_sub(old.of.size); + } + while kept.len() >= DRAWN_KEPT || total.saturating_add(size) > LIVE_KEPT_SIZE { + let Some(other) = kept.keys().next().copied() else { break }; + if let Some(old) = kept.remove(&other) { + *total = total.saturating_sub(old.of.size); + } + } + kept.insert(n.id, EvaluatedDrawn { of, reach }); + *total = total.saturating_add(size); + }); + } + Some((art, reach)) +} + +/// Is `n` an object whose art [`drawn`] evaluates: a path or compound path, or a group or layer with +/// geometry effects or fills and strokes of its own, which paint its members as their effects draw +/// them? +fn evaluates(n: &Node) -> bool { + match &n.kind { + NodeKind::Path { guide, .. } => !guide, + NodeKind::Compound { .. } => true, + NodeKind::Group { .. } | NodeKind::Layer { .. } => has_own_effects(n) || !n.appearance.items.is_empty(), + _ => false, + } +} + +/// The art path or compound path `n` draws with its geometry effects ([`drawn`]) in Preview, or +/// group or layer `n` with geometry effects or fills and strokes of its own: `None` in outline +/// (`outline`, where the canvas draws no effects), for other objects, and when no geometry effect +/// changes what it draws. Also `None` for a clip group or layer whose art holds only its clipping +/// path and that path's strokes, not the art it clips: its members are then tested one by one. +fn drawn_art(symbols: &SymbolBoxes, n: &Node, outline: bool) -> Option>> { + if outline { + return None; + } + drawn(symbols, n).map(|(art, _)| art).filter(|art| !art.is_empty() && (!n.clips() || holds_clipped_art(n, art))) +} + +/// Does `art`, the drawn art of clip group or layer `n`, hold any of the objects `n` clips (its +/// members after the clipping path), or does `n` clip none? +fn holds_clipped_art(n: &Node, art: &[Node]) -> bool { + let clipped: HashSet = n.children().into_iter().flatten().skip(1).map(|c| c.id).collect(); + if clipped.is_empty() { + return true; + } + let mut found = false; + for a in art { + a.walk(&mut |c| found |= clipped.contains(&c.id)); + } + found +} + +/// `base`, a box round what `n` paints without its geometry effects, grown to hold the art they +/// draw ([`effects_reach`]). `None` when `base` is. +fn drawn_reach(symbols: &SymbolBoxes, n: &Node, base: Option) -> Option { + let base = base?; + Some(effects_reach(symbols, n).map_or(base, |r| base.union(r))) +} + +/// The box round the art that the geometry effects in `n` draw: that of its own art ([`drawn`]) +/// when it is evaluated ([`evaluates`]), else the union of its members' in a group, layer or +/// Intertwine group. `None` when +/// no geometry effect changes what it draws, and while a [`DrawnOff`] guard lives. +fn effects_reach(symbols: &SymbolBoxes, n: &Node) -> Option { + if DRAWN_OFF.get() { + return None; + } + if evaluates(n) { + return drawn(symbols, n).filter(|(art, _)| !art.is_empty()).and_then(|(_, reach)| reach); + } + match &n.kind { + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Intertwine { children } => { + children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, effects_reach(symbols, c))) + } + _ => None, + } +} + /// Topmost editable object under `p`. pub fn hit_test(doc: &Document, p: Point, opt: HitOptions) -> Option { hit_test_skipping(doc, p, opt, &|_| false, true) @@ -323,34 +507,31 @@ fn path_options(nodes: &[&Node], chain: &[NodeId], opt: HitOptions) -> Option) -> Vec { - let walk = ArtWalk::open(); + let _walk = ArtWalk::open(); let opt = HitOptions { scope: scope.or(opt.scope), ..opt }; // Normally one hit test per *object* suffices: layers and sublayers aren't selectable, // while a group (including a clipping group) is selected as one object. Repeatedly // searching the full tree for each hit made a stack of n overlapping paths O(n^2). // Isolation and Edit Contents change where selection groups begin; keep the original // traversal for those cases rather than change their Select Behind semantics. - if opt.scope.is_some() { + // Malformed files may contain non-layer roots; let the general traversal handle them. + if opt.scope.is_some() || doc.layers.iter().any(|l| !l.is_layer()) { return objects_at_repeated(doc, p, opt, scope); } let mut tops = Vec::new(); let mut seen = HashSet::new(); let symbols = doc.symbol_boxes(); for layer in doc.layers.iter().rev() { - // Malformed files may contain non-layer roots; let the general traversal handle them. - if !layer.is_layer() { - walk.restart(); - return objects_at_repeated(doc, p, opt, scope); - } if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) { continue; } if !objects_at_layer(layer, p, opt, &symbols, &mut tops, &mut seen) { // An envelope in Edit Contents may expose objects *within* a top-level group. - // The repeated traversal handles that mixed hierarchy precisely, with the whole - // limit of symbol art to walk. - walk.restart(); - return objects_at_repeated(doc, p, opt, scope); + // The repeated traversal handles that mixed hierarchy precisely. The objects found + // so far lie above the envelope and stay first; the repeated traversal finds the + // rest with what is left of the limit of symbol art to walk. + tops = objects_at_repeated_after(doc, p, opt, scope, tops); + break; } } // The objects on a locked artboard can't be selected, as `hit_test_skipping` passes over them. @@ -368,6 +549,11 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option, seen: &mut HashSet) -> bool { let Some(children) = layer.children() else { return true }; let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt }; + // A layer whose own geometry effects reshape its art is hit where that art is drawn, which the + // general traversal finds ([`hit_children`]). + if drawn_art(symbols, layer, opt.outline).is_some() { + return false; + } if layer.clips() && let Some(clip) = children.first() { @@ -400,11 +586,11 @@ fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBox } let skip = |id| seen.contains(&id); let mut chain = Vec::new(); - let hit = match &c.kind { + let hit = plain(i == 0 && layer.clips(), || match &c.kind { NodeKind::Group { .. } | NodeKind::Intertwine { .. } => hit_children(c, p, opt, symbols, &skip, &mut chain, true).is_some(), NodeKind::Blend { .. } => hit_children(c, p, opt, symbols, &skip, &mut chain, true).is_some() || hit_leaf(c, p, opt, symbols).is_some(), _ => hit_leaf(c, p, opt, symbols).is_some(), - }; + }); if hit && seen.insert(c.id) { tops.push(c.id); } @@ -414,7 +600,11 @@ fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBox /// The general selection order also handles isolation and nested Edit Contents. fn objects_at_repeated(doc: &Document, p: Point, opt: HitOptions, scope: Option) -> Vec { - let mut tops: Vec = vec![]; + objects_at_repeated_after(doc, p, opt, scope, vec![]) +} + +/// [`objects_at_repeated`] after `tops`, the topmost objects under `p` already found. +fn objects_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, scope: Option, mut tops: Vec) -> Vec { // Each round leaves out the objects found so far (and everything inside them). while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id), true).map(|h| h.top_object(scope)) { if tops.contains(&top) { @@ -461,6 +651,23 @@ pub fn locked_objects_at(doc: &Document, p: Point, opt: HitOptions) -> Vec) { let Some(children) = parent.children() else { return }; + // A group or layer whose own geometry effects reshape what it holds: the locked objects drawn + // under `p` ([`drawn_hit`]). + if !(parent.clips() && edits_inside(parent, opt.scope)) + && let Some(art) = drawn_art(symbols, parent, opt.outline) + { + let _off = DrawnOff::set(); + let mut list = |id: NodeId, _: HitKind| { + if let Some(locked) = locked_member(parent, id, opt) + && !out.contains(&locked) + { + out.push(locked); + } + out.len() >= MAX_LOCKED_AT + }; + art.iter().rev().any(|a| art_hit(a, p, opt, symbols, &mut list)); + return; + } if parent.clips() && !edits_inside(parent, opt.scope) && children.first().is_some_and(|clip| !clip_contains(clip, p, opt.outline)) { return; } @@ -473,7 +680,7 @@ fn locked_children(parent: &Node, p: Point, opt: HitOptions, symbols: &SymbolBox continue; } if c.locked { - if locked_hit(c, p, opt, symbols) { + if plain(i == 0 && parent.clips(), || locked_hit(c, p, opt, symbols)) { out.push(c.id); } continue; @@ -598,13 +805,26 @@ pub fn set_clip_region(f: ClipRegion) { /// then can the registered [`ClipRegion`] find a geometry effect in it. fn has_effects(clip: &Node) -> bool { let mut found = false; - clip.walk(&mut |n| { - let visible = |e: &crate::Effect| e.visible; - found |= n.appearance.effects.iter().any(visible) || n.appearance.items.iter().any(|i| i.effects().iter().any(visible)); + clip.walk(&mut |n| found |= has_own_effects(n)); + found +} + +/// Does `n`, anything it holds, or the art of a symbol an instance in it shows have a visible +/// effect? Only then can the registered [`DrawnArt`] find a geometry effect in it. +fn draws_effects(symbols: &SymbolBoxes, n: &Node) -> bool { + let mut found = false; + n.walk(&mut |c| { + found = found || has_own_effects(c) || matches!(&c.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.has_effects(symbol)); }); found } +/// Does `n` itself have a visible effect, of its own or on one of its own fills or strokes? +fn has_own_effects(n: &Node) -> bool { + let visible = |e: &crate::Effect| e.visible; + n.appearance.effects.iter().any(visible) || n.appearance.items.iter().any(|i| i.effects().iter().any(visible)) +} + /// A clipping path's region evaluated by [`clip_region`] on this thread: the clipping path and the /// [`LiveInputs`] as they were, the region (`None` without geometry effects) and the number of its /// path elements. @@ -747,15 +967,7 @@ pub fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_ /// hidden, when it can't be edited (`editable_only`), when it is the part of a Shaper group that /// isn't shown, or when `p` is outside its reach. fn may_hit(parent: &Node, i: usize, c: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, editable_only: bool) -> bool { - if shaper_hides(parent, i, opt.scope) { - return false; - } - // Read-only samples can read locked/template art; hidden art never participates. - if !c.visible || editable_only && (c.locked || c.is_template()) { - return false; - } - // A ruler guide is picked by the guide commands, never by an object hit test. - if c.is_ruler_guide() || opt.skip_guides && matches!(c.kind, NodeKind::Path { guide: true, .. }) { + if !may_reach(parent, i, c, opt, editable_only) { return false; } // (An envelope's content sits where it was, not where the envelope draws it.) @@ -764,11 +976,28 @@ fn may_hit(parent: &Node, i: usize, c: &Node, p: Point, opt: HitOptions, symbols || cull_reach(c, symbols).is_none_or(|b| b.inflate(opt.tol, opt.tol).contains(p)) } +/// Can a click hit `c`, the child `i` of `parent`, or something inside it, wherever it is? Not +/// when it is hidden, when it can't be edited (`editable_only`), when it is a ruler guide or a +/// guide while guides are locked or hidden, or when it is the part of a Shaper group that isn't +/// shown. +fn may_reach(parent: &Node, i: usize, c: &Node, opt: HitOptions, editable_only: bool) -> bool { + if shaper_hides(parent, i, opt.scope) { + return false; + } + // Read-only samples can read locked/template art; hidden art never participates. + if !c.visible || editable_only && (c.locked || c.is_template()) { + return false; + } + // A ruler guide is picked by the guide commands, never by an object hit test. + !(c.is_ruler_guide() || opt.skip_guides && matches!(c.kind, NodeKind::Path { guide: true, .. })) +} + /// A box round everything `c` can paint, for culling clicks: [`Node::reach_bounds_with`], except /// that paths and compound paths are measured by their control points ([`PathData::control_bounds`], /// which hold the curves) instead of along their curves, which a compound path of thousands of /// members takes milliseconds to do on every click and hover. The box only rules points out, and it -/// is at least as large, so the same objects are hit. +/// is at least as large, so the same objects are hit. It also holds the art that the geometry +/// effects in `c` draw ([`drawn_reach`]), wherever they move it. /// /// [`PathData::control_bounds`]: vectorcraft_geom::PathData::control_bounds fn cull_reach(c: &Node, symbols: &SymbolBoxes) -> Option { @@ -777,10 +1006,10 @@ fn cull_reach(c: &Node, symbols: &SymbolBoxes) -> Option { NodeKind::Compound { children, .. } if children.iter().all(|m| m.path_data().is_some()) => { children.iter().filter_map(|m| m.path_data().and_then(vectorcraft_geom::PathData::control_bounds)).reduce(|a, b| a.union(b)) } - _ => return c.reach_bounds_with(symbols), + _ => return drawn_reach(symbols, c, c.reach_bounds_with(symbols)), }; let o = c.appearance.outset(); - control.map(|b| b.inflate(o, o)) + drawn_reach(symbols, c, control.map(|b| b.inflate(o, o))) } /// The members of compound path `children` that a click at `p` within `tol` can touch, as one @@ -854,19 +1083,36 @@ fn hit_children( editable_only: bool, ) -> Option { let children = parent.children()?; - if parent.clips() - && let Some(clip) = children.first() - { - if let Some(kind) = clip_outline_hit(parent, clip, p, opt, symbols, editable_only).filter(|_| !skip(clip.id)) { + let clip = children.first().filter(|_| parent.clips()); + // The selection tools in isolation mode within a clip group (or a layer with a clipping mask) + // hit what it holds outside its clipping mask too. + let edited = clip.is_some() && opt.clip_outlines && editable_only && edits_inside(parent, opt.scope); + // A group or layer whose own geometry effects reshape what it holds hits where that art is drawn. + let art = if edited { None } else { drawn_art(symbols, parent, opt.outline) }; + if let Some(clip) = clip { + // The clipping mask's outline first, where it is drawn. + let drawn_clip = art.as_deref().and_then(|a| a.first()).filter(|a| a.clips()).and_then(|a| a.children()?.first()); + let kind = match drawn_clip { + Some(drawn) => { + let takes = opt.clip_outlines && editable_only && may_reach(parent, 0, clip, opt, editable_only); + takes.then(|| clip_outline(drawn, p, opt)).flatten() + } + None => clip_outline_hit(parent, clip, p, opt, symbols, editable_only), + }; + if let Some(kind) = kind.filter(|_| !skip(clip.id)) { chain.push(clip.id); return Some(Hit { leaf: clip.id, ancestry: chain.clone(), kind, contents_of: None, layers: 1 }); } - // Elsewhere a clip group (or a layer with a clipping mask) only hits inside it, except for - // the selection tools in isolation mode within it. - let edited = opt.clip_outlines && editable_only && edits_inside(parent, opt.scope); - if !edited && !clip_contains(clip, p, opt.outline) { - return None; - } + } + if let Some(art) = art { + return drawn_hit(parent, &art, p, opt, symbols, skip, chain, editable_only); + } + // Elsewhere a clip group (or a layer with a clipping mask) only hits inside it. + if let Some(clip) = clip + && !edited + && !clip_contains(clip, p, opt.outline) + { + return None; } for i in hit_order(parent, children, p) { let Some(c) = children.get(i) else { continue }; @@ -874,7 +1120,7 @@ fn hit_children( continue; } chain.push(c.id); - let hit = match &c.kind { + let hit = plain(i == 0 && clip.is_some(), || match &c.kind { // A sublayer whose Preview is off is clicked in outline, like an outline view. NodeKind::Layer { preview: false, .. } => hit_children(c, p, HitOptions { outline: true, ..opt }, symbols, skip, chain, editable_only), NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Intertwine { .. } => { @@ -887,7 +1133,7 @@ fn hit_children( NodeKind::Blend { .. } => hit_children(c, p, opt, symbols, skip, chain, editable_only) .or_else(|| hit_leaf(c, p, opt, symbols).map(|kind| Hit { leaf: c.id, ancestry: chain.clone(), kind, contents_of: None, layers: 1 })), _ => hit_leaf(c, p, opt, symbols).map(|kind| Hit { leaf: c.id, ancestry: chain.clone(), kind, contents_of: None, layers: 1 }), - }; + }); if hit.is_some() { return hit; } @@ -896,6 +1142,123 @@ fn hit_children( None } +/// What a click at `p` hits in `art`, the art that group or layer `parent` draws with its own +/// geometry effects ([`drawn_art`]): the member of `parent` that the topmost object of the art hit +/// there is drawn from, found by its id, at the depth [`hit_children`] gives it, or `parent` itself, +/// when it is not a layer, for art of its own (its own fills and strokes). Where that member can't be hit (hidden, locked, +/// skipped, a guide, a Shaper group's part that isn't shown), the click goes on to the art below. +#[allow(clippy::too_many_arguments)] +fn drawn_hit( + parent: &Node, + art: &[Node], + p: Point, + opt: HitOptions, + symbols: &SymbolBoxes, + skip: &dyn Fn(NodeId) -> bool, + chain: &mut Vec, + editable_only: bool, +) -> Option { + let _off = DrawnOff::set(); + let mut found = None; + let mut accept = |id: NodeId, kind: HitKind| { + found = member_chain(parent, id, opt, skip, editable_only).map(|path| (path, kind)); + found.is_some() + }; + if !art.iter().rev().any(|a| art_hit(a, p, opt, symbols, &mut accept)) { + return None; + } + let (path, kind) = found?; + let leaf = path.last().copied().unwrap_or(parent.id); + chain.extend(path); + Some(Hit { leaf, ancestry: chain.clone(), kind, contents_of: None, layers: 1 }) +} + +/// The ids from a child of `parent` down to its member `id`, when a click may hit each of them +/// ([`may_reach`], and not passed over by `skip`); empty when `id` is `parent` itself, `parent` is +/// not a layer and `skip` does not pass over it. `None` otherwise, and when `id` is not in `parent`. +fn member_chain(parent: &Node, id: NodeId, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option> { + // A layer's own fills and strokes are not an object to select. + if id == parent.id { + return (!skip(id) && !parent.is_layer()).then(Vec::new); + } + let mut steps = vec![]; + if !path_to(parent, id, &mut steps) { + return None; + } + let reachable = steps.iter().all(|(n, i, c)| may_reach(n, *i, c, opt, editable_only) && !skip(c.id)); + reachable.then(|| steps.iter().map(|(_, _, c)| c.id).collect()) +} + +/// Each container from `n` down to its member `id`, with the index and the child it holds on the +/// way, into `path`. `false` when `id` is not in `n`. +fn path_to<'a>(n: &'a Node, id: NodeId, path: &mut Vec<(&'a Node, usize, &'a Node)>) -> bool { + for (i, c) in n.children().into_iter().flatten().enumerate() { + path.push((n, i, c)); + if c.id == id || path_to(c, id, path) { + return true; + } + path.pop(); + } + false +} + +/// The locked object [`locked_objects_at`] lists for member `id` of `parent`: the outermost object +/// with its own lock on, from a child of `parent` down to `id`, when a click may reach each of them +/// ([`may_reach`] with locked objects counted) and none is a locked or template layer, as +/// [`locked_children`] goes down. `None` otherwise. +fn locked_member(parent: &Node, id: NodeId, opt: HitOptions) -> Option { + let mut steps = vec![]; + if !path_to(parent, id, &mut steps) { + return None; + } + for (n, i, c) in steps { + if !may_reach(n, i, c, opt, false) || c.is_layer() && (c.locked || c.is_template()) { + return None; + } + if c.locked { + return Some(c.id); + } + } + None +} + +/// Does a click at `p` hit an object of `art` (the art [`drawn_art`] gives) that `accept` takes? The +/// objects are tried front first, the members of an Intertwine group in the order they are drawn at +/// `p` ([`hit_order`]), and `accept` is given the id and the hit kind of each object hit until it +/// takes one. +fn art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, accept: &mut dyn FnMut(NodeId, HitKind) -> bool) -> bool { + if !n.visible { + return false; + } + if !edits_contents(n) && n.extras().shaper.is_none() && n.reach_bounds_with(symbols).is_some_and(|b| !b.inflate(opt.tol, opt.tol).contains(p)) { + return false; + } + match &n.kind { + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Intertwine { children } => { + // A layer with Preview off is clicked in outline, as [`hit_children`] clicks it. + let opt = HitOptions { outline: opt.outline || previews_off(n), ..opt }; + if n.clips() + && let Some(clip) = children.first() + { + // The selection tools take a clipping path on its outline before the art it clips, + // as [`hit_children`] does. + if opt.clip_outlines + && clip.visible + && let Some(kind) = clip_outline(clip, p, opt) + && accept(clip.id, kind) + { + return true; + } + if !clip_contains(clip, p, opt.outline) { + return false; + } + } + hit_order(n, children, p).any(|i| children.get(i).is_some_and(|c| !shaper_hides(n, i, None) && art_hit(c, p, opt, symbols, accept))) + } + _ => hit_leaf(n, p, opt, symbols).is_some_and(|kind| accept(n.id, kind)), + } +} + /// The order a click at `p` tries the children of `parent` in, front first: their stacking order /// from the top, except that in an Intertwine group the members are tried in the order they are /// drawn at `p`, from the top ([`crate::intertwine::tier_at`]). @@ -964,10 +1327,17 @@ thread_local! { /// What a click at `p` hits on leaf object `n`: its outline, strokes and fills, its frame or its /// bounds, by kind. Raster effects (drop shadows, glows, blurs) do not take clicks: the area they /// paint beyond the object is left out here and in [`cull_reach`], so a click there reaches the -/// object under it. +/// object under it. Except in outline, a path or compound path with geometry effects is hit by the +/// art they draw ([`drawn_art`]), its own geometry only where that art lies. fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option { #[cfg(test)] LEAVES_TESTED.with(|c| c.set(c.get() + 1)); + // A path or compound path whose geometry effects reshape it is hit where its art is drawn, and + // not where its own geometry no longer paints. + if let Some(art) = drawn_art(symbols, n, opt.outline) { + let _off = DrawnOff::set(); + return art.iter().rev().find_map(|a| hit_any(a, p, opt, symbols)); + } match &n.kind { NodeKind::Path { path, rule, .. } => { if opt.outline @@ -1121,24 +1491,36 @@ fn on_type_path(n: &Node, t: &crate::TextObject, p: Point, tol: f64) -> bool { stroke_contains(&path.to_bezpath(), 0.0, tol, p) } -/// Hit anywhere in an evaluated subtree (groups recurse; leaves use [`hit_leaf`]). +/// Hit anywhere in an evaluated subtree (groups recurse; leaves use [`hit_leaf`]). In symbol art +/// placed by [`FindPart`], each object visited takes one object of the [`ArtWalk`] limit, and +/// nothing more is tested once the limit is used up. fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option { // Hidden art does not hit. - if !n.visible { + if !n.visible || ArtWalk::charged() && !ArtWalk::take(1) { return None; } // Nor art whose reach does not hold `p`, as in [`may_hit`]: a blend's steps far from `p` are // passed by without being measured. - if !edits_contents(n) && n.extras().shaper.is_none() && n.reach_bounds_with(symbols).is_some_and(|b| !b.inflate(opt.tol, opt.tol).contains(p)) { + if !edits_contents(n) + && n.extras().shaper.is_none() + && drawn_reach(symbols, n, n.reach_bounds_with(symbols)).is_some_and(|b| !b.inflate(opt.tol, opt.tol).contains(p)) + { return None; } + // A group whose own geometry effects reshape its members hits where that art is drawn. + if matches!(n.kind, NodeKind::Group { .. }) + && let Some(art) = drawn_art(symbols, n, opt.outline) + { + let _off = DrawnOff::set(); + return art.iter().rev().find_map(|a| hit_any(a, p, opt, symbols)); + } match &n.kind { // A clip group only hits inside its clipping path. NodeKind::Group { children, clip } => { if *clip && children.first().is_some_and(|c| !clip_contains(c, p, opt.outline)) { return None; } - children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols)) + children.iter().enumerate().rev().find_map(|(i, c)| plain(i == 0 && *clip, || hit_any(c, p, opt, symbols))) } // An intertwine group hits by its members, as on the canvas. NodeKind::Intertwine { children } => children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols)), @@ -1257,8 +1639,12 @@ struct FindPart<'a> { } impl FindPart<'_> { + /// What a click at `p` hits on object `n` of the art, placed. [`hit_any`] takes `n` and each + /// object it visits inside `n` from the [`ArtWalk`] limit. fn hit(&self, n: &Node, whole: Option, opt: HitOptions) -> Option { - self.art.place(n, whole).and_then(|n| hit_any(&n, self.p, opt, self.symbols)) + let placed = self.art.place(n, whole)?; + let _charged = ArtWalk::charge(); + hit_any(&placed, self.p, opt, self.symbols) } fn skips_guide(&self, n: &Node) -> bool { @@ -1268,7 +1654,7 @@ impl FindPart<'_> { /// What a click at `p` hits on object `n` of the art, with `path` the child indices that lead /// to what it hits. `outline`: the view is in Outline, or a layer around `n` has Preview off. fn find(&self, n: &Node, path: &mut Vec, whole: Option, outline: bool) -> Option { - if !n.visible || !self.whole_instance && (n.locked || n.is_template()) || self.skips_guide(n) || !ArtWalk::take(1) { + if !n.visible || !self.whole_instance && (n.locked || n.is_template()) || self.skips_guide(n) || ArtWalk::used_up() { return None; } let outline = outline || previews_off(n); @@ -1277,6 +1663,9 @@ impl FindPart<'_> { if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH { return self.hit(n, whole, opt); } + if !ArtWalk::take(1) { + return None; + } let whole = self.art.whole(n, whole); if n.clips() && let Some(first) = children.first() @@ -1303,7 +1692,7 @@ impl FindPart<'_> { } let Ok(i) = u32::try_from(i) else { continue }; path.push(i); - if let Some(kind) = self.find(c, path, whole, outline) { + if let Some(kind) = plain(i == 0 && n.clips(), || self.find(c, path, whole, outline)) { return Some(kind); } path.pop(); @@ -1370,6 +1759,8 @@ thread_local! { /// How many more objects of symbol art the click or marquee under way may visit ([`ArtWalk`]), /// `None` outside one. static ART_WALK_LEFT: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// Whether [`hit_any`] is testing symbol art that [`FindPart`] placed ([`ArtWalk::charge`]). + static ART_WALK_CHARGED: std::cell::Cell = const { std::cell::Cell::new(false) }; } #[cfg(test)] @@ -1420,6 +1811,19 @@ impl ArtWalk { ART_WALK_LEFT.set(Some(rest.unwrap_or(0))); rest.is_some() } + + /// While the guard lives, each object [`hit_any`] visits takes one object from what is left: + /// [`FindPart`] holds one while it tests a placed object of symbol art, so that the members of an + /// Intertwine group, and the objects of groups nested deeper than + /// [`crate::symbol_overrides::MAX_PATH_DEPTH`], count toward the limit. + fn charge() -> ArtWalkCharge { + ArtWalkCharge { was: ART_WALK_CHARGED.replace(true) } + } + + /// Does [`hit_any`] take the objects it visits from what is left ([`Self::charge`])? + fn charged() -> bool { + ART_WALK_CHARGED.get() + } } impl Drop for ArtWalk { @@ -1430,6 +1834,17 @@ impl Drop for ArtWalk { } } +/// The guard of [`ArtWalk::charge`]. +struct ArtWalkCharge { + was: bool, +} + +impl Drop for ArtWalkCharge { + fn drop(&mut self) { + ART_WALK_CHARGED.set(self.was); + } +} + /// Is `n` below a layer whose Preview is off, so that the canvas draws it in outline? As for clicks /// ([`path_options`]), the Preview of the isolated container `scope` and of the layers around it /// does not count. @@ -1599,7 +2014,9 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option { /// clipping mask counts only when the marquee meets the region its clipping path clips to, and then /// only within that region's bounds. In isolation mode the clipping mask of the isolated container, /// or of the parent of the single object isolated, does not limit the marquee, as it does not limit -/// the selection tools' clicks. +/// the selection tools' clicks. Except in outline, a path or compound path with geometry effects, and +/// the members of a group or layer with geometry effects of its own, are touched where the art those +/// effects draw lies ([`set_drawn_art`]), as clicks hit them. pub fn marquee(doc: &Document, r: Rect, scope: Option, leaves: bool) -> Vec { marquee_with(doc, r, scope, leaves, false, false) } @@ -1625,25 +2042,30 @@ fn previews_off(n: &Node) -> bool { fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, whole_compounds: bool, outline: bool) -> Vec { let _walk = ArtWalk::open(); let mut out = Vec::new(); + let symbols = doc.symbol_boxes(); // The objects the marquee may touch ([`Top`]). let tops: Vec = match scope.and_then(|s| doc.node(s)) { // Isolated art whose layer, or a group around it, was locked or hidden afterwards: the // marquee touches none of it, as clicks don't (#5309). Some(s) if !doc.is_editable(s.id) => vec![], Some(s) => match s.children() { - Some(c) => c - .iter() - .enumerate() - .filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope)) - .map(|(_, c)| (c, Some(r), outline, None)) - .collect(), + Some(c) => { + // In an isolated clip group, its members by their own geometry, as clicks take + // them ([`edits_inside`]). + let drawn = if s.clips() { None } else { touched_in_art(s, &symbols, r, whole_compounds, outline || previews_off(s)) }; + c.iter() + .enumerate() + .filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope)) + .map(|(_, c)| (c, Some(r), outline, None, drawn.clone())) + .collect() + } // A single object isolated: only it. None => doc .parent_of(s.id) .and_then(|p| doc.node(p)) .and_then(|p| p.children()) .into_iter() - .flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, Some(r), outline, None))) + .flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, Some(r), outline, None, None))) .collect(), }, // The objects of the layers, looking through sublayers (hidden, locked and template ones @@ -1652,36 +2074,80 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh .layers .iter() .filter(|l| l.visible && !l.locked && !l.is_template() && doc.pattern_edit.as_ref().is_none_or(|e| e.layer == l.id)) - .flat_map(|l| layer_objects(l, r, outline)) + .flat_map(|l| layer_objects(l, &symbols, r, outline, whole_compounds, None)) .collect(), }; /// The objects of layer `l`, each with the part of `r` that the clipping masks of `l` and of /// the sublayers it is in leave, whether it is in outline, and for the clipping mask of `l`, /// `r` for its edge test. The clipping mask itself counts by its own geometry within its plain - /// shapes ([`mask_marquee`]). - fn layer_objects(l: &Node, r: Rect, outline: bool) -> Vec> { + /// shapes ([`mask_marquee`]). In a layer whose own geometry effects reshape its art, each object + /// comes with the objects that art touches ([`touched_in_art`]), `drawn` when a layer around + /// `l` has such effects. + fn layer_objects<'a>( + l: &'a Node, + s: &SymbolBoxes, + r: Rect, + outline: bool, + whole_compounds: bool, + drawn: Option>>, + ) -> Vec> { let mut out = vec![]; let outline = outline || previews_off(l); + let drawn = drawn.or_else(|| touched_in_art(l, s, r, whole_compounds, outline)); let inner = marquee_in_parent(l, r, outline); for (i, c) in l.children().into_iter().flatten().enumerate() { if c.is_layer() { - if let Some(inner) = inner + if let Some(inner) = if drawn.is_some() { Some(r) } else { inner } && c.visible && !c.locked && !c.is_template() { - out.extend(layer_objects(c, inner, outline)); + out.extend(layer_objects(c, s, inner, outline, whole_compounds, drawn.clone())); } } else if !c.is_ruler_guide() { - if i == 0 && l.clips() { - out.push((c, mask_marquee(l, r), outline, Some(r))); + if drawn.is_some() { + out.push((c, Some(r), outline, None, drawn.clone())); + } else if i == 0 && l.clips() { + out.push((c, mask_marquee(l, r), outline, Some(r), None)); } else if inner.is_some() { - out.push((c, inner, outline, None)); + out.push((c, inner, outline, None, None)); } } } out } + /// The ids of the objects of the art that group or layer `n` draws with its own geometry + /// effects ([`drawn_art`]) that the marquee `r` touches, as [`collect_leaves`] collects them. + /// `None` in outline and when it has no such effects. + fn touched_in_art(n: &Node, s: &SymbolBoxes, r: Rect, whole_compounds: bool, outline: bool) -> Option>> { + let art = drawn_art(s, n, outline)?; + let _off = DrawnOff::set(); + let mut ids = vec![]; + for a in art.iter().filter(|a| a.visible) { + collect_leaves(a, s, r, None, whole_compounds, false, &mut ids); + } + Some(Rc::new(ids.into_iter().collect())) + } + /// The objects inside `n` that a marquee collects ([`collect_leaves`]) whose ids are in + /// `drawn` ([`touched_in_art`]), into `out`: leaves, and groups whose own fills and strokes + /// the art paints there. + fn collect_drawn(n: &Node, drawn: &HashSet, scope: Option, out: &mut Vec) { + for (i, c) in n.children().into_iter().flatten().enumerate() { + if !c.visible || c.locked || shaper_hides(n, i, scope) { + continue; + } + if is_leaf(c) { + if drawn.contains(&c.id) { + out.push(c.id); + } + } else { + if drawn.contains(&c.id) && !c.is_layer() { + out.push(c.id); + } + collect_drawn(c, drawn, scope, out); + } + } + } /// The part of `r` in which the marquee can touch the clipping path of `parent` by its own /// geometry: within the bounds of its plain shapes ([`marquee_in`]), where clicks find its /// outline too ([`clip_outline_hit`]), whatever its live effects do to the region it clips to. @@ -1714,6 +2180,12 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh /// compound paths, layers and groups are touched by their box. A clipping path is touched by /// its own geometry ([`mask_marquee`]) and on the edge of its region ([`clip_edge_touches`]). fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool, outline: bool) -> bool { + // A path or compound path whose geometry effects reshape it, or a group or layer whose own + // geometry effects reshape its members, is touched where that art is drawn ([`drawn_art`]). + if let Some(art) = drawn_art(s, n, outline || previews_off(n)) { + let _off = DrawnOff::set(); + return art.iter().any(|a| a.visible && touches(a, s, r, None, whole_compounds, false)); + } match &n.kind { NodeKind::Path { path, .. } => vectorcraft_geom::hit::intersects_rect(path, r), NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => { @@ -1723,7 +2195,8 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh c.visible && !shaper_hides(n, i, scope) && if i == 0 && n.clips() { - mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)) || clip_edge_touches(c, r, outline) + plain(true, || mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline))) + || clip_edge_touches(c, r, outline) } else { inner.is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)) } @@ -1777,6 +2250,15 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh match &n.kind { NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => { let outline = outline || previews_off(n); + // The members that the art its own geometry effects draw touches, and a group whose + // own fills and strokes that art paints, as clicks hit it ([`member_chain`]). + if let Some(drawn) = touched_in_art(n, s, r, whole_compounds, outline) { + if drawn.contains(&n.id) && !n.is_layer() { + out.push(n.id); + } + collect_drawn(n, &drawn, scope, out); + return; + } let inner = marquee_in_parent(n, r, outline); for (i, c) in children.iter().enumerate() { if !c.visible || c.locked || shaper_hides(n, i, scope) { @@ -1785,7 +2267,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh if i == 0 && n.clips() { let before = out.len(); if let Some(r) = mask_marquee(n, r) { - collect_leaves(c, s, r, scope, whole_compounds, outline, out); + plain(true, || collect_leaves(c, s, r, scope, whole_compounds, outline, out)); } if out.len() == before && is_leaf(c) && clip_edge_touches(c, r, outline) { out.push(c.id); @@ -1802,12 +2284,33 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh } } } - let symbols = doc.symbol_boxes(); let locks = doc.locked_artboards(); - for (t, r, outline, edge) in tops { + for (t, r, outline, edge, drawn) in tops { if !t.visible || t.locked || locks.holds_id(t.id) { continue; } + // In a layer or isolated container whose own geometry effects reshape its art: by what + // that art touches. + if let Some(drawn) = drawn { + if !leaves { + let mut touched = false; + t.walk(&mut |n| touched |= drawn.contains(&n.id)); + if touched { + out.push(t.id); + } + } else { + // A leaf, or a group whose own fills and strokes the art paints, and its members. + if drawn.contains(&t.id) && !t.is_layer() { + out.push(t.id); + } + if !is_leaf(t) { + collect_drawn(t, &drawn, scope, &mut out); + } + } + continue; + } + // A layer's clipping mask counts by its own geometry ([`plain`]). + let _mask = edge.is_some().then(DrawnOff::set); if leaves { let before = out.len(); if let Some(r) = r { @@ -1827,8 +2330,10 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh /// An object a marquee may touch ([`marquee_with`]): the object, the part of the marquee in which /// it can be touched (`None` when nowhere), whether it is in outline, and for the clipping mask of a -/// layer, the marquee whose edge test it also takes (`clip_edge_touches`). -type Top<'a> = (&'a std::sync::Arc, Option, bool, Option); +/// layer, the marquee whose edge test it also takes (`clip_edge_touches`), and in a layer or an +/// isolated container whose own geometry effects reshape its art, the ids of the objects of that art +/// the marquee touches (`touched_in_art`). +type Top<'a> = (&'a std::sync::Arc, Option, bool, Option, Option>>); /// The part of a marquee `r` in which it can touch the children of `parent`. For a clip group or a /// layer with a clipping mask, this is what [`marquee_in_clip`] returns for the plain shapes of its diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 74bd959a7f..39efd78795 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -307,6 +307,423 @@ fn hovers_past_more_clip_groups_than_the_boxes_kept_evaluate_few_again() { assert!(again < groups / 8, "{again} of {groups} regions evaluated again"); } +/// A stand-in for the engine's [`DrawnArt`]: an object with a visible effect named `test.shift` +/// draws 100 pt to the right of its own place, and one with a visible effect named `test.copy` +/// draws at its own place and 100 pt to the right. The effects are applied innermost first, and +/// the art keeps the ids of the objects it is drawn from. An instance of a symbol whose art has a +/// visible effect draws as a 50 pt square from (100, 0), white with a black 1 pt stroke. A clip +/// group with a visible effect named `test.mask_only` draws as a group of its clipping path alone, +/// as the engine's art for a clip group whose clipping path's strokes have geometry effects is. +/// Without any of these, no geometry effect changes what an object draws. +fn shifted_art(s: &SymbolBoxes<'_>, n: &Node) -> Option { + if n.clips() + && n.appearance.effects.iter().any(|e| e.visible && e.id == "test.mask_only") + && let Some(mask) = n.children().and_then(|c| c.first()) + { + return Some(Node::group(n.id, vec![mask.clone()])); + } + fn draw(s: &SymbolBoxes<'_>, n: &Node, found: &mut bool) -> Node { + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind + && s.has_effects(symbol) + { + *found = true; + return Node::path(n.id, shapes::rectangle(Rect::new(100.0, 0.0, 150.0, 50.0)), Appearance::default_art()); + } + let mut m = n.clone(); + if let Some(children) = m.children_mut() { + for c in children.iter_mut() { + *c = Arc::new(draw(s, c, found)); + } + } + let has = |id: &str| n.appearance.effects.iter().any(|e| e.visible && e.id == id); + let (shift, copy) = (has("test.shift"), has("test.copy")); + m.appearance.effects.retain(|e| e.id != "test.shift" && e.id != "test.copy"); + *found |= shift || copy; + let shifted = |m: &Node| moved(m, vectorcraft_geom::Affine::translate((100.0, 0.0))); + if shift { + shifted(&m) + } else if copy { + Node::group(n.id, vec![Arc::new(shifted(&m)), Arc::new(m)]) + } else { + m + } + } + let mut found = false; + let art = draw(s, n, &mut found); + found.then_some(art) +} + +/// A visible effect named `id`. +fn effect(id: &str) -> crate::Effect { + crate::Effect { id: id.into(), params: serde_json::json!({}), visible: true } +} + +/// A 50 pt square at `x`, `y`, white with a black 1 pt stroke. +fn square(d: &mut Document, x: f64, y: f64) -> Node { + Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 50.0, y + 50.0)), Appearance::default_art()) +} + +/// The leaf and the kind a click at (`x`, `y`) hits. +fn hit_at(d: &Document, x: f64, y: f64, opt: HitOptions) -> Option<(NodeId, HitKind)> { + hit_test(d, Point::new(x, y), opt).map(|h| (h.leaf, h.kind)) +} + +/// A path that a geometry effect moves is clicked where it is drawn, and not at its own place, +/// which it no longer paints; with Object Selection by Path Only on its drawn outline, not its +/// fill. Outline view draws no effects: there its own outline is clicked. Hidden, the effect no +/// longer moves what clicks hit. +#[test] +fn a_click_hits_a_paths_shifted_art_not_its_source() { + set_drawn_art(shifted_art); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let mut p = square(&mut d, 0.0, 0.0); + p.appearance.effects.push(effect("test.shift")); + let a = p.id; + d.insert(Some(l), 0, p).unwrap(); + let opt = HitOptions::default(); + assert_eq!(hit_at(&d, 125.0, 25.0, opt), Some((a, HitKind::Fill)), "where it is drawn"); + assert_eq!(hit_at(&d, 25.0, 25.0, opt), None, "its own place"); + assert_eq!(objects_at(&d, Point::new(125.0, 25.0), opt, None), [a]); + assert!(objects_at(&d, Point::new(25.0, 25.0), opt, None).is_empty()); + let path_only = HitOptions { path_only: true, ..opt }; + assert_eq!(hit_at(&d, 125.0, 25.0, path_only), None, "path only: the drawn fill"); + assert_eq!(hit_at(&d, 100.0, 25.0, path_only), Some((a, HitKind::Stroke)), "path only: the drawn outline"); + let outline = HitOptions { outline: true, ..opt }; + assert_eq!(hit_at(&d, 0.5, 25.0, outline), Some((a, HitKind::Outline)), "outline: its own outline"); + assert_eq!(hit_at(&d, 100.5, 25.0, outline), None, "outline: no drawn art"); + d.node_mut(a).unwrap().appearance.effects[0].visible = false; + assert_eq!(hit_at(&d, 25.0, 25.0, opt), Some((a, HitKind::Fill)), "hidden effect: its own place"); + assert_eq!(hit_at(&d, 125.0, 25.0, opt), None, "hidden effect: nothing drawn there"); +} + +/// A geometry effect that copies a path is clicked on the copy and on the path, the topmost of the +/// stack first. The pointer moving over it evaluates its art once until it changes, and a path +/// without effects is not evaluated. +#[test] +fn a_click_hits_a_paths_copy_and_evaluates_its_art_once_until_it_changes() { + set_drawn_art(shifted_art); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let below = square(&mut d, 100.0, 0.0); + let mut p = square(&mut d, 0.0, 0.0); + p.appearance.effects.push(effect("test.copy")); + let (a, b) = (p.id, below.id); + d.insert(Some(l), 0, below).unwrap(); + d.insert(Some(l), 1, p).unwrap(); + let evaluated = || DRAWN_EVALUATED.with(std::cell::Cell::get); + let before = evaluated(); + let opt = HitOptions::default(); + for _ in 0..3 { + assert_eq!(hit_at(&d, 25.0, 25.0, opt).map(|h| h.0), Some(a), "the path"); + assert_eq!(hit_at(&d, 125.0, 25.0, opt).map(|h| h.0), Some(a), "its copy, over the square below"); + } + assert_eq!(objects_at(&d, Point::new(125.0, 25.0), opt, None), [a, b]); + assert_eq!(evaluated(), before + 1, "evaluated once"); + if let Some(NodeKind::Path { path, .. }) = d.node_mut(a).map(|n| &mut n.kind) { + *path = shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 50.0)); + } + assert_eq!(hit_at(&d, 140.0, 25.0, opt).map(|h| h.0), Some(b), "narrowed, the copy leaves the square below"); + assert_eq!(evaluated(), before + 2, "evaluated again after it changed"); + // The square below has no effects: it is never evaluated. + assert_eq!(hit_at(&d, 145.0, 45.0, opt).map(|h| h.0), Some(b)); + assert_eq!(evaluated(), before + 2); +} + +/// A group without effects or fills and strokes of its own is not evaluated as a whole: a click +/// on the art of a moved member in it evaluates that member only, and finds the group by it. +#[test] +fn a_click_in_a_plain_group_evaluates_only_its_member_with_effects() { + set_drawn_art(shifted_art); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let mut moved = square(&mut d, 0.0, 0.0); + moved.appearance.effects.push(effect("test.shift")); + let still = square(&mut d, 0.0, 100.0); + let (a, g) = (moved.id, d.alloc_id()); + d.insert(Some(l), 0, Node::group(g, vec![Arc::new(moved), Arc::new(still)])).unwrap(); + let evaluated = || DRAWN_EVALUATED.with(std::cell::Cell::get); + let before = evaluated(); + let opt = HitOptions::default(); + for _ in 0..3 { + assert_eq!(hit_at(&d, 125.0, 25.0, opt), Some((a, HitKind::Fill))); + assert_eq!(objects_at(&d, Point::new(125.0, 25.0), opt, None), [g]); + } + assert_eq!(evaluated(), before + 1, "only the member with effects, once"); +} + +/// A compound path that a geometry effect moves keeps its hole where it is drawn, for clicks and +/// marquees. +#[test] +fn a_compound_paths_shifted_art_keeps_its_hole() { + set_drawn_art(shifted_art); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let outer = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 60.0, 60.0)), Appearance::default()); + let hole = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 40.0, 40.0)), Appearance::default()); + let c = d.alloc_id(); + let mut compound = Node::new(c, NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(hole)], rule: FillRule::EvenOdd }); + compound.appearance = Appearance::default_art().into(); + compound.appearance.effects.push(effect("test.shift")); + d.insert(Some(l), 0, compound).unwrap(); + let opt = HitOptions::default(); + assert_eq!(hit_at(&d, 105.0, 5.0, opt), Some((c, HitKind::Fill)), "its drawn fill"); + assert_eq!(hit_at(&d, 130.0, 30.0, opt), None, "its drawn hole"); + assert_eq!(hit_at(&d, 5.0, 5.0, opt), None, "its own place"); + assert_eq!(marquee(&d, Rect::new(155.0, 25.0, 165.0, 35.0), None, false), [c], "a marquee across the drawn edge"); + assert!(marquee(&d, Rect::new(-5.0, 25.0, 5.0, 35.0), None, false).is_empty(), "a marquee across its own edge"); +} + +/// A marquee touches a path that a geometry effect moves where it is drawn, and not at its own +/// place; in Outline view, at its own place. +#[test] +fn a_marquee_touches_a_paths_shifted_art_not_its_source() { + set_drawn_art(shifted_art); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let mut p = square(&mut d, 0.0, 0.0); + p.appearance.effects.push(effect("test.shift")); + let a = p.id; + d.insert(Some(l), 0, p).unwrap(); + let (drawn, own) = (Rect::new(140.0, 40.0, 160.0, 60.0), Rect::new(40.0, 40.0, 60.0, 60.0)); + for leaves in [false, true] { + assert_eq!(marquee(&d, drawn, None, leaves), [a], "where it is drawn"); + assert!(marquee(&d, own, None, leaves).is_empty(), "its own place"); + assert!(marquee_in_view(&d, drawn, None, leaves, true).is_empty(), "outline: no drawn art"); + assert_eq!(marquee_in_view(&d, own, None, leaves, true), [a], "outline: its own place"); + } +} + +/// A group whose own geometry effect moves its members is clicked where each member is drawn: the +/// member, inside the group, is hit, and a locked member lets the click through to what is below +/// and is listed for unlocking there. A marquee there touches the group, or the member for Direct +/// Selection. +#[test] +fn a_groups_own_effect_moves_where_its_members_are_hit() { + set_drawn_art(shifted_art); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let below = square(&mut d, 150.0, 0.0); + let (a, b) = (square(&mut d, 0.0, 0.0), square(&mut d, 50.0, 0.0)); + let (below_id, a_id, b_id, g) = (below.id, a.id, b.id, d.alloc_id()); + let mut group = Node::group(g, vec![Arc::new(a), Arc::new(b)]); + group.appearance.effects.push(effect("test.shift")); + d.insert(Some(l), 0, below).unwrap(); + d.insert(Some(l), 1, group).unwrap(); + let opt = HitOptions::default(); + let h = hit_test(&d, Point::new(125.0, 25.0), opt).unwrap(); + assert_eq!((h.leaf, h.top_object(None)), (a_id, g), "the first member, drawn there"); + assert_eq!(h.ancestry, [l, g, a_id]); + assert_eq!(hit_at(&d, 175.0, 25.0, opt).map(|h| h.0), Some(b_id), "the second member, over the square below"); + assert_eq!(hit_at(&d, 25.0, 25.0, opt), None, "the first member's own place"); + assert_eq!(objects_at(&d, Point::new(175.0, 25.0), opt, None), [g, below_id]); + let drawn = Rect::new(195.0, 20.0, 205.0, 30.0); + assert_eq!(marquee(&d, drawn, None, false), [below_id, g]); + assert_eq!(marquee(&d, drawn, None, true), [below_id, b_id]); + assert!(marquee(&d, Rect::new(-5.0, 20.0, 5.0, 30.0), None, true).is_empty(), "the members' own place"); + d.node_mut(b_id).unwrap().locked = true; + assert_eq!(hit_at(&d, 175.0, 25.0, opt).map(|h| h.0), Some(below_id), "a locked member lets the click through"); + assert_eq!(marquee(&d, drawn, None, true), [below_id], "nor does a marquee collect it"); + assert_eq!(locked_objects_at(&d, Point::new(175.0, 25.0), opt), [b_id], "the Unlock submenu lists it where it is drawn"); + assert!(locked_objects_at(&d, Point::new(75.0, 25.0), opt).is_empty(), "and not at its own place"); + // Outline view draws no effects: the members are clicked at their own places. + let outline = HitOptions { outline: true, ..opt }; + assert_eq!(hit_at(&d, 0.5, 25.0, outline).map(|h| h.0), Some(a_id)); +} + +/// A layer whose own geometry effect moves its art is clicked and marqueed where the art is +/// drawn. With the layer's Preview off, its art is clicked at its own place, in outline. +#[test] +fn a_layers_own_effect_moves_where_its_art_is_hit() { + set_drawn_art(shifted_art); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let a = square(&mut d, 0.0, 0.0); + let a_id = a.id; + d.insert(Some(l), 0, a).unwrap(); + d.node_mut(l).unwrap().appearance.effects.push(effect("test.shift")); + let opt = HitOptions::default(); + assert_eq!(hit_at(&d, 125.0, 25.0, opt), Some((a_id, HitKind::Fill)), "where it is drawn"); + assert_eq!(hit_at(&d, 25.0, 25.0, opt), None, "its own place"); + assert_eq!(objects_at(&d, Point::new(125.0, 25.0), opt, None), [a_id]); + assert!(objects_at(&d, Point::new(25.0, 25.0), opt, None).is_empty()); + let (drawn, own) = (Rect::new(145.0, 20.0, 155.0, 30.0), Rect::new(-5.0, 20.0, 5.0, 30.0)); + for leaves in [false, true] { + assert_eq!(marquee(&d, drawn, None, leaves), [a_id], "a marquee where it is drawn"); + assert!(marquee(&d, own, None, leaves).is_empty(), "a marquee at its own place"); + } + if let Some(NodeKind::Layer { preview, .. }) = d.node_mut(l).map(|n| &mut n.kind) { + *preview = false; + } + assert_eq!(hit_at(&d, 0.5, 25.0, opt), Some((a_id, HitKind::Outline)), "preview off: its own outline"); + assert_eq!(hit_at(&d, 125.0, 25.0, opt), None, "preview off: no drawn art"); + assert_eq!(marquee(&d, own, None, false), [a_id], "preview off: a marquee at its own place"); +} + +/// In a layer whose own geometry effect moves its art, a sublayer with Preview off is clicked in +/// outline: on the outline of its art where the art is drawn, not inside its fill. +#[test] +fn a_preview_off_sublayer_of_an_effected_layer_is_clicked_in_outline() { + set_drawn_art(shifted_art); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let sub = d.alloc_id(); + d.insert(Some(l), 0, Node::layer(sub, "Sub", crate::LayerColor::Preset(2))).unwrap(); + let a = square(&mut d, 0.0, 0.0); + let a_id = a.id; + d.insert(Some(sub), 0, a).unwrap(); + d.node_mut(l).unwrap().appearance.effects.push(effect("test.shift")); + let opt = HitOptions::default(); + assert_eq!(hit_at(&d, 125.0, 25.0, opt), Some((a_id, HitKind::Fill)), "preview on: inside its fill"); + if let Some(NodeKind::Layer { preview, .. }) = d.node_mut(sub).map(|n| &mut n.kind) { + *preview = false; + } + assert_eq!(hit_at(&d, 125.0, 25.0, opt), None, "preview off: inside its fill"); + assert_eq!(hit_at(&d, 100.5, 25.0, opt), Some((a_id, HitKind::Outline)), "preview off: on its outline"); +} + +/// A group with fills and strokes of its own around an instance of a symbol whose art has an +/// effect is clicked where its art is drawn, though no object in the group has an effect. +#[test] +fn a_painted_group_around_an_effected_symbols_instance_is_hit_where_its_art_is_drawn() { + set_drawn_art(shifted_art); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let mut art = square(&mut d, 0.0, 0.0); + art.appearance.effects.push(effect("test.raster")); + d.symbols.push(crate::Symbol { dynamic: false, name: "Effected".into(), art: Arc::new(art) }); + let (g, inst) = (d.alloc_id(), d.alloc_id()); + let instance = Node::new(inst, NodeKind::SymbolInstance { symbol: "Effected".into(), xf: vectorcraft_geom::Affine::IDENTITY }); + let mut group = Node::group(g, vec![Arc::new(instance)]); + group.appearance = Appearance::default_art().into(); + d.insert(Some(l), 0, group).unwrap(); + let opt = HitOptions::default(); + assert_eq!(hit_at(&d, 125.0, 25.0, opt), Some((inst, HitKind::Fill)), "where its art is drawn"); + assert_eq!(objects_at(&d, Point::new(125.0, 25.0), opt, None), [g]); +} + +/// In a layer with fills and strokes of its own whose art is evaluated for a member's geometry +/// effect, an Intertwine group's members are still clicked in the order they are drawn at the +/// click: where the lower member is woven over the upper one, the click takes the lower member. +#[test] +fn an_intertwine_group_in_a_layers_drawn_art_is_hit_in_its_woven_order() { + set_drawn_art(shifted_art); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + d.node_mut(l).unwrap().appearance = Appearance::default_art().into(); + let mut a = square(&mut d, 0.0, 100.0); + a.extras_mut().intertwine = Some(Box::new(shapes::rectangle(Rect::new(25.0, 100.0, 50.0, 150.0)))); + let b = square(&mut d, 25.0, 100.0); + let (a_id, b_id, g) = (a.id, b.id, d.alloc_id()); + d.insert(Some(l), 0, Node::new(g, NodeKind::Intertwine { children: vec![Arc::new(a), Arc::new(b)] })).unwrap(); + let mut moved = square(&mut d, 200.0, 0.0); + moved.appearance.effects.push(effect("test.shift")); + d.insert(Some(l), 1, moved).unwrap(); + let opt = HitOptions::default(); + assert_eq!(hit_at(&d, 40.0, 125.0, opt), Some((a_id, HitKind::Fill)), "where the lower member is woven over"); + assert_eq!(hit_at(&d, 60.0, 125.0, opt), Some((b_id, HitKind::Fill)), "where the upper member is drawn over"); +} + +/// The clipping path of a clip group and of a clipping layer is still marqueed by its own geometry +/// when a geometry effect moves what it draws. +#[test] +fn a_clipping_path_keeps_its_own_geometry_under_a_geometry_effect() { + set_drawn_art(shifted_art); + let edge = Rect::new(-5.0, 40.0, 5.0, 60.0); + // A clip group. + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(effect("test.shift")); + let (g, mask_id, art_id) = (d.alloc_id(), mask.id, art.id); + let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + d.insert(Some(l), 0, clip).unwrap(); + assert_eq!(marquee(&d, edge, None, true), [mask_id, art_id], "clip group"); + // A clipping layer. + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(effect("test.shift")); + let (mask_id, art_id) = (mask.id, art.id); + let layer = d.node_mut(l).unwrap(); + if let NodeKind::Layer { children, clip, .. } = &mut layer.kind { + (*children, *clip) = (vec![Arc::new(mask), Arc::new(art)], true); + } + assert_eq!(marquee(&d, edge, None, true), [mask_id, art_id], "clipping layer"); +} + +/// The selection tools take the clipping path of a clip group whose own geometry effect moves it +/// on its outline where it is drawn, before the art it clips, and not at its own place. +#[test] +fn a_clip_groups_own_effect_moves_where_its_mask_outline_is_hit() { + set_drawn_art(shifted_art); + let mut d = Document::new(400.0, 200.0); + let l = d.layers[0].id; + let (mask, art) = half_clipped(&mut d); + let (g, mask_id, art_id) = (d.alloc_id(), mask.id, art.id); + let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + clip.appearance.effects.push(effect("test.shift")); + d.insert(Some(l), 0, clip).unwrap(); + let tools = HitOptions { clip_outlines: true, ..HitOptions::default() }; + assert_eq!(hit_at(&d, 199.5, 50.0, tools), Some((mask_id, HitKind::Outline)), "the drawn edge, over the art"); + assert_eq!(hit_at(&d, 150.0, 50.0, tools).map(|h| h.0), Some(art_id), "the drawn art inside the mask"); + assert_eq!(hit_at(&d, 0.5, 50.0, tools), None, "the mask's own edge"); + // The same clip group in a group whose own effect moves it. + let mut d = Document::new(400.0, 200.0); + let l = d.layers[0].id; + let (mask, art) = half_clipped(&mut d); + let (g, mask_id, art_id) = (d.alloc_id(), mask.id, art.id); + let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + let mut outer = Node::group(d.alloc_id(), vec![Arc::new(clip)]); + outer.appearance.effects.push(effect("test.shift")); + d.insert(Some(l), 0, outer).unwrap(); + assert_eq!(hit_at(&d, 199.5, 50.0, tools), Some((mask_id, HitKind::Outline)), "in a moved group: the drawn edge, over the art"); + assert_eq!(hit_at(&d, 150.0, 50.0, tools).map(|h| h.0), Some(art_id), "in a moved group: the drawn art"); +} + +/// In isolation mode in a clip group whose own geometry effect moves it, the selection tools take +/// the art outside the clipping mask by its own geometry, for a marquee as for a click. +#[test] +fn an_isolated_clip_group_with_its_own_effect_is_marqueed_by_its_members_own_geometry() { + set_drawn_art(shifted_art); + let mut d = Document::new(400.0, 200.0); + let l = d.layers[0].id; + let (mask, art) = half_clipped(&mut d); + let (g, art_id) = (d.alloc_id(), art.id); + let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + clip.appearance.effects.push(effect("test.shift")); + d.insert(Some(l), 0, clip).unwrap(); + let tools = HitOptions { clip_outlines: true, scope: Some(g), ..HitOptions::default() }; + assert_eq!(hit_at(&d, 150.0, 50.0, tools).map(|h| h.0), Some(art_id), "a click outside the mask"); + let edge = Rect::new(190.0, 40.0, 210.0, 60.0); + for leaves in [false, true] { + assert_eq!(marquee(&d, edge, Some(g), leaves), [art_id], "a marquee across its own edge outside the mask"); + } +} + +/// A clip group whose drawn art holds only its clipping path still has the art it clips clicked +/// inside the mask. +#[test] +fn a_clip_groups_art_is_hit_when_its_drawn_art_holds_only_the_clipping_path() { + set_drawn_art(shifted_art); + let mut d = Document::new(400.0, 200.0); + let l = d.layers[0].id; + let (mask, art) = half_clipped(&mut d); + let (g, art_id) = (d.alloc_id(), art.id); + let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + clip.appearance.effects.push(effect("test.mask_only")); + d.insert(Some(l), 0, clip).unwrap(); + let opt = HitOptions::default(); + assert_eq!(hit_at(&d, 50.0, 50.0, opt), Some((art_id, HitKind::Fill)), "inside the mask"); + assert_eq!(objects_at(&d, Point::new(50.0, 50.0), opt, None), [g]); + assert!(hit_at(&d, 150.0, 50.0, opt).is_none(), "outside the mask"); +} + /// Every test of a clip group by its clipping path follows the region a live effect moved it to: /// the selected art hidden by the mask, a click into a group holding the clip group, the locked /// objects under the pointer, and, below a clipping layer whose Preview is on, art on a sublayer @@ -1452,6 +1869,76 @@ fn objects_at_edit_contents_uses_general_order() { assert_eq!(objects_at(&d, p, opt, None), vec![b, a]); } +/// Select Behind keeps one limit of symbol art to walk when it falls back to the general +/// traversal, for an envelope in Edit Contents and for a root that is not a layer: the fallback +/// walks no more art than what the first pass left, and keeps what the first pass found. +#[test] +fn select_behind_keeps_one_art_limit_when_it_falls_back() { + // 60 instances of `Clipped` with the rectangle hidden, which a click at (150, 50) walks the art + // of and misses: each walk takes 3 objects of the 100. + let stack = |d: &mut Document, count: usize| { + let l = d.layers[0].id; + for _ in 0..count { + let inst = instance_of(d, "Clipped"); + d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(inst)).unwrap(); + } + }; + // An envelope in Edit Contents at the bottom of the layer, its contents under (150, 50). + let envelope = |d: &mut Document| { + let inner = |id| Arc::new(Node::path(id, shapes::rectangle(Rect::new(120.0, 20.0, 180.0, 80.0)), Appearance::default_art())); + let (a, b) = (d.alloc_id(), d.alloc_id()); + let e = Node::new( + d.alloc_id(), + NodeKind::Envelope { + content: vec![inner(a), inner(b)], + kind: Box::new(crate::live::EnvelopeKind::Warp { style: "arc".to_string(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }), + fidelity: 100.0, + editing: true, + options: Default::default(), + frame: Box::new(vectorcraft_geom::Affine::IDENTITY), + }, + ); + let l = d.layers[0].id; + d.insert(Some(l), 0, e).unwrap(); + (a, b) + }; + let p = Point::new(150.0, 50.0); + let mut d = Document::new(600.0, 400.0); + clipped_symbol(&mut d, false); + let (a, b) = envelope(&mut d); + stack(&mut d, 60); + let (behind, _, arts) = with_art_limit(100, || objects_at(&d, p, HitOptions::default(), None)); + assert_eq!(behind, vec![b, a]); + assert!(arts <= 34, "envelope in Edit Contents: {arts} instances' art walked"); + // An instance that the first pass hits by its art, the limit then used up, stays in the list: + // `Shown` is `Clipped` with its rectangle shown, below 32 instances of `Clipped`. + let mut d = Document::new(600.0, 400.0); + clipped_symbol(&mut d, false); + let (a, b) = envelope(&mut d); + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(test_move()); + let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + group_symbol(&mut d, "Shown", vec![Arc::new(clip)]); + let hit = instance_of(&mut d, "Shown"); + let hit_id = hit.id; + let l = d.layers[0].id; + d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(hit)).unwrap(); + stack(&mut d, 32); + let (behind, _, arts) = with_art_limit(100, || objects_at(&d, p, HitOptions::default(), None)); + assert_eq!(behind, vec![hit_id, b, a], "hit before the fallback"); + assert!(arts <= 34, "hit before the fallback: {arts} instances' art walked"); + // A root that is not a layer, below the layer. + let mut d = Document::new(600.0, 400.0); + clipped_symbol(&mut d, false); + stack(&mut d, 60); + let root = Arc::new(Node::group(d.alloc_id(), vec![])); + d.layers.insert(0, root); + let (behind, _, arts) = with_art_limit(100, || objects_at(&d, p, HitOptions::default(), None)); + assert!(behind.is_empty()); + assert!(arts <= 34, "root that is not a layer: {arts} instances' art walked"); +} + #[test] fn locked_and_hidden_skip() { let mut d = Document::new(200.0, 200.0); @@ -2140,6 +2627,37 @@ fn a_click_and_a_marquee_walk_repeated_nested_symbol_instances_within_one_limit( assert_eq!(with_art_limit(100, || marquee(&d, edge, None, false)).0, [inst], "marquee across the art's edge"); } +/// The members of an Intertwine group in symbol art count toward the art walk's limit of objects +/// for a click, as the members of a plain group do. A click on a member's path past the instance's +/// box is still found within the limit. +#[test] +fn a_click_counts_the_members_of_an_intertwine_group_in_symbol_art_toward_one_limit() { + set_clip_region(moved_clip_region); + // A clip group whose clipping region `test.move` moves to 100..200 × 0..100, past the 0..100 + // box, over an Intertwine group of 200 squares at 140..160 × 40..60. + let mut d = Document::new(600.0, 400.0); + let l = d.layers[0].id; + let (mut mask, _) = half_clipped(&mut d); + mask.appearance.effects.push(test_move()); + let squares = (0..200) + .map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(140.0, 40.0, 160.0, 60.0)), Appearance::default_art()))) + .collect(); + let woven = Arc::new(Node::new(d.alloc_id(), NodeKind::Intertwine { children: squares })); + let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), woven]); + clip.set_clips(true); + group_symbol(&mut d, "Woven", vec![Arc::new(clip)]); + let inst = instance_of(&mut d, "Woven"); + let id = inst.id; + d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap(); + let opt = HitOptions { path_only: true, ..HitOptions::default() }; + let at = |x: f64| hit_test(&d, Point::new(x, 50.0), opt).map(|h| h.leaf); + // Inside the squares and away from their paths, every member is tested and none is hit. + let (hit, leaves, _) = with_art_limit(100, || at(150.0)); + assert_eq!(hit, None); + assert!(leaves <= 100, "{leaves} leaves tested"); + assert_eq!(with_art_limit(100, || at(140.0)).0, Some(id), "on the squares' paths"); +} + /// In a dynamic symbol's art that placing through its 9-slice guides could make more than /// [`crate::MAX_SYMBOL_NODES`] objects of, Direct Selection picks and outlines nothing, as the /// canvas draws nothing of it. At the art's natural size the same art is picked. diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 7b7ef4fee7..11711b3f1d 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; @@ -28,6 +29,7 @@ pub mod shared; mod symbol_export_type; mod symbol_nine_slice; pub mod symbol_overrides; +mod symbol_pixel_aligned; mod symbol_registration; pub use inline::{SYMBOL_HALF, SYMBOL_SIZES}; pub use shared::Shared; @@ -37,6 +39,7 @@ pub use symbol_nine_slice::{ SymbolNineSlice, charge_symbol_art, }; pub use symbol_overrides::SymbolOverride; +pub use symbol_pixel_aligned::SYMBOL_PIXEL_ALIGNED; pub use symbol_registration::{SYMBOL_REGISTRATION, SymbolRegistration}; pub mod links; pub mod live; @@ -52,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; @@ -94,8 +97,9 @@ pub use compound_shape::ShapeMode; pub use corners::LiveCorners; pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES}; pub use graph::{ - ColumnDesign, ColumnType, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows, LabelStyles, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, - PiePosition, PieSort, SeriesPaint, TickLength, ValueAxisSide, + ColumnDesign, ColumnType, DEFAULT_FILLED_LINE_WIDTH, FILLED_LINE_OUTLINE_WIDTH, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows, + LabelStyles, MAX_FILLED_LINE_WIDTH, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, MIN_FILLED_LINE_WIDTH, PiePosition, PieSort, SeriesPaint, TickLength, + ValueAxisSide, }; pub use hit::{Hit, HitKind}; pub use links::{LinkInfo, PlacementOptions}; 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/live/envelope.rs b/crates/doc/src/live/envelope.rs index 5aa43b0a67..a0ad0eb1e4 100644 --- a/crates/doc/src/live/envelope.rs +++ b/crates/doc/src/live/envelope.rs @@ -316,6 +316,7 @@ fn content_hash(text: &crate::TextObject) -> Option<[u64; 2]> { let inline_bounds = text.runs.iter().filter_map(|r| r.inline.as_ref()).map(|i| i.bounds.map(|b| [b.x0, b.y0, b.x1, b.y1].map(f64::to_bits))); for h in &mut feed.0 { h.write_u8(u8::from(text.first_para_continues)); + h.write_u32(text.first_para_lead.map_or(u32::MAX, u32::from)); for b in inline_bounds.clone() { match b { None => h.write_u8(0), 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/recolor.rs b/crates/doc/src/recolor.rs index 0efa82296a..f25340b29f 100644 --- a/crates/doc/src/recolor.rs +++ b/crates/doc/src/recolor.rs @@ -16,6 +16,11 @@ pub trait ColorVisitor { fn color(&mut self, c: Color) -> Color; /// The key of embedded image `key` recoloured, `None` when it stays as it is. fn image(&mut self, key: &str) -> Option; + /// Whether the pass recolors child `n` of a container: false leaves `n` and everything inside + /// it as they are. + fn enters(&mut self, _n: &Node) -> bool { + true + } } /// What a recolouring pass reaches: fills (including colorized image fills and gradient-mesh @@ -82,6 +87,9 @@ pub fn recolor_node(n: &mut Node, reach: Reach, v: &mut dyn ColorVisitor) -> usi } _ => { for c in n.children_mut().into_iter().flatten() { + if !v.enters(c) { + continue; + } let mut m = (**c).clone(); let k = recolor_node(&mut m, reach, v); if k > 0 { diff --git a/crates/doc/src/selection.rs b/crates/doc/src/selection.rs index 541e7801c2..e97a4b0cc1 100644 --- a/crates/doc/src/selection.rs +++ b/crates/doc/src/selection.rs @@ -50,10 +50,10 @@ pub struct Selection { #[serde(default, skip_serializing_if = "Option::is_none")] pub key_guide: Option, /// The key anchor for Align: one of two or more anchor points selected with Direct Selection, - /// the last one a Shift-click added (path, anchor in [`Self::anchors`]). Align and Distribute - /// move the other selected points relative to it, and it stays in place. Never set with `key` - /// or `key_guide`; [`Self::prune`] clears it when the point is no longer a selected anchor, or - /// fewer than two points are selected. + /// designated by clicking an already-selected anchor point without modifiers (path, anchor in + /// [`Self::anchors`]). Align and Distribute move the other selected points relative to it, and + /// it stays in place. Never set with `key` or `key_guide`; [`Self::prune`] clears it when the + /// point is no longer a selected anchor, or fewer than two points are selected. #[serde(default, skip_serializing_if = "Option::is_none")] pub key_anchor: Option<(NodeId, AnchorRef)>, /// The new art on a locked artboard that this selection keeps editable @@ -311,7 +311,7 @@ impl Selection { let anchor_kept = self.key_anchor.is_some_and(|(id, (si, ai))| { self.objects.contains(&id) && !self.segments.contains_key(&id) - && self.anchors.get(&id).is_some_and(|set| set.contains(&(si, ai))) + && (self.anchors.get(&id).is_some_and(|set| set.contains(&(si, ai))) || !self.anchors.contains_key(&id)) && found .get(&id) .and_then(|p| doc.node_at(p)) 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/doc/src/swatches.rs b/crates/doc/src/swatches.rs index 63951d8104..6d2c14a102 100644 --- a/crates/doc/src/swatches.rs +++ b/crates/doc/src/swatches.rs @@ -384,14 +384,14 @@ pub fn override_paints(n: &Node) -> impl Iterator { n.extras().symbol_overrides.iter().flat_map(|o| [o.fill.as_ref(), o.stroke.as_ref()]).flatten() } -/// The paints a graph keeps for its series and its labels ([`crate::graph::GraphSpec`]), which its -/// marks and labels take each time it is drawn again and which [`node_paints`] leaves out. +/// The paints a graph keeps for its series, its labels and its lines ([`crate::graph::GraphSpec`]), which +/// its marks, labels and lines take each time it is drawn again and which [`node_paints`] leaves out. pub fn graph_paints(n: &Node) -> impl Iterator { let g = n.extras().graph.as_deref(); let series = g.into_iter().flat_map(|g| &g.series_paints).flat_map(|s| [s.fill.as_ref(), s.stroke.as_ref()]).flatten(); let labels = g.into_iter().flat_map(|g| [&g.label_styles.values, &g.label_styles.categories, &g.label_styles.legend]).flatten(); let l = g.map(|g| &g.label_styles); - let rows = l.into_iter().flat_map(|l| [&l.values_rows, &l.categories_rows, &l.legend_rows]).flatten(); + let rows = l.into_iter().flat_map(|l| [&l.values_rows, &l.categories_rows, &l.legend_rows, &l.axis_rows, &l.ring_rows]).flatten(); series.chain(labels.flat_map(|st| [&st.fill, &st.stroke])).chain(rows.flat_map(|r| [r.paint.fill.as_ref(), r.paint.stroke.as_ref()]).flatten()) } @@ -400,7 +400,7 @@ fn graph_paints_mut(g: &mut crate::graph::GraphSpec) -> impl Iterator, _: &mut f32| s.as_deref() == Some("Brand") && std::mem::replace(c, blue) != blue; - assert_eq!(d.map_solid_paints(&mut to_blue), 5); + assert_eq!(d.map_solid_paints(&mut to_blue), 7); let g = d.node(a).unwrap().extras().graph.clone().unwrap(); assert_eq!(g.series_paints[0].fill, Some(linked(blue, "Brand"))); assert_eq!(g.series_paints[0].stroke, Some(linked(blue, "Brand"))); let legend = g.label_styles.legend.unwrap(); assert_eq!((legend.fill, legend.stroke), (linked(blue, "Brand"), Paint::None)); assert_eq!(g.label_styles.values_rows.unwrap().paint.fill, Some(linked(blue, "Brand"))); + assert_eq!(g.label_styles.axis_rows.unwrap().paint.stroke, Some(linked(blue, "Brand"))); + assert_eq!(g.label_styles.ring_rows.unwrap().paint.stroke, Some(linked(blue, "Brand"))); let mut cleared = |p: &Paint| (*p == linked(blue, "Brand")).then_some(Paint::None); - assert_eq!(d.map_paints(&mut cleared), 5, "the fill and the graph's four"); + assert_eq!(d.map_paints(&mut cleared), 7, "the fill and the graph's six"); assert!(graph_paints(d.node(a).unwrap()).all(Paint::is_none)); } diff --git a/crates/doc/src/symbol_pixel_aligned.rs b/crates/doc/src/symbol_pixel_aligned.rs new file mode 100644 index 0000000000..6eb9d226dc --- /dev/null +++ b/crates/doc/src/symbol_pixel_aligned.rs @@ -0,0 +1,80 @@ +//! Symbol Options › Align to Pixel Grid: a symbol whose instances stay on the pixel grid at their +//! actual size wherever they are placed +//! (). +//! +//! Stored under [`SYMBOL_PIXEL_ALIGNED`] keyed by symbol name; a symbol that is not pixel-aligned +//! (the default) is left out of the map. + +use std::collections::HashSet; + +use crate::Document; + +/// Document unknown key: `{ symbolName: true }` for each pixel-aligned symbol. +pub const SYMBOL_PIXEL_ALIGNED: &str = "symbolPixelAligned"; + +impl Document { + /// Whether symbol `name` has Symbol Options › Align to Pixel Grid on (default: off). + pub fn symbol_pixel_aligned(&self, name: &str) -> bool { + self.unknown.get(SYMBOL_PIXEL_ALIGNED).and_then(|m| m.get(name)).and_then(serde_json::Value::as_bool).unwrap_or(false) + } + + /// Turn Align to Pixel Grid on or off for symbol `name`. Off removes the symbol from the map, + /// and the map goes when it is empty. + pub fn set_symbol_pixel_aligned(&mut self, name: &str, on: bool) { + if on { + let m = self.unknown.entry(SYMBOL_PIXEL_ALIGNED.to_string()).or_insert_with(|| serde_json::json!({})); + if let Some(o) = m.as_object_mut() { + o.insert(name.into(), serde_json::json!(true)); + } + return; + } + let Some(o) = self.unknown.get_mut(SYMBOL_PIXEL_ALIGNED).and_then(|m| m.as_object_mut()) else { return }; + o.remove(name); + if o.is_empty() { + self.unknown.remove(SYMBOL_PIXEL_ALIGNED); + } + } + + /// Move the stored setting when a symbol is renamed. + pub fn rename_symbol_pixel_aligned(&mut self, from: &str, to: &str) { + if from == to { + return; + } + let on = self.symbol_pixel_aligned(from); + self.set_symbol_pixel_aligned(from, false); + self.set_symbol_pixel_aligned(to, on); + } + + /// The names of the pixel-aligned symbols the document holds (empty for most documents). + pub fn pixel_aligned_symbols(&self) -> HashSet { + let Some(o) = self.unknown.get(SYMBOL_PIXEL_ALIGNED).and_then(|m| m.as_object()) else { return HashSet::new() }; + o.iter() + .filter(|(name, v)| v.as_bool() == Some(true) && self.symbols.iter().any(|s| &s.name == *name)) + .map(|(name, _)| name.clone()) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_setting_is_off_by_default_and_follows_a_rename() { + let mut d = Document::new(100.0, 100.0); + let art = std::sync::Arc::new(crate::Node::group(d.alloc_id(), vec![])); + d.symbols.push(crate::Symbol { dynamic: false, name: "A".into(), art }); + assert!(!d.symbol_pixel_aligned("A")); + assert!(d.unknown.get(SYMBOL_PIXEL_ALIGNED).is_none()); + d.set_symbol_pixel_aligned("A", true); + assert!(d.symbol_pixel_aligned("A")); + assert_eq!(d.pixel_aligned_symbols(), HashSet::from(["A".to_string()])); + d.symbols[0].name = "B".into(); + d.rename_symbol_pixel_aligned("A", "B"); + assert!(!d.symbol_pixel_aligned("A")); + assert!(d.symbol_pixel_aligned("B")); + d.set_symbol_pixel_aligned("B", false); + assert!(d.unknown.get(SYMBOL_PIXEL_ALIGNED).is_none()); + assert!(d.pixel_aligned_symbols().is_empty()); + } +} diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index d165a086fb..6863960230 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -18,8 +18,8 @@ mod wrap; pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape}; use char_style::yes; pub use char_style::{ - CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, GlyphForm, MAX_AKI, MAX_TSUME, MAX_WARICHU_GAP, ScriptMetrics, - WARICHU_LINES, WARICHU_SCALE, WarichuAlign, + CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, GlyphForm, MAX_AKI, MAX_DIACRITIC_POSITION, MAX_TSUME, + MAX_WARICHU_GAP, ScriptMetrics, WARICHU_LINES, WARICHU_SCALE, WarichuAlign, }; pub use composite::{ COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX, CharClass, @@ -35,7 +35,7 @@ pub use tabs_lists::{ Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, NumberStyle, ParaList, TabAlign, TabStop, }; -pub use wrap::{resolve_wrap, wrap_work}; +pub use wrap::{resolve_wrap, wrap_outline, wrap_sources, wrap_work}; /// A text object. `runs` split into paragraphs at `\n`. /// @@ -67,6 +67,12 @@ pub struct TextObject { /// it on a frame that leaves its thread and on a copy. Not saved. #[serde(skip)] pub first_para_continues: bool, + /// Threaded text whose first paragraph continues ([`TextObject::first_para_continues`]): the + /// last character of that paragraph in the frames before that a repeat mark could stand for + /// (Kurikaeshi Moji Shori), or None. The engine sets it with `first_para_continues`; layout + /// reads it only while `first_para_continues` is on. Not saved. + #[serde(skip)] + pub first_para_lead: Option, /// Area Type Options (area type only). #[serde(default, skip_serializing_if = "crate::skip::is_default")] pub area: AreaOptions, diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs index 41fbf168ae..a8fdfbe535 100644 --- a/crates/doc/src/text/char_style.rs +++ b/crates/doc/src/text/char_style.rs @@ -48,8 +48,10 @@ pub struct CharStyle { /// of the character's ink, inside its own width, that is taken away, 0 to [`MAX_TSUME`]. 50 /// halves that space and 100 sets the ink edge to edge; the glyph itself is not scaled. A /// cluster takes the value of its first character. Tracking, kerning and Insert Aki are added - /// after it. Horizontal type only. + /// after it. In vertical type an upright character is measured above and below its ink, inside + /// its cell down the column. /// + /// #[serde(default, skip_serializing_if = "crate::skip::is_default")] pub tsume: f64, /// Use glyph shapes for automatic pair spacing; false uses font metrics. @@ -180,6 +182,18 @@ pub struct CharStyle { /// these characters are drawn in, whatever digits were typed. #[serde(default, skip_serializing_if = "crate::skip::is_default")] pub digits: Digits, + /// Adjust Horizontal Diacritic Position (Character panel, Middle Eastern options): the font's + /// mark glyphs among these characters (GDEF class 3, such as Arabic harakat and Hebrew points) + /// move right by a positive value and left by a negative one, relative to their letters, in + /// 1/1000 em of the size, from -[`MAX_DIACRITIC_POSITION`] to [`MAX_DIACRITIC_POSITION`]. + /// Saved only when not 0. + /// + #[serde(default, rename = "diacriticHorizontal", skip_serializing_if = "crate::skip::is_default")] + pub diacritic_horizontal: f64, + /// Adjust Vertical Diacritic Position: the mark glyphs move up by a positive value and down by + /// a negative one, as [`Self::diacritic_horizontal`] moves them across. + #[serde(default, rename = "diacriticVertical", skip_serializing_if = "crate::skip::is_default")] + pub diacritic_vertical: f64, /// Font height reference (Character panel menu › Show Font Height Options): the height of the /// font that [`Self::size`] measures, the em box by default. #[serde(default, rename = "fontHeightReference", skip_serializing_if = "crate::skip::is_default")] @@ -553,6 +567,10 @@ pub const MAX_AKI: f64 = 1000.0; /// The largest Tsume ([`CharStyle::tsume`]), in percent: all the blank space beside the ink. pub const MAX_TSUME: f64 = 100.0; +/// The largest Adjust Horizontal or Vertical Diacritic Position either way +/// ([`CharStyle::diacritic_horizontal`]), in 1/1000 em: one em. +pub const MAX_DIACRITIC_POSITION: f64 = 1000.0; + /// The number of lines a warichu block may be stacked on ([`CharStyle::warichu_lines`]). pub const WARICHU_LINES: std::ops::RangeInclusive = 1..=6; @@ -684,6 +702,8 @@ impl Default for CharStyle { warichu_align: WarichuAlign::Auto, small_caps: None, digits: Digits::Default, + diacritic_horizontal: 0.0, + diacritic_vertical: 0.0, font_height_reference: FontHeightReference::EmBox, no_break: false, language: None, @@ -707,7 +727,8 @@ impl CharStyle { /// same way. The Warichu Settings Lines and Scale /// are kept to [`WARICHU_LINES`] and [`WARICHU_SCALE`]; a gap or scale that is not a number becomes its default. The gap is kept to 0 to /// [`crate::MAX_COORD`], as the baseline shift is, since a scaled type object holds it in its - /// own units. + /// own units. The Adjust Horizontal and Vertical Diacritic Positions are kept within + /// [`MAX_DIACRITIC_POSITION`] either way, and one that is not a number becomes 0. pub fn keep_dimensions_in_range(&mut self) { let default = Self::default(); let within = |v: f64, or: f64| if v > 0.0 { v.min(crate::MAX_COORD) } else { or }; @@ -723,6 +744,9 @@ impl CharStyle { self.aki_left = aki(self.aki_left); self.aki_right = aki(self.aki_right); self.tsume = if self.tsume.is_nan() { 0.0 } else { self.tsume.clamp(0.0, MAX_TSUME) }; + let diacritic = |v: f64| if v.is_nan() { 0.0 } else { v.clamp(-MAX_DIACRITIC_POSITION, MAX_DIACRITIC_POSITION) }; + self.diacritic_horizontal = diacritic(self.diacritic_horizontal); + self.diacritic_vertical = diacritic(self.diacritic_vertical); self.warichu_lines = self.warichu_lines.clamp(*WARICHU_LINES.start(), *WARICHU_LINES.end()); self.warichu_gap = if self.warichu_gap.is_nan() { default.warichu_gap } else { self.warichu_gap.clamp(0.0, crate::MAX_COORD) }; self.warichu_scale = diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index b787cebfe0..5bd31f7699 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -94,6 +94,7 @@ impl TextObject { para: ParaStyle::default(), paras: Vec::new(), first_para_continues: false, + first_para_lead: None, area: AreaOptions::default(), path_effect: PathEffect::default(), path_align: PathAlign::default(), @@ -511,6 +512,8 @@ impl crate::Document { st.aki_left = num("akiLeft").unwrap_or(st.aki_left); st.aki_right = num("akiRight").unwrap_or(st.aki_right); st.tsume = num("tsume").unwrap_or(st.tsume); + st.diacritic_horizontal = num("diacriticHorizontal").unwrap_or(st.diacritic_horizontal); + st.diacritic_vertical = num("diacriticVertical").unwrap_or(st.diacritic_vertical); st.warichu_gap = num("warichuGap").unwrap_or(st.warichu_gap); st.warichu_scale = num("warichuScale").unwrap_or(st.warichu_scale); st.keep_dimensions_in_range(); @@ -537,6 +540,8 @@ impl crate::Document { ("akiLeft", Some(st.aki_left)), ("akiRight", Some(st.aki_right)), ("tsume", Some(st.tsume)), + ("diacriticHorizontal", Some(st.diacritic_horizontal)), + ("diacriticVertical", Some(st.diacritic_vertical)), ("leading", st.leading), ]; for (k, v) in kept { diff --git a/crates/doc/src/text/para_style.rs b/crates/doc/src/text/para_style.rs index c3db242ed0..62c6b8dd33 100644 --- a/crates/doc/src/text/para_style.rs +++ b/crates/doc/src/text/para_style.rs @@ -271,6 +271,9 @@ pub struct ParaStyle { /// dashes, two ellipses, two two-dot leaders, a vertical kana repeat mark's two halves). Kept /// with kinsoku None, where it has no effect. Off by default. pub bunri_kinshi: bool, + /// Kurikaeshi Moji Shori (Paragraph panel menu): a repeat mark (々, ゝ, ゞ, ヽ or ヾ) that starts + /// a line is drawn as the character it repeats, and the text keeps the mark. Off by default. + pub kurikaeshi_moji_shori: bool, /// Roman Hanging Punctuation (Paragraph panel menu): quotation marks, hyphens, full stops and /// commas starting or ending a line hang outside the margin, and asterisks, tildes, ellipses, /// dashes, colons and semicolons hang by half. East Asian punctuation hangs by burasagari. @@ -375,6 +378,8 @@ struct ParaStyleFile { #[serde(default, skip_serializing_if = "crate::skip::is_default")] bunri_kinshi: bool, #[serde(default, skip_serializing_if = "crate::skip::is_default")] + kurikaeshi_moji_shori: bool, + #[serde(default, skip_serializing_if = "crate::skip::is_default")] roman_hanging: bool, #[serde(default, skip_serializing_if = "crate::skip::is_default")] kashida: Kashida, @@ -412,6 +417,7 @@ impl From for ParaStyleFile { kinsoku, kinsoku_type, bunri_kinshi, + kurikaeshi_moji_shori, roman_hanging, kashida, korean_line_break_anywhere, @@ -439,6 +445,7 @@ impl From for ParaStyleFile { kinsoku, kinsoku_type, bunri_kinshi, + kurikaeshi_moji_shori, roman_hanging, kashida, korean_line_break_anywhere, @@ -470,6 +477,7 @@ impl From for ParaStyle { kinsoku, kinsoku_type, bunri_kinshi, + kurikaeshi_moji_shori, roman_hanging, kashida, korean_line_break_anywhere, @@ -496,6 +504,7 @@ impl From for ParaStyle { kinsoku, kinsoku_type, bunri_kinshi, + kurikaeshi_moji_shori, roman_hanging, kashida, korean_line_break_anywhere, diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index 0976edbb93..a5230d5d86 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -129,6 +129,42 @@ fn insert_aki_is_saved_only_when_set() { assert_eq!((d.char_styles[0].attrs["akiLeft"].as_f64(), d.char_styles[0].attrs["akiRight"].as_f64()), (Some(MAX_AKI), Some(0.0))); } +/// Adjust Horizontal and Vertical Diacritic Position are 0 by default and saved only when not 0, +/// each on its own; styles written before them read as 0, and a value out of range from a file is +/// kept within one em either way. +#[test] +fn diacritic_positions_are_saved_only_when_set() { + let st = CharStyle::default(); + assert_eq!((st.diacritic_horizontal, st.diacritic_vertical), (0.0, 0.0)); + let saved = serde_json::to_value(&st).unwrap(); + assert!(saved.get("diacriticHorizontal").is_none() && saved.get("diacriticVertical").is_none()); + for set in [ + CharStyle { diacritic_horizontal: -250.0, ..CharStyle::default() }, + CharStyle { diacritic_vertical: 500.0, ..CharStyle::default() }, + CharStyle { diacritic_horizontal: 12.5, diacritic_vertical: -1000.0, ..CharStyle::default() }, + ] { + let saved = serde_json::to_value(&set).unwrap(); + assert_eq!(saved.get("diacriticHorizontal").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.diacritic_horizontal); + assert_eq!(saved.get("diacriticVertical").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.diacritic_vertical); + assert_eq!(saved.get("diacriticHorizontal").is_some(), set.diacritic_horizontal != 0.0); + assert_eq!(saved.get("diacriticVertical").is_some(), set.diacritic_vertical != 0.0); + assert_eq!(serde_json::from_value::(saved).unwrap(), set); + } + let mut damaged = CharStyle { diacritic_horizontal: -4000.0, diacritic_vertical: 4000.0, ..CharStyle::default() }; + damaged.keep_dimensions_in_range(); + assert_eq!((damaged.diacritic_horizontal, damaged.diacritic_vertical), (-MAX_DIACRITIC_POSITION, MAX_DIACRITIC_POSITION)); + let mut damaged = CharStyle { diacritic_horizontal: f64::NAN, diacritic_vertical: f64::NEG_INFINITY, ..CharStyle::default() }; + damaged.keep_dimensions_in_range(); + assert_eq!((damaged.diacritic_horizontal, damaged.diacritic_vertical), (0.0, -MAX_DIACRITIC_POSITION)); + // A character style from a file is kept in range the same way. + let mut d = crate::Document::new(100.0, 100.0); + let attrs = serde_json::json!({"diacriticHorizontal": 5000, "diacriticVertical": -5000}); + d.char_styles.push(TextStyleDef { name: "Moved".into(), attrs: attrs.as_object().cloned().unwrap_or_default() }); + d.keep_type_values_in_range(); + let kept = |key: &str| d.char_styles[0].attrs[key].as_f64(); + assert_eq!((kept("diacriticHorizontal"), kept("diacriticVertical")), (Some(MAX_DIACRITIC_POSITION), Some(-MAX_DIACRITIC_POSITION))); +} + /// Tsume is 0 by default and saved only when not 0; styles written before it read as 0, and a /// value out of range from a file, in a run or a character style, is kept from 0 to 100. #[test] diff --git a/crates/doc/src/text/wrap.rs b/crates/doc/src/text/wrap.rs index 0b5fe45dc2..15a0fbbd40 100644 --- a/crates/doc/src/text/wrap.rs +++ b/crates/doc/src/text/wrap.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use vectorcraft_geom::{PathData, shapes}; -use super::{TextKind, WrapShape}; +use super::{TextKind, TextObject, WrapShape}; use crate::{Document, Node, NodeId, NodeKind}; /// Outline of a wrap object in document coordinates: its paths, or its bounds for other art. @@ -32,6 +32,16 @@ fn outline(n: &Node, out: &mut PathData) { } } +/// The outline area type wraps around for wrap object `n`, in document coordinates, as +/// [`resolve_wrap`] makes it: a path's subpaths that are closed or have more than two anchors, those +/// of the shown members of a group or compound path, a clip group's clipping object's, and the +/// bounds of other art. Empty when `n` has none. +pub fn wrap_outline(n: &Node) -> PathData { + let mut pd = PathData::default(); + outline(n, &mut pd); + pd +} + enum Item<'a> { Wrap(&'a Node), Text(&'a Node), @@ -82,6 +92,57 @@ pub fn wrap_work(doc: &Document) -> usize { total } +/// Each area text object of `layer`, from the top down, with the wrap objects above it in the +/// layer whose outlines aren't empty, topmost first, each with the shape its outline makes in +/// document coordinates. Each wrap object's outline is made once. +fn each_text<'a>(layer: &'a Node, mut f: impl FnMut(&'a Node, &[(&'a Node, WrapShape)])) { + let mut items = vec![]; + collect(layer, &mut items); + let mut above: Vec<(&Node, WrapShape)> = vec![]; + for it in items.iter().rev() { + match it { + Item::Wrap(n) => { + let mut pd = PathData::default(); + outline(n, &mut pd); + if !pd.is_empty() { + above.push((n, WrapShape { path: pd, wrap: n.extras().wrap.unwrap_or_default() })); + } + } + Item::Text(n) => f(n, &above), + } + } +} + +/// The wrap shapes of text object `t` (text space) from `above`, the wrap objects above it as +/// [`each_text`] gives them: bottom first. +fn shapes_of(t: &TextObject, above: &[(&Node, WrapShape)]) -> Vec { + let inv = t.xf.inverse(); + above + .iter() + .rev() + .map(|(_, s)| { + let mut path = s.path.clone(); + path.transform(inv); + WrapShape { path, wrap: s.wrap } + }) + .collect() +} + +/// Each area text object on `doc`'s layers that [`resolve_wrap`] gives wrap shapes, with the wrap +/// objects whose outlines make them, bottom first, and those shapes (text space), as +/// [`resolve_wrap`] works them out. The copying is [`wrap_work`]. +pub fn wrap_sources<'a>(doc: &'a Document, mut f: impl FnMut(&'a Node, Vec<&'a Node>, Vec)) { + for layer in &doc.layers { + each_text(layer, |n, above| { + if let NodeKind::Text(t) = &n.kind + && !above.is_empty() + { + f(n, above.iter().rev().map(|(s, _)| *s).collect(), shapes_of(t, above)); + } + }); + } +} + /// Resolve the wrap shapes (`TextObject::wrap`, text space) of each area text object from the /// outlines of the wrap objects above it in its layer. With `before`, the layers it holds unchanged /// are skipped; without it, every layer is resolved. Returns the area text objects whose shapes @@ -95,41 +156,14 @@ pub fn resolve_wrap(before: Option<&Document>, doc: &mut Document) -> Vec = vec![]; - for it in items.iter().rev() { - match it { - Item::Wrap(n) => { - let mut pd = PathData::default(); - outline(n, &mut pd); - if !pd.is_empty() { - above.push(WrapShape { path: pd, wrap: n.extras().wrap.unwrap_or_default() }); - } - } - Item::Text(n) => { - let NodeKind::Text(t) = &n.kind else { continue }; - let inv = t.xf.inverse(); - let shapes: Vec = above - .iter() - .rev() - .map(|s| { - let mut path = s.path.clone(); - path.transform(inv); - WrapShape { path, wrap: s.wrap } - }) - .collect(); - if shapes != t.wrap { - updates.push((n.id, shapes)); - } + each_text(layer, |n, above| { + if let NodeKind::Text(t) = &n.kind { + let shapes = shapes_of(t, above); + if shapes != t.wrap { + updates.push((n.id, shapes)); } } - } + }); } let mut changed = Vec::with_capacity(updates.len()); for (id, shapes) in updates { 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/bake.rs b/crates/effects/src/bake.rs index d8f3ae0fe4..5e95244e26 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -117,6 +117,11 @@ thread_local! { /// The objects of symbol art that [`bake_document`] has baked for instances inside the art of /// other instances, counted against [`crate::SYMBOL_ART_MAX_NODES`]. static NESTED_NODES: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The objects in the baked art of the instances inside the art of other instances that + /// [`bake_node`] baked for one export and then left as they are, counted with + /// [`NESTED_NODES`] against [`crate::SYMBOL_ART_MAX_NODES`] before more art is baked. Never + /// given back. + static NESTED_DROPPED: std::cell::Cell = const { std::cell::Cell::new(0) }; /// While [`bake_document_placing_symbols`] bakes: the symbols whose instances become their /// placed art ([`placed_symbol_art`]). static PLACING: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; @@ -162,7 +167,7 @@ struct Placing { layers: WrittenLayers, } -/// The layers an exporter writes besides the shown, printing ones +/// The layers and objects an exporter writes besides the shown, printing ones /// ([`bake_document_placing_symbols`]). Template layers are never written. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct WrittenLayers { @@ -170,16 +175,19 @@ pub struct WrittenLayers { pub hidden: bool, /// Layers that do not print. pub non_printing: bool, + /// Hidden objects other than layers (written hidden, as SVG writes them when it keeps hidden + /// layers). + pub hidden_objects: bool, } /// Does the export leave `n` and everything in it out, while [`bake_document_placing_symbols`] -/// bakes? A hidden object other than a layer, a template layer, and a hidden layer or a layer +/// bakes? A template layer, and a hidden object other than a layer, a hidden layer or a layer /// that does not print when the export leaves those out ([`WrittenLayers`]). fn unwritten(n: &Node) -> bool { PLACING.with(|p| { p.borrow().as_ref().is_some_and(|p| match n.kind { NodeKind::Layer { template, printable, .. } => template || !(printable || p.layers.non_printing) || !(n.visible || p.layers.hidden), - _ => !n.visible, + _ => !(n.visible || p.layers.hidden_objects), }) }) } @@ -369,17 +377,29 @@ fn bake_object(d: &mut Document, n: &Node) -> Option { }; // Instances baked inside the art of others stop at the depth limit, or once their art // passes the objects one export bakes that way: an instance of a symbol whose art holds - // instances of itself is kept as it is there. + // instances of itself is kept as it is there. The symbol's art is held in the count while + // it bakes, so the instances inside it bake only within what is left; the art it bakes to, + // with what its effects add, then takes its place in the count. When that art does not + // fit, the instance stays as it is, and the art baked for it, with the art dropped for the + // instances inside it, still counts against the instances after it. let instance = matches!(n.kind, NodeKind::SymbolInstance { .. }); - if instance && INSTANCE_DEPTH.with(|c| c.get()) > 0 { + let nested = instance && INSTANCE_DEPTH.with(|c| c.get()) > 0; + let before = NESTED_NODES.with(|c| c.get()); + if nested { let count = symbol.as_ref().map_or(0, |a| a.count() as u64); - let spent = NESTED_NODES.with(|c| c.get()).saturating_add(count); - if INSTANCE_DEPTH.with(|c| c.get()) >= vectorcraft_doc::depth::MAX_DEPTH || spent > crate::SYMBOL_ART_MAX_NODES { + let spent = before.saturating_add(count); + let dropped = NESTED_DROPPED.with(|c| c.get()); + if INSTANCE_DEPTH.with(|c| c.get()) >= vectorcraft_doc::depth::MAX_DEPTH || spent.saturating_add(dropped) > crate::SYMBOL_ART_MAX_NODES { return None; } NESTED_NODES.with(|c| c.set(spent)); } - let m = reshape(Some(d), n, symbol.as_ref())?; + let Some(m) = reshape(Some(d), n, symbol.as_ref()) else { + if nested { + NESTED_NODES.with(|c| c.set(before)); + } + return None; + }; if instance { INSTANCE_DEPTH.with(|c| c.set(c.get() + 1)); } @@ -387,7 +407,17 @@ fn bake_object(d: &mut Document, n: &Node) -> Option { if instance { INSTANCE_DEPTH.with(|c| c.set(c.get() - 1)); } - return Some(baked.unwrap_or(m)); + let baked = baked.unwrap_or(m); + if nested { + let spent = before.saturating_add(baked.count() as u64); + if spent.saturating_add(NESTED_DROPPED.with(|c| c.get())) > crate::SYMBOL_ART_MAX_NODES { + NESTED_NODES.with(|c| c.set(before)); + NESTED_DROPPED.with(|c| c.set(c.get().saturating_add(baked.count() as u64))); + return None; + } + NESTED_NODES.with(|c| c.set(spent)); + } + return Some(baked); } // Symbol instances whose art draws live effects, when the caller asks for them: the art // placed, then baked. When the baked art passes the export's budget, or would draw too deep @@ -653,9 +683,11 @@ fn apart(offsets: &[Vec2], b: Rect) -> bool { /// Type `n` whose own geometry effects only move it ([`transform_moves`]) as a group of the moved /// type ([`moved_type`]). The group keeps `n`'s id, name, visibility, transparency, opacity mask and -/// remaining (raster) effects, and the type in it has none of them. `None` otherwise. +/// remaining (raster) effects, and the type in it has none of them. `None` otherwise, and for type +/// whose copies each carry the raster effects listed before their Transform effect +/// ([`crate::outer_effects`]), which is baked through its outlines as the canvas draws it. fn moved_type_group(n: &Node) -> Option { - if !matches!(n.kind, NodeKind::Text(_)) { + if !matches!(n.kind, NodeKind::Text(_)) || crate::reshape::copied_raster_at(n).is_some() { return None; } let moves = transform_moves(&geometry_effects(n))?; @@ -1014,13 +1046,14 @@ pub fn bake_document(doc: &Document) -> Option { /// (live geometry effects, color adjustments and the rest [`needs_bake`] counts, in its own art or /// in the art of the symbols it places) replaced by that art as the instance places it, baked /// ([`placed_symbol_art`]), so the art draws as on the canvas wherever the instance is. For -/// exporters that write each instance's art in its place (PDF, print, EPS, DXF), rather than -/// writing each symbol once. `clip_slices`: whether 9-slice cells are clipped -/// ([`Document::place_symbol_art`]) or not ([`Document::place_symbol_art_unclipped`]), as the -/// exporter places other instances. `layers`: the hidden layers and layers that do not print -/// that the exporter writes. Instances the export does not write (hidden ones, those in hidden -/// objects, on template layers, and on the layers `layers` leaves out) stay as they are. The -/// symbols' own art is left as it is. +/// exporters that write each instance's art in its place (PDF, print, EPS, DXF, EMF, WMF), and +/// for SVG, which writes the instances of other symbols as one shared definition. `clip_slices`: +/// whether 9-slice cells are clipped ([`Document::place_symbol_art`]) or not +/// ([`Document::place_symbol_art_unclipped`]), as the exporter places other instances. `layers`: +/// the hidden layers, layers that do not print and hidden objects that the exporter writes. +/// Instances the export does not write (template layers, and the hidden objects and layers +/// `layers` leaves out, with what is in them) stay as they are. The symbols' own art is left as +/// it is. pub fn bake_document_placing_symbols(doc: &Document, clip_slices: bool, layers: WrittenLayers) -> Option { bake(doc, Some((clip_slices, vectorcraft_doc::MAX_SYMBOL_NODES, layers))) } @@ -1068,6 +1101,7 @@ fn bake(doc: &Document, placing: Option<(bool, u64, WrittenLayers)>) -> Option bool { d.node(NodeId(id)).is_some_and(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })) @@ -1455,10 +1455,20 @@ fn placing_symbols_skips_instances_the_export_leaves_out() { } // An export that writes the layers that do not print, or the hidden layers, places that // layer's instance first; the template layer's instance is never placed. - for (layers, first) in [(WrittenLayers { non_printing: true, hidden: false }, 921), (WrittenLayers { non_printing: false, hidden: true }, 931)] { + for (layers, first) in + [(WrittenLayers { non_printing: true, ..WrittenLayers::default() }, 921), (WrittenLayers { hidden: true, ..WrittenLayers::default() }, 931)] + { let out = bake(&d, Some((true, each, layers))).unwrap(); assert!(!is_instance(&out, first) && is_instance(&out, 900) && is_instance(&out, 911), "{layers:?}"); } + // An export that writes hidden objects (SVG keeping hidden layers) places the hidden instance + // first, and the instance in the hidden group would come next; the hidden layer's instance + // stays, since that layer is still left out. + let out = bake(&d, Some((true, each, WrittenLayers { hidden_objects: true, ..WrittenLayers::default() }))).unwrap(); + assert!(!is_instance(&out, 901), "the hidden instance is placed"); + for id in [900, 903, 911, 921, 931] { + assert!(is_instance(&out, id), "{id} stays as it is"); + } } /// `leaf` in `levels` groups, with ids from `id` up. @@ -1525,3 +1535,125 @@ fn placing_symbols_counts_art_dropped_for_depth_against_later_baked_art() { let room = bake(&d, Some((true, a + e + f, ALL))).unwrap(); assert!(!is_instance(&room, 900) && !is_instance(&room, 901)); } + +/// Instance `id` of `symbol` with a geometry effect, so baking it reshapes its art. +fn offset_instance(id: u64, symbol: &str) -> Node { + let mut n = instance(id, symbol, vectorcraft_geom::Affine::IDENTITY); + n.appearance.effects.push(fx("path.offsetPath", json!({"offset": 1.0}))); + n +} + +/// `n` baked as an instance inside another instance's art, with `spent` objects of nested symbol +/// art already baked: the baked object, and the objects counted after it, art baked and dropped +/// included. +fn bake_nested(d: &mut Document, n: &Node, spent: u64) -> (Option, u64) { + INSTANCE_DEPTH.with(|c| c.set(1)); + NESTED_NODES.with(|c| c.set(spent)); + NESTED_DROPPED.with(|c| c.set(0)); + let out = bake_node(d, n); + INSTANCE_DEPTH.with(|c| c.set(0)); + (out, NESTED_NODES.with(|c| c.replace(0)).saturating_add(NESTED_DROPPED.with(|c| c.replace(0)))) +} + +/// The object with id `id` in `n`'s subtree. +fn find(n: &Node, id: u64) -> Option<&Node> { + if n.id == NodeId(id) { + return Some(n); + } + n.children().into_iter().flatten().find_map(|c| find(c, id)) +} + +/// Is `n` an object other than a symbol instance? +fn baked(n: Option<&Node>) -> bool { + n.is_some_and(|n| !matches!(n.kind, NodeKind::SymbolInstance { .. })) +} + +/// An instance baked inside another instance's art counts the art it bakes to, the copies its +/// symbol's effects make included: art that fits exactly takes the last of the budget, and art +/// whose symbol fits but whose baked art does not leaves the instance as it is and still counts. +#[test] +fn nested_reshape_counts_baked_art() { + let mut d = Document::new(400.0, 400.0); + add_symbol(&mut d, "Inner", gradient_copies(800)); + let n = offset_instance(900, "Inner"); + let source = d.symbols[0].art.count() as u64; + let (all, spent) = bake_nested(&mut d, &n, 0); + let baked = all.map_or(0, |m| m.count() as u64); + assert!(baked > source + 1, "the copies are objects of their own: {baked} > {source} + 1"); + assert_eq!(spent, baked, "the baked art is counted in place of the symbol's art"); + let max = crate::SYMBOL_ART_MAX_NODES; + let (exact, spent) = bake_nested(&mut d, &n, max - baked); + assert!(exact.is_some(), "{baked} objects fit in {baked}"); + assert_eq!(spent, max); + let (short, spent) = bake_nested(&mut d, &n, max - baked + 1); + assert!(short.is_none(), "the symbol's {source} objects fit, the {baked} baked ones do not"); + assert_eq!(spent, max + 1, "the art baked for the instance left as it is still counts"); +} + +/// An instance left as it is because its baked art does not fit still counts the art baked for +/// it: an instance after it is left as it is too, before its art bakes. +#[test] +fn nested_reshape_refusal_keeps_its_work_counted() { + let mut d = Document::new(400.0, 400.0); + add_symbol(&mut d, "Big", gradient_copies(800)); + add_symbol(&mut d, "Small", moved_square(810)); + let (big, small) = (offset_instance(900, "Big"), offset_instance(901, "Small")); + let count = |d: &mut Document, n: &Node| bake_nested(d, n, 0).0.map_or(0, |m| m.count() as u64); + let (b, s) = (count(&mut d, &big), count(&mut d, &small)); + assert!(s < b, "{s} < {b}"); + let first = crate::SYMBOL_ART_MAX_NODES - b + 1; + let (refused, spent) = bake_nested(&mut d, &big, first); + assert!(refused.is_none(), "the big art passes the budget"); + assert_eq!(spent, first + b, "the big art baked and dropped counts"); + let (later, after) = bake_nested(&mut d, &small, spent); + assert!(later.is_none(), "the small art does not fit after the dropped art"); + assert_eq!(after, spent, "the small instance is refused before it bakes"); +} + +/// Sibling instances inside other instances' art whose baked art each passes what is left: the +/// first is baked and dropped, and its art counts, so the others are left as they are before +/// their art bakes. With room for all of them, every one is baked. +#[test] +fn nested_reshape_refused_siblings_bake_once() { + let mut d = Document::new(400.0, 400.0); + add_symbol(&mut d, "Big", gradient_copies(800)); + let one = offset_instance(900, "Big"); + let b = bake_nested(&mut d, &one, 0).0.map_or(0, |m| m.count() as u64); + let siblings: Vec> = (0..16).map(|i| Arc::new(offset_instance(1000 + i, "Big"))).collect(); + let group = Node::group(NodeId(999), siblings); + let first = crate::SYMBOL_ART_MAX_NODES - b + 1; + let (refused, spent) = bake_nested(&mut d, &group, first); + let refused = refused.unwrap_or_else(|| group.clone()); + assert!((0..16).all(|i| !baked(find(&refused, 1000 + i))), "no sibling fits: {refused:?}"); + assert_eq!(spent, first + b, "only the first sibling's art is baked and counted: {spent}"); + let (room, spent) = bake_nested(&mut d, &group, 0); + let room = room.unwrap_or_else(|| panic!("the siblings are baked")); + assert!((0..16).all(|i| baked(find(&room, 1000 + i))), "every sibling is baked"); + assert_eq!(spent, 16 * b); +} + +/// An instance inside another instance's art whose own art holds a reshaped instance counts that +/// instance's baked art once: a budget of exactly the outer art's baked objects bakes both, and +/// with one object less the art baked and dropped still counts. +#[test] +fn nested_reshape_counts_successful_descendants_once() { + let mut d = Document::new(400.0, 400.0); + add_symbol(&mut d, "Inner", gradient_copies(800)); + let square = Node::path(NodeId(803), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); + add_symbol(&mut d, "Outer", Node::group(NodeId(801), vec![Arc::new(offset_instance(802, "Inner")), Arc::new(square)])); + let outer = offset_instance(900, "Outer"); + let (all, spent) = bake_nested(&mut d, &outer, 0); + let all = all.unwrap_or_else(|| panic!("the outer instance is baked")); + assert!(baked(find(&all, 802)), "the inner instance is baked: {all:?}"); + let total = all.count() as u64; + assert_eq!(spent, total); + let max = crate::SYMBOL_ART_MAX_NODES; + let (exact, spent) = bake_nested(&mut d, &outer, max - total); + let exact = exact.unwrap_or_else(|| panic!("{total} objects fit in {total}")); + assert!(baked(find(&exact, 802)), "the inner instance is baked too"); + assert_eq!(spent, max); + let (short, spent) = bake_nested(&mut d, &outer, max - total + 1); + assert!(short.as_ref().is_none_or(|m| !baked(find(m, 802))), "with one object less, not both are baked"); + assert!(spent > max, "the art baked and dropped counts: {spent}"); + assert!(spent <= max - total + 1 + 2 * total, "at most the outer and the inner art are dropped: {spent}"); +} diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 8e0d63e9d0..ea727b804c 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -182,49 +182,49 @@ pub fn effect_catalog() -> Vec { REVOLVE, "Revolve…", &["Effect", "3D and Materials"], - "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true, close circular ends of open profiles; partial-sweep cut sides stay open), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", + "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[],"render":{"mode":"shaded"}}), ), g( EXTRUDE, "Extrude & Bevel…", &["Effect", "3D and Materials"], - "{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", + "{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}), ), g( INFLATE, "Inflate…", &["Effect", "3D and Materials"], - "{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).", + "{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).", json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"render":{"mode":"shaded"}}), ), g( ROTATE, "Rotate…", &["Effect", "3D and Materials"], - "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.", + "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.", json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}), ), g( CLASSIC_EXTRUDE, "Extrude & Bevel (Classic)…", &["Effect", "3D and Materials", "3D (Classic)"], - "{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.", + "{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.", json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"drawHiddenFaces":false}), ), g( CLASSIC_REVOLVE, "Revolve (Classic)…", &["Effect", "3D and Materials", "3D (Classic)"], - "{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.", + "{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends and a partial sweep's cut sides closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.", json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}), ), g( CLASSIC_ROTATE, "Rotate (Classic)…", &["Effect", "3D and Materials", "3D (Classic)"], - "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none (black; the color the art darkens toward; none keeps the paint), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, with black multiplied and overprinting where the art darkens, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.", + "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the art darkens toward; none keeps the paint; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, with black multiplied and overprinting where the art darkens, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint the art keeps its paint and swatch link whether it is on or off)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.", json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"diffuse","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}), ), g( @@ -267,7 +267,7 @@ pub fn effect_catalog() -> Vec { "distort.transform", "Transform…", DT, - "{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once; on, without copies or random, the raster effects listed before this effect (Rasterize and SVG filters excepted) transform with the art whatever strokes says: their sizes scale by the mean scale and a Drop Shadow's offset turns, reflects and scales, while the angles and light directions of pixel filters stay as they are; so do the raster effects of the object's fills and strokes and, on a group, those of its members, of their fills and strokes and of their linked opacity masks' art, after their own Transform effects, including those that a member's own Transform effect with copies or random holds back), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power; raster effects that transform with the art are not scaled again; on a fill or stroke, the effects listed after this effect in that fill's or stroke's own list keep their distances and apply to the transformed art, and with objects off so do the effects before it)}", + "{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once; on, without copies or random, the raster effects listed before this effect (Rasterize and SVG filters excepted) transform with the art whatever strokes says: their sizes scale by the mean scale, a Drop Shadow's offset turns, reflects and scales, a pixel filter's lightDirection or strokeDirection turns and reflects to the nearest choice (at a tie, the one clockwise of it; VectorCraft's own rule), and Color Halftone's channel angles turn and reflect with the art (0 to 360); so do the raster effects of the object's fills and strokes and, on a group, those of its members, of their fills and strokes and of their linked opacity masks' art, after their own Transform effects, including those that a member's own Transform effect with copies or random holds back), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power; raster effects that transform with the art are not scaled again; on a fill or stroke, the effects listed after this effect in that fill's or stroke's own list keep their distances and apply to the transformed art, and with objects off so do the effects before it)}", json!({"scaleH": 100.0, "scaleV": 100.0, "moveH": 0.0, "moveV": 0.0, "rotate": 0.0, "copies": 0, "reflectX": false, "reflectY": false, "reference": 4, "random": false, "objects": true, "patterns": false, "strokes": false}), ), g( diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index d2a6687dd7..63215d897d 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -367,9 +367,14 @@ fn compound_shape_art_in(doc: Option<&Document>, n: &Node, hook: Option Node { let mut appearance = Appearance { items: src.appearance.items.clone(), ..Default::default() }; if outline { - let fill = src.appearance.fill_paint(); - let paint = if fill.is_none() { src.appearance.stroke_paint() } else { fill }; - appearance = Appearance { items: vec![AppearanceItem::Stroke(StrokeLayer::new(paint, 1.0))], ..Default::default() }; + // The edges take the paint, opacity, blend mode and overprint of the top fill that paints, + // or of the top stroke that paints when no fill does. + let layer = top_painting_fill(&src.appearance).or_else(|| src.appearance.items.iter().rev().find(|i| paints(i))); + let mut stroke = StrokeLayer::new(layer.map_or(Paint::None, |i| i.paint().clone()), 1.0); + if let Some(i) = layer { + (stroke.opacity, stroke.blend, stroke.overprint) = (i.opacity(), i.blend(), i.overprint()); + } + appearance = Appearance { items: vec![AppearanceItem::Stroke(stroke)], ..Default::default() }; } let mut n = Node::path(src.id, path, appearance); n.opacity = src.opacity; @@ -504,7 +509,8 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option f64 { } fn fill_cmyk(src: &Node) -> Option<[f32; 4]> { - let paint = src.appearance.fill_paint(); + // The top fill that paints: a hidden fill adds no color. + let paint = top_painting_fill(&src.appearance)?.paint().clone(); let color = paint.color()?; let tinted = match paint { Paint::Solid { tint, .. } => color.tinted(tint), @@ -637,6 +644,11 @@ fn is_container(n: &Node) -> bool { matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) } +/// The top fill of `a` that paints: hidden fills and fills of no paint are skipped. +fn top_painting_fill(a: &Appearance) -> Option<&AppearanceItem> { + a.items.iter().rev().find(|i| i.is_fill() && paints(i)) +} + /// Does `item` paint anything? pub fn paints(item: &AppearanceItem) -> bool { item.visible() @@ -853,7 +865,11 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { } if !fx.is_empty() { m = crate::reshape::outlined_members(doc, &m); - members_as_drawn(doc, &mut m); + { + // The members' raster effects then follow the group's own Transform effects as well. + let _later = crate::raster::LaterGroups::enter(&n.appearance.effects); + members_as_drawn(doc, &mut m); + } let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc); // The group's own fills and strokes paint the members as a whole: their gradients follow // the effects as the members' do. diff --git a/crates/effects/src/group/tests.rs b/crates/effects/src/group/tests.rs index 50fbf8f759..3b8addadea 100644 --- a/crates/effects/src/group/tests.rs +++ b/crates/effects/src/group/tests.rs @@ -1,6 +1,6 @@ use super::*; use vectorcraft_color::{BlendMode, Color, Paint}; -use vectorcraft_doc::{CharStyle, Effect, NodeId, TextObject}; +use vectorcraft_doc::{CharStyle, Effect, FillLayer, NodeId, TextObject}; use vectorcraft_geom::{Point, Rect, shapes}; /// Type tests need glyph outlines, which only the optional craft-fonts build input provides. @@ -71,6 +71,33 @@ fn trap_effect_adds_an_overprinting_strip_above_the_members() { assert_eq!(fill.paint.color(), Some(yellow)); } +/// Trap takes each member's top fill that paints: a hidden fill on top is skipped, and a member +/// whose only fill is hidden does not take part. +#[test] +fn trap_skips_a_hidden_fill() { + let yellow = Color::cmyk(0.0, 0.0, 1.0, 0.0); + let blue = Color::cmyk(1.0, 0.6, 0.0, 0.0); + let mut hidden = FillLayer::new(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0))); + hidden.visible = false; + let trap = |members: Vec>| { + let mut g = Node::group(NodeId(10), members); + let params = serde_json::json!({"thickness": 1.0, "tintReduction": 100}); + g.appearance.effects.push(Effect { id: crate::trap::TRAP.into(), params, visible: true }); + pathfinder_children(None, &g, None).unwrap() + }; + let mut covered = (*sq(1, 0.0, yellow)).clone(); + covered.appearance.items.push(AppearanceItem::Fill(hidden.clone())); + let out = trap(vec![Arc::new(covered), sq(2, 10.0, blue)]); + assert_eq!(out.len(), 3, "both squares and one trap"); + assert_eq!(out[2].appearance.fill().unwrap().paint.color(), Some(yellow)); + let only_hidden = Node::path( + NodeId(1), + shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), + Appearance { items: vec![AppearanceItem::Fill(hidden)], ..Default::default() }, + ); + assert_eq!(trap(vec![Arc::new(only_hidden), sq(2, 10.0, blue)]).len(), 2, "no trap"); +} + #[test] fn hard_mix_takes_the_highest_of_each_cmyk_channel_and_drops_strokes() { let mut g = two_overlapping_cmyk_squares(); @@ -87,6 +114,72 @@ fn soft_mix_blends_cmyk_bottom_to_top_and_drops_strokes() { assert!((c - 0.3).abs() < 0.02 && (m - 0.43).abs() < 0.02 && (y - 0.35).abs() < 0.02 && (k - 0.05).abs() < 0.02, "{c} {m} {y} {k}"); } +/// Soft Mix and Hard Mix mix the top fill that paints: a hidden fill above it adds no color. +#[test] +fn mixes_skip_a_hidden_fill() { + for effect in ["pathfinder.softMix", "pathfinder.hardMix"] { + let mut plain = two_overlapping_cmyk_squares(); + plain.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({"mixingRate": 50.0}), visible: true }); + let mut covered = plain.clone(); + let NodeKind::Group { children, .. } = &mut covered.kind else { panic!("group") }; + let mut hidden = FillLayer::new(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0))); + hidden.visible = false; + for c in children.iter_mut() { + Arc::make_mut(c).appearance.items.push(AppearanceItem::Fill(hidden.clone())); + } + assert_eq!(overlap_cmyk(&covered), overlap_cmyk(&plain), "{effect}"); + } +} + +/// Outline strokes each edge with the top fill that paints, keeping that fill's opacity, blend +/// mode and overprint. A hidden fill or a fill of no paint gives the edges nothing; with no fill +/// that paints, the edges take the top stroke that paints, which skips hidden and 0 pt strokes. +#[test] +fn outline_edges_keep_the_fill_layers_opacity_blend_and_overprint() { + use vectorcraft_doc::StrokeLayer; + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + let mut fill = FillLayer::new(red.clone()); + (fill.opacity, fill.blend, fill.overprint) = (0.5, BlendMode::Multiply, true); + let mut hidden = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0))); + hidden.visible = false; + let mut stroke = StrokeLayer::new(blue.clone(), 2.0); + (stroke.opacity, stroke.blend, stroke.overprint) = (0.5, BlendMode::Multiply, true); + let mut hidden_stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), 2.0); + hidden_stroke.visible = false; + let zero_stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), 0.0); + let look = |items: Vec| Appearance { items, ..Default::default() }; + let (f, s) = (AppearanceItem::Fill, AppearanceItem::Stroke); + let cases = [ + (look(vec![f(fill.clone())]), Some(red.clone())), + (look(vec![f(fill.clone()), f(hidden.clone())]), Some(red.clone())), + (look(vec![f(fill.clone()), f(FillLayer::new(Paint::None))]), Some(red.clone())), + (look(vec![f(hidden.clone())]), None), + (look(vec![s(stroke.clone())]), Some(blue.clone())), + (look(vec![f(hidden.clone()), s(stroke.clone())]), Some(blue.clone())), + (look(vec![s(stroke.clone()), s(hidden_stroke), s(zero_stroke.clone())]), Some(blue.clone())), + (look(vec![s(zero_stroke)]), None), + ]; + for (appearance, want) in cases { + let member = Arc::new(Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), appearance)); + let mut g = Node::group(NodeId(10), vec![member, sq(2, 5.0, Color::rgb(0.0, 0.0, 1.0))]); + g.appearance.effects.push(Effect { id: "pathfinder.outline".into(), params: serde_json::json!({}), visible: true }); + let out = pathfinder_children(None, &g, None).unwrap(); + let edges: Vec<_> = out.iter().filter(|n| n.id == NodeId(1)).collect(); + assert!(!edges.is_empty(), "{out:#?}"); + for n in edges { + let [AppearanceItem::Stroke(s)] = n.appearance.items.as_slice() else { panic!("one stroke: {n:#?}") }; + match &want { + Some(paint) => { + assert_eq!(&s.paint, paint); + assert_eq!((s.opacity, s.blend, s.overprint), (0.5, BlendMode::Multiply, true), "{s:#?}"); + } + None => assert!(s.paint.is_none() && s.opacity == 1.0, "{s:#?}"), + } + } + } +} + #[test] fn shape_modes_follow_the_pathfinder_panel() { let add = pathfinder_children(None, &group_with("pathfinder.add"), None).unwrap(); diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index e3915797f2..9d5e96744a 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -86,9 +86,9 @@ pub use raster::{ without_geometry, }; pub use reshape::{ - SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_gradient_copies, has_instance_row_raster, has_item_geometry, - has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outer_effects, outline_art, - outline_text, paint_type_piece, reshape, + SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_copied_row_raster, has_gradient_copies, + has_instance_row_raster, has_item_geometry, has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, + instance_as_art, needs_outline, outer_effects, outline_art, outline_text, paint_type_piece, reshape, }; pub use revolve::{ CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in, @@ -103,8 +103,8 @@ pub use solids::{ with_graphic, }; pub use solids::{ - GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, graphic_frame_at, graphics_reshaped_after, - rename_appearance_graphic_symbol, + GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_frame_at, + graphics_reshaped_after, rename_appearance_graphic_symbol, }; pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings}; pub use svg_filter::SVG_FILTER; diff --git a/crates/effects/src/lighting.rs b/crates/effects/src/lighting.rs index 257576822a..99bd568ee9 100644 --- a/crates/effects/src/lighting.rs +++ b/crates/effects/src/lighting.rs @@ -168,6 +168,62 @@ pub(crate) fn footprint(path: &vectorcraft_geom::BezPath, seam: f64) -> vectorcr if sign < 0.0 { footprint.reverse_subpaths() } else { footprint } } +/// The most edges a facet may have for [`seamed_fill`] to test it for crossing edges. +const SEAMED_FILL_EDGES: usize = 256; + +/// Facet `path` and its round seam `seam` wide as one path to fill ([`footprint`]), so that at an +/// edge pixel the facet and its seam cover it once between them, not a fill's coverage and then a +/// stroke's over it. `None` unless `path` is one closed polygon of up to [`SEAMED_FILL_EDGES`] +/// finite edges, with an area, and with no two edges that are not neighbors touching: only there +/// does the footprint's nonzero fill cover the facet and its seam and nothing more. `None` too for +/// a seam that is not a positive finite width, or a footprint with no finite bounds or less area +/// than the facet. +pub(crate) fn seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Option { + use kurbo::{PathEl, Point, Shape}; + if !(seam.is_finite() && seam > 0.0) { + return None; + } + let bez = path.to_bezpath(); + let mut elements = bez.elements().iter(); + let Some(PathEl::MoveTo(first)) = elements.next() else { return None }; + let mut points = vec![*first]; + let mut closed = false; + for el in elements { + match el { + PathEl::LineTo(p) if !closed => points.push(*p), + PathEl::ClosePath if !closed => closed = true, + _ => return None, + } + } + if points.len() > 1 && points.first() == points.last() { + points.pop(); + } + let area = bez.area().abs(); + if !closed || !(3..=SEAMED_FILL_EDGES).contains(&points.len()) || points.iter().any(|p| !p.is_finite()) || !area.is_finite() || area <= 1e-9 { + return None; + } + let side = |a: Point, b: Point, c: Point| (b - a).cross(c - a); + let touch = |a: Point, b: Point, c: Point, d: Point| { + let boxes = a.x.min(b.x) <= c.x.max(d.x) && c.x.min(d.x) <= a.x.max(b.x) && a.y.min(b.y) <= c.y.max(d.y) && c.y.min(d.y) <= a.y.max(b.y); + boxes && side(a, b, c) * side(a, b, d) <= 0.0 && side(c, d, a) * side(c, d, b) <= 0.0 + }; + let n = points.len(); + let edge = |i: usize| (points[i], points[(i + 1) % n]); + for i in 0..n { + for j in i + 2..n { + if i == 0 && j == n - 1 { + continue; + } + let ((a, b), (c, d)) = (edge(i), edge(j)); + if touch(a, b, c, d) { + return None; + } + } + } + let fill = footprint(&bez, seam); + (fill.bounding_box().is_finite() && fill.area().abs() >= area).then(|| vectorcraft_geom::PathData::from_bezpath(&fill)) +} + /// Colored-light facets `faces` (in drawing order) drawn over an underlay of themselves, the same /// facets grown to seams [`UNDERLAY_SEAM`] wide, all clipped once to the union of the facets' /// footprints. Where two facets' antialiased edges meet, the underlay fills what they leave @@ -175,6 +231,20 @@ pub(crate) fn footprint(path: &vectorcraft_geom::BezPath, seam: f64) -> vectorcr /// every face is a facet a surface draws: a path filled and stroked by its seam, or a facet composed /// in a clip of its footprint, neither with an opacity mask. pub(crate) fn sealed(id: vectorcraft_doc::NodeId, faces: &[std::sync::Arc]) -> Option { + use std::sync::Arc; + use vectorcraft_doc::{Node, NodeKind}; + let (clip, mut underlay) = underlay(id, faces)?; + underlay.extend(faces.iter().cloned()); + Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, underlay))], clip: true })) +} + +/// The parts of [`sealed`] for `faces`: a path of the union of the facets' footprints, to clip to, +/// and the facets grown to seams [`UNDERLAY_SEAM`] wide, in the same order. `None` under the same +/// conditions as [`sealed`]. +pub(crate) fn underlay( + id: vectorcraft_doc::NodeId, + faces: &[std::sync::Arc], +) -> Option<(vectorcraft_doc::Node, Vec>)> { use std::sync::Arc; use vectorcraft_doc::{Appearance, Node, NodeKind}; let mut outline = vectorcraft_geom::BezPath::new(); @@ -207,15 +277,15 @@ pub(crate) fn sealed(id: vectorcraft_doc::NodeId, faces: &[std::sync::Arc return None, } } - let clip = Node::path(id, vectorcraft_geom::PathData::from_bezpath(&outline), Appearance::default()); - underlay.extend(faces.iter().cloned()); - Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, underlay))], clip: true })) + Some((Node::path(id, vectorcraft_geom::PathData::from_bezpath(&outline), Appearance::default()), underlay)) } /// Composite smooth solid-fill facets with one clip and three channel groups per surface. In each /// channel, an underlay of the facets with wide seams lies under the facets themselves, so a /// shared edge is opaque in that channel's own light before the channels are screened together; -/// the black backdrop shows only outside the surface, which the clip removes. +/// the black backdrop shows only outside the surface, which the clip removes. Each facet over the +/// underlay is one fill of the facet and its seam together ([`seamed_fill`]), or a fill and a seam +/// stroke where that is `None`. pub(crate) fn solid_surface(id: vectorcraft_doc::NodeId, facets: &[vectorcraft_three_d::Facet], paint: &Paint) -> vectorcraft_doc::Node { use kurbo::Shape; use std::sync::Arc; @@ -239,6 +309,8 @@ pub(crate) fn solid_surface(id: vectorcraft_doc::NodeId, facets: &[vectorcraft_t let clip = Node::path(id, PathData::from_bezpath(&boundary), Appearance::default()); let bounds = bounds.unwrap_or(Rect::ZERO).inflate(1.0, 1.0); let cover = |paint| Node::path(id, shapes::rectangle(bounds), Appearance::basic(paint, Paint::None, 0.0)); + let seam = |face: &vectorcraft_three_d::Facet| (face.thickness() / 2.0).clamp(0.05, 0.75); + let exact: Vec> = facets.iter().map(|face| seamed_fill(&face.path(), seam(face))).collect(); let channels = (0..3) .map(|channel| { let mut color = [0.0; 3]; @@ -274,7 +346,17 @@ pub(crate) fn solid_surface(id: vectorcraft_doc::NodeId, facets: &[vectorcraft_t }; let mut children = vec![Arc::new(cover(Paint::solid(Color::BLACK)))]; children.extend(draw(|_| UNDERLAY_SEAM)); - children.extend(draw(|face| (face.thickness() / 2.0).clamp(0.05, 0.75))); + children.extend(facets.iter().zip(&exact).zip(&paints).map(|((face, fill), paint)| { + let mut items = vec![AppearanceItem::Fill(FillLayer::new(paint.clone()))]; + let path = match fill { + Some(fill) => fill.clone(), + None => { + items.push(AppearanceItem::Stroke(seam_stroke(paint.clone(), seam(face)))); + face.path() + } + }; + Arc::new(Node::path(id, path, Appearance { items, ..Default::default() })) + })); let mut group = Node::group(id, children); group.isolate = true; group.blend = BlendMode::Screen; @@ -321,6 +403,22 @@ pub(crate) fn opaque_paint(paint: &Paint) -> (Paint, Option) { (base, transparent.then_some(mask)) } +/// [`opaque_paint`] for a surface of several faces under one opacity mask. A transparent gradient +/// without a placement (or a freeform gradient without points) is first pinned to `bounds`, the +/// faces' bounds together grown by 1 pt, so every face's color and the mask share one placement. +/// An opaque gradient is returned as [`opaque_paint`] returns it. +pub(crate) fn opaque_surface_paint(paint: &Paint, bounds: impl FnOnce() -> vectorcraft_geom::Rect) -> (Paint, Option) { + let (base, mask) = opaque_paint(paint); + if mask.is_none() || !matches!(paint, Paint::Gradient(_)) { + return (base, mask); + } + let mut pinned = paint.clone(); + if let Paint::Gradient(g) = &mut pinned { + g.pin(bounds().inflate(1.0, 1.0)); + } + opaque_paint(&pinned) +} + fn composed_art(id: vectorcraft_doc::NodeId, path: &vectorcraft_geom::PathData, paint: &Paint, light: Ramp, seam: f64) -> vectorcraft_doc::Node { use std::sync::Arc; use vectorcraft_doc::color::BlendMode; @@ -501,4 +599,65 @@ mod tests { } } } + + /// A simple polygon facet and its 0.75 pt round seam are one nonzero-filled path: it covers the + /// facet and the 0.375 pt the seam reaches past each edge and corner, and nothing more, wound + /// either way and in a concave notch. A facet whose footprint would gain or lose area under a + /// nonzero fill (no area, crossing edges, a hole, curves) or a seam with no width has none. + #[test] + fn seamed_fill_covers_a_polygon_and_its_seam_once() { + use kurbo::Shape; + use vectorcraft_geom::BezPath; + let polygon = |points: &[(f64, f64)]| { + let mut bp = BezPath::new(); + bp.move_to(points[0]); + for p in &points[1..] { + bp.line_to(*p); + } + bp.close_path(); + bp + }; + let covers = |fill: &vectorcraft_geom::PathData, x: f64, y: f64| fill.to_bezpath().winding(Point::new(x, y)) != 0; + let notched = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (6.0, 10.0), (6.0, 4.0), (4.0, 4.0), (4.0, 10.0), (0.0, 10.0)]; + let mut reversed = notched; + reversed.reverse(); + for points in [¬ched[..], &reversed[..], &[(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)][..]] { + let fill = seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&polygon(points)), 0.75).expect("a simple polygon"); + let contours = fill.to_bezpath().elements().iter().filter(|el| matches!(el, kurbo::PathEl::MoveTo(_))).count(); + assert!(contours >= 2, "{points:?}: the seam's outline and the facet, {contours} contours"); + for (x, y) in [(1.0, 1.0), (2.0, 0.5), (5.0, -0.3), (-0.3, 5.0), (-0.2, -0.2)] { + assert!(covers(&fill, x, y), "{points:?} covers ({x},{y})"); + } + for (x, y) in [(5.0, -0.5), (-0.5, 5.0), (-0.3, -0.3), (12.0, 12.0)] { + assert!(!covers(&fill, x, y), "{points:?} leaves ({x},{y})"); + } + } + let fill = seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&polygon(¬ched)), 0.75).unwrap(); + assert!(covers(&fill, 4.3, 8.0) && covers(&fill, 5.0, 4.3), "the notch's edges carry the seam"); + assert!(!covers(&fill, 5.0, 8.0), "the notch stays open"); + let square = polygon(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]); + let mut holed = square.clone(); + holed.extend(polygon(&[(3.0, 3.0), (3.0, 7.0), (7.0, 7.0), (7.0, 3.0)]).iter()); + let mut curved = BezPath::new(); + curved.move_to((0.0, 0.0)); + curved.quad_to((5.0, -5.0), (10.0, 0.0)); + curved.line_to((5.0, 10.0)); + curved.close_path(); + let mut open = BezPath::new(); + open.move_to((0.0, 0.0)); + open.line_to((10.0, 0.0)); + open.line_to((10.0, 10.0)); + for (name, path, seam) in [ + ("sliver", polygon(&[(0.0, 0.0), (10.0, 0.0), (5.0, 0.0)]), 0.75), + ("bow tie", polygon(&[(0.0, 0.0), (10.0, 10.0), (10.0, 0.0), (0.0, 10.0)]), 0.75), + ("a vertex visited twice", polygon(&[(0.0, 0.0), (10.0, 0.0), (5.0, 5.0), (10.0, 10.0), (0.0, 10.0), (5.0, 5.0)]), 0.75), + ("hole", holed, 0.75), + ("curve", curved, 0.75), + ("open", open, 0.75), + ("no seam", square.clone(), 0.0), + ("endless seam", square, f64::INFINITY), + ] { + assert!(seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&path), seam).is_none(), "{name}"); + } + } } diff --git a/crates/effects/src/pixel.rs b/crates/effects/src/pixel.rs index f2c49dadd7..f6c33079c0 100644 --- a/crates/effects/src/pixel.rs +++ b/crates/effects/src/pixel.rs @@ -29,6 +29,8 @@ mod sketch_ink; mod texture; mod video; +use std::f64::consts::{PI, TAU}; + use serde_json::Value; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; @@ -332,6 +334,9 @@ pub struct PixelSpace { pub extent: f64, } +/// Color Halftone's screen angle parameters with their defaults (degrees). +const SCREEN_ANGLES: [(&str, f64); 4] = [("channel1", 108.0), ("channel2", 162.0), ("channel3", 90.0), ("channel4", 45.0)]; + /// Effect `id`'s parameters `p` (defaults merged in) as a [`PixelFx`]; `None` for other effects. pub(crate) fn parse(id: &str, p: &Value) -> Option { let quality = |levels: [(&str, u32); 3], default: u32| { @@ -565,8 +570,7 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option { }, "pixelate.colorHalftone" => PixelFx::ColorHalftone { max_radius: num(p, "maxRadius", 8.0).clamp(4.0, 127.0), - angles: [("channel1", 108.0), ("channel2", 162.0), ("channel3", 90.0), ("channel4", 45.0)] - .map(|(k, d)| num(p, k, d).clamp(-360.0, 360.0)), + angles: SCREEN_ANGLES.map(|(k, d)| num(p, k, d).clamp(-360.0, 360.0)), }, "pixelate.crystallize" => PixelFx::Crystallize { cell: num(p, "cellSize", 10.0).clamp(3.0, 300.0) }, "pixelate.mezzotint" => PixelFx::Mezzotint { kind: Mezzotint::parse(text(p, "type", "fineDots")) }, @@ -855,6 +859,113 @@ fn pick(table: &[(&str, &str)], all: &[T], value: &str, default: T) -> table.iter().zip(all).find(|((_, v), _)| v.eq_ignore_ascii_case(value)).map_or(default, |(_, t)| t.clone()) } +/// The shortest that a direction's unit vector may become under a Transform effect and still give +/// a direction ([`turned_directions`]). +const MIN_TURNED: f64 = 1e-9; + +/// How close (radians) two directions' angles to a turned direction must be to count as equally +/// near ([`nearest`]). +const TIE: f64 = 1e-9; + +/// The parameters of pixel filter `id` (params `p`, defaults not merged in) that set a direction +/// on the page, as `a` turns them: `a` is the linear part of a Transform effect listed after the +/// filter, which turns, reflects and scales what the filter paints. A light direction or stroke +/// direction becomes the one nearest to where `a` takes it, the one clockwise of it when two are +/// equally near ([`snapped`]); `later` is the map the filter still goes through when it is drawn, +/// after `a`. Color Halftone's screen angles (degrees counterclockwise from the page's horizontal) +/// turn with `a`, from 0 up to 360. A direction that `a` takes to no direction (a zero scale) stays +/// as it is. Empty for filters with no such parameter. +pub(crate) fn turned_directions(id: &str, p: &Value, a: Affine, later: Affine) -> Vec<(&'static str, Value)> { + enum Kind { + Light(&'static str), + Stroke, + Screens, + } + let kind = match id { + "sketch.basRelief" => Kind::Light("bottom"), + "artistic.underpainting" | "artistic.roughPastels" | "sketch.conteCrayon" | "sketch.plaster" | "texture.texturizer" => Kind::Light("top"), + "brushStrokes.sprayedStrokes" | "sketch.graphicPen" => Kind::Stroke, + "pixelate.colorHalftone" => Kind::Screens, + _ => return Vec::new(), + }; + let p = crate::merged_params(id, p); + match kind { + Kind::Light(default) => { + let light = Light::parse(text(&p, "lightDirection", default)); + snapped(&Light::ALL, Light::toward, light, a, later, false) + .and_then(|t| name_of(&LIGHT_DIRECTIONS, &Light::ALL, t)) + .map(|name| vec![("lightDirection", Value::from(name))]) + .unwrap_or_default() + } + Kind::Stroke => { + let direction = StrokeDirection::parse(text(&p, "strokeDirection", "rightDiagonal")); + snapped(&StrokeDirection::ALL, StrokeDirection::along, direction, a, later, true) + .and_then(|t| name_of(&STROKE_DIRECTIONS, &StrokeDirection::ALL, t)) + .map(|name| vec![("strokeDirection", Value::from(name))]) + .unwrap_or_default() + } + // A screen at θ° runs along (cos θ, −sin θ) on the page (y down). + Kind::Screens => SCREEN_ANGLES + .iter() + .filter_map(|&(key, default)| { + let t = num(&p, key, default).clamp(-360.0, 360.0).to_radians(); + let v = mapped(a, Vec2::new(t.cos(), -t.sin()))?; + let degrees = ((-v.y).atan2(v.x).to_degrees() * 1e6).round() / 1e6; + Some((key, Value::from(degrees.rem_euclid(360.0) + 0.0))) + }) + .collect(), + } +} + +/// Where the linear part of `a` takes direction `v`; `None` when it takes it to no direction. +fn mapped(a: Affine, v: Vec2) -> Option { + let w = (a * v.to_point()) - (a * Point::ORIGIN); + (w.is_finite() && w.hypot() > MIN_TURNED).then_some(w) +} + +/// The entry of `all` to store for `from` (directions `dir`) once `a` turns it: the one nearest to +/// where `a` takes it ([`nearest`]). When the stored entry is still to be mapped by `later` and +/// rounded again as it is drawn, it is the entry nearest to that among those that `later` takes to +/// the entry nearest to where `later` after `a` takes `from`, so that the drawn direction is +/// rounded once. `None` when `a` takes `from` to no direction. +fn snapped(all: &[T], dir: fn(T) -> Vec2, from: T, a: Affine, later: Affine, axis: bool) -> Option { + let v = mapped(a, dir(from))?; + let turned = nearest(all, dir, v, axis)?; + if later == Affine::IDENTITY { + return Some(turned); + } + let Some(target) = mapped(later * a, dir(from)).and_then(|w| nearest(all, dir, w, axis)) else { return Some(turned) }; + let fits: Vec = all.iter().copied().filter(|&t| mapped(later, dir(t)).and_then(|w| nearest(all, dir, w, axis)) == Some(target)).collect(); + nearest(&fits, dir, v, axis).or(Some(turned)) +} + +/// The entry of `all` whose direction (`dir`, page axes with y down) is nearest to `v` by angle, +/// a direction and its opposite counting as the same with `axis`. Of two equally near, the one +/// clockwise of `v` on the page. +fn nearest(all: &[T], dir: impl Fn(T) -> Vec2, v: Vec2, axis: bool) -> Option { + let period = if axis { PI } else { TAU }; + let at = v.atan2(); + let mut best: Option<(T, f64)> = None; + for &t in all { + // How far clockwise of `v` the entry lies, within half a period either way. + let d = (dir(t).atan2() - at).rem_euclid(period); + let d = if d > period / 2.0 { d - period } else { d }; + let better = match best { + None => true, + Some((_, b)) => d.abs() < b.abs() - TIE || (d.abs() <= b.abs() + TIE && d > b), + }; + if better { + best = Some((t, d)); + } + } + best.map(|(t, _)| t) +} + +/// The value in `table` of entry `t` of `all` (the same order). +fn name_of(table: &[(&'static str, &'static str)], all: &[T], t: T) -> Option<&'static str> { + table.iter().zip(all).find(|(_, u)| **u == t).map(|((_, v), _)| *v) +} + /// `data` as `w` × `h` RGBA pixels, `None` when it isn't that size (or is empty). fn pixels(data: &mut [u8], w: usize, h: usize) -> Option<&mut [[u8; 4]]> { let (px, rest) = data.as_chunks_mut::<4>(); diff --git a/crates/effects/src/pixel/brushstrokes.rs b/crates/effects/src/pixel/brushstrokes.rs index 100d4e2497..ca5c0a9b48 100644 --- a/crates/effects/src/pixel/brushstrokes.rs +++ b/crates/effects/src/pixel/brushstrokes.rs @@ -43,7 +43,7 @@ pub enum StrokeDirection { } impl StrokeDirection { - const ALL: [StrokeDirection; 4] = + pub(super) const ALL: [StrokeDirection; 4] = [StrokeDirection::RightDiagonal, StrokeDirection::Horizontal, StrokeDirection::LeftDiagonal, StrokeDirection::Vertical]; /// The direction of `value` (a [`STROKE_DIRECTIONS`] value, any case); Right Diagonal @@ -53,7 +53,7 @@ impl StrokeDirection { } /// The unit vector along the strokes (document axes, y down). - fn along(self) -> Vec2 { + pub(super) fn along(self) -> Vec2 { match self { StrokeDirection::RightDiagonal => RIGHT, StrokeDirection::Horizontal => Vec2::new(1.0, 0.0), 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/pixel/texture.rs b/crates/effects/src/pixel/texture.rs index a408454530..e041256dc0 100644 --- a/crates/effects/src/pixel/texture.rs +++ b/crates/effects/src/pixel/texture.rs @@ -137,7 +137,7 @@ pub enum Light { } impl Light { - const ALL: [Light; 8] = + pub(super) const ALL: [Light; 8] = [Light::Bottom, Light::BottomLeft, Light::Left, Light::TopLeft, Light::Top, Light::TopRight, Light::Right, Light::BottomRight]; /// The direction of `value` (a [`LIGHT_DIRECTIONS`] value, any case); Top otherwise. diff --git a/crates/effects/src/raster.rs b/crates/effects/src/raster.rs index f24a5dd2ee..ef8b32d56e 100644 --- a/crates/effects/src/raster.rs +++ b/crates/effects/src/raster.rs @@ -452,7 +452,7 @@ pub(crate) fn followed(effects: &[Effect]) -> Cow<'_, [Effect]> { let Some(a) = after.filter(|a| *a != Affine::IDENTITY && follows(&e.id)) else { continue }; let list = out.get_or_insert_with(|| effects.to_vec()); if let Some(e) = list.get_mut(i) { - follow_transform(e, a); + follow_transform(e, a, Affine::IDENTITY); } } out.map_or(Cow::Borrowed(effects), Cow::Owned) @@ -472,7 +472,7 @@ pub(crate) fn follow_one(effects: &mut [Effect], t: &Effect) -> bool { let Some(a) = transform_step(t).filter(|a| *a != Affine::IDENTITY) else { return false }; let mut changed = false; for e in effects.iter_mut().filter(|e| follows(&e.id)) { - follow_transform(e, a); + follow_transform(e, a, Affine::IDENTITY); changed = true; } changed @@ -519,7 +519,7 @@ pub(crate) fn follow_contents(effects: &mut [Effect], a: Affine, outer: Affine) let det = b.determinant(); let c = if b == Affine::IDENTITY || !(det.is_finite() && det.abs() > 1e-12) { a } else { b.inverse() * a * b }; if c.is_finite() { - follow_transform(e, c); + follow_transform(e, c, b); changed = true; } } @@ -666,11 +666,44 @@ pub(crate) fn follows(id: &str) -> bool { crate::is_raster(id) && id != crate::SVG_FILTER && id != RASTERIZE } +thread_local! { + /// The linear part of the Transform effects of the groups and layers whose members are being + /// evaluated ([`LaterGroups`]), which those groups apply to the members' raster effects once + /// the members are evaluated: the members' light and stroke directions are rounded for them as + /// well ([`follow_transform`]). + static LATER_GROUPS: std::cell::Cell = const { std::cell::Cell::new(Affine::IDENTITY) }; +} + +/// The Transform effects of a group or layer whose members are being evaluated before the group's +/// own effects are applied to them, added to [`LATER_GROUPS`] until it is dropped. +pub(crate) struct LaterGroups(Affine); + +impl LaterGroups { + /// Add the Transform effects of `owner`, a group's or layer's own effects ([`contents_step`]), + /// to those the members will still go through. + pub(crate) fn enter(owner: &[Effect]) -> Self { + let was = LATER_GROUPS.with(|l| l.get()); + if let Some(step) = contents_step(owner) { + LATER_GROUPS.with(|l| l.set(was * step)); + } + LaterGroups(was) + } +} + +impl Drop for LaterGroups { + fn drop(&mut self) { + LATER_GROUPS.with(|l| l.set(self.0)); + } +} + /// Make raster effect `e` follow `a`, the linear part of a Transform effect listed after it, as /// that effect transforms what `e` paints: its distances and raster sizes scale by `a`'s mean -/// scale ([`crate::scale_effect`]), and a Drop Shadow's offset turns, reflects and scales with -/// `a`. Effects that [`follows`] leaves out stay as they are. -fn follow_transform(e: &mut Effect, a: Affine) { +/// scale ([`crate::scale_effect`]), a Drop Shadow's offset turns, reflects and scales with `a`, +/// and a pixel filter's light direction, stroke direction or screen angles turn and reflect with +/// it ([`pixel::turned_directions`]; `later` is the map `e` still goes through when it is drawn, +/// before the Transform effects of the groups around it in [`LATER_GROUPS`]). Effects that +/// [`follows`] leaves out stay as they are. +fn follow_transform(e: &mut Effect, a: Affine, later: Affine) { if !follows(&e.id) { return; } @@ -678,15 +711,22 @@ fn follow_transform(e: &mut Effect, a: Affine) { let p = merged_params(&e.id, &e.params); a * Point::new(num(&p, "x", 7.0), num(&p, "y", 7.0)) }); + let turned = pixel::turned_directions(&e.id, &e.params, a, LATER_GROUPS.with(|l| l.get()) * later); if let Some(k) = vectorcraft_doc::Scaling::factor(a) { crate::scale_effect(e, k); } - if let Some(o) = offset.filter(|o| o.x.is_finite() && o.y.is_finite()) { + let mut set = |key: &str, value: Value| { if !e.params.is_object() { e.params = Value::Object(Map::new()); } - e.params["x"] = json!(o.x); - e.params["y"] = json!(o.y); + e.params[key] = value; + }; + if let Some(o) = offset.filter(|o| o.x.is_finite() && o.y.is_finite()) { + set("x", json!(o.x)); + set("y", json!(o.y)); + } + for (key, value) in turned { + set(key, value); } } diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 4c8191fd2b..441e78e9e2 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -107,24 +107,84 @@ fn reaches_appearance(e: &Effect) -> bool { } /// Is `n` a path or compound path that its Transform effects make into art of separate objects -/// ([`has_gradient_copies`], [`has_layered_copies`], [`has_transform_options`], [`copied_raster_at`]), -/// or whose live-effect plug-ins paint what they return ([`has_painted_effects`])? It is drawn, -/// baked and expanded through that art ([`reshape`]). +/// ([`has_gradient_copies`], [`has_layered_copies`], [`has_transform_options`], [`copied_raster_at`], +/// [`has_copied_row_raster`]), or whose live-effect plug-ins paint what they return +/// ([`has_painted_effects`])? It is drawn, baked and expanded through that art ([`reshape`]). pub fn has_transform_art(n: &Node) -> bool { - has_gradient_copies(n) || has_layered_copies(n) || has_transform_options(n) || has_painted_effects(n) || copied_raster_at(n).is_some() + has_gradient_copies(n) + || has_layered_copies(n) + || has_transform_options(n) + || has_painted_effects(n) + || (matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && copied_raster_at(n).is_some()) + || has_copied_row_raster(n) } -/// Where the own effects of `n`, a path or compound path, split so that each copy of a Transform -/// effect carries the raster effects listed before that effect ([`copied_raster_art`]): the index -/// of the last visible Transform effect that makes copies, when a visible raster effect that -/// follows a Transform effect ([`crate::raster::follows`]) is listed before it and every other -/// visible effect before it is a geometry effect or such a raster effect. `None` otherwise, and for -/// a path with a linked opacity mask, a 3D effect, Crop Marks, Vector Halftone, a live-effect -/// plug-in that paints what it returns, or a fill or stroke that paints with geometry effects of -/// its own. -pub(crate) fn copied_raster_at(n: &Node) -> Option { +/// Is `n` a path or compound path with a fill or stroke that paints and whose raster effects are +/// carried by copies: one whose own effects list a Transform effect that makes copies after a +/// raster effect that follows it ([`copied_row_raster_at`]), or one with a raster effect that +/// follows a Transform effect ([`crate::raster::follows`]) on a path whose own Transform effect makes +/// copies ([`has_transform_copies`])? Each copy is then an object of its own carrying that fill's or +/// stroke's raster effects, moved, turned, reflected and scaled with it ([`transform_item_leaf`], +/// [`follow_copies`]). +pub fn has_copied_row_raster(n: &Node) -> bool { if !matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }) { - return None; + return false; + } + // Checked first: this runs for every object drawn. + if !n.appearance.items.iter().any(follows_row_raster) { + return false; + } + n.appearance.items.iter().any(|i| crate::paints(i) && copied_row_raster_at(i.effects()).is_some()) || has_transform_copies(n) +} + +/// Does `item` paint and carry a visible raster effect that follows a Transform effect +/// ([`crate::raster::follows`])? +fn follows_row_raster(item: &AppearanceItem) -> bool { + crate::paints(item) && item.effects().iter().any(|e| e.visible && crate::raster::follows(&e.id)) +} + +/// Where a fill's or stroke's own effects `fx` split so that each copy of a Transform effect carries +/// the raster effects listed before it: the index of the first visible Transform effect that makes +/// copies (an earlier one that makes copies included) for which a visible raster effect that +/// follows a Transform effect ([`crate::raster::follows`]) is listed before it, every other visible +/// effect before it is a geometry effect or such a raster effect, and no Transform effect before it +/// that makes copies or moves at random holds those raster effects back +/// ([`crate::raster::held_back`]). `None` otherwise, and when a raster effect is listed after it +/// and before a later Transform effect that makes copies or moves at random, which would apply to +/// the art that raster effect paints. +fn copied_row_raster_at(fx: &[Effect]) -> Option { + let copying = + |e: &Effect| e.visible && e.id == "distort.transform" && crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).1 > 0; + // Is a visible raster effect in `rest` listed before its last Transform effect that holds back? + let raster_held = |rest: &[Effect]| { + rest.iter().rposition(crate::raster::holds_back).is_some_and(|k| rest[..k].iter().any(|e| e.visible && crate::is_raster(&e.id))) + }; + (0..fx.len()).find(|&t| { + let before = &fx[..t]; + copying(&fx[t]) + && !raster_held(&fx[t + 1..]) + && crate::raster::held_back(before) == 0 + && before.iter().any(|e| e.visible && crate::raster::follows(&e.id)) + && before.iter().all(|e| !e.visible || is_geometry(&e.id) || crate::raster::follows(&e.id)) + }) +} + +/// Where the own effects of `n`, a path, compound path, type, image or symbol instance, split so +/// that each copy of a Transform effect carries the raster effects listed before that effect +/// ([`copied_raster_art`]): the index of the last visible Transform effect that makes copies, when +/// a visible raster effect that follows a Transform effect ([`crate::raster::follows`]) is listed +/// before it and every other visible effect before it is a geometry effect or such a raster effect. +/// `None` otherwise, and for an object with a linked opacity mask, a 3D effect, Crop Marks, Vector +/// Halftone, a live-effect plug-in that paints what it returns, a fill or stroke that paints with +/// geometry effects of its own, or (type, images and symbol instances) a perspective. +pub(crate) fn copied_raster_at(n: &Node) -> Option { + match n.kind { + NodeKind::Path { guide: false, clipping: false, .. } + | NodeKind::Compound { .. } + | NodeKind::Text(_) + | NodeKind::Image(_) + | NodeKind::SymbolInstance { .. } => {} + _ => return None, } let effects = &n.appearance.effects; // Checked first: this runs for every object drawn. @@ -143,7 +203,8 @@ pub(crate) fn copied_raster_at(n: &Node) -> Option { || crate::has_crop_marks(n) || crate::addons::halftone::has_halftone(n) || has_painted_effects(n) - || n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())); + || n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())) + || n.projection().is_some(); (carried && !excluded).then_some(t) } @@ -515,18 +576,62 @@ fn laid_out(t: &vectorcraft_doc::TextObject) -> (Vec, kurbo::Bez /// gradient fitted across the whole layout, and the transform also scales its stroke weights and /// dashes and transforms its pattern tiles. Placed gradients keep their place in text space and /// move with the type. -pub fn paint_type_piece(piece: &mut Node, style: &vectorcraft_doc::CharStyle, bounds: Rect, xf: Affine) { +/// +/// When `xf` is not a similarity (it scales unevenly, shears or flattens), one weight can't give +/// the stroke the thickness the canvas paints in each direction: `piece` keeps only the run's fill, +/// and the returned path is the area the run's stroke paints around `piece` in text space +/// ([`crate::stroke::outline_region`]: dashes, caps, joins and alignment), placed by `xf` and +/// filled with the stroke's paint, to paint over `piece`. `None` under a similarity and for a run +/// without a stroke. +pub fn paint_type_piece(piece: &mut Node, style: &vectorcraft_doc::CharStyle, bounds: Rect, xf: Affine) -> Option { + let scaling = vectorcraft_doc::Scaling { strokes: true, patterns: true, ..Default::default() }; let mut ap = style.appearance(); ap.pin_gradients(bounds); + let stroke = if is_similarity(xf) { None } else { filled_stroke(piece, &mut ap) }; piece.appearance = ap.into(); - piece.transform(xf, vectorcraft_doc::Scaling { strokes: true, patterns: true, ..Default::default() }); + piece.transform(xf, scaling); + stroke.map(|mut s| { + s.transform(xf, scaling); + s + }) +} + +/// Does `xf` keep angles and scale every direction alike (a move, a rotation, a uniform scale or a +/// reflection), without flattening? +fn is_similarity(xf: Affine) -> bool { + let [a, b, c, d, ..] = xf.as_coeffs(); + let (x, y) = (a.hypot(b), c.hypot(d)); + let tol = 1e-9 * x.max(y); + x.is_finite() && y.is_finite() && x > 0.0 && y > 0.0 && (x - y).abs() <= tol && (a * c + b * d).abs() <= tol * x.max(y) +} + +/// Takes the stroke out of `ap`, the appearance of `piece` (a path or compound path in text space), +/// and returns the area it paints there as a path filled with its paint, opacity, blend mode, +/// effects and overprint, with `piece`'s id. `None` when `ap` has no stroke or it paints nothing. +fn filled_stroke(piece: &Node, ap: &mut Appearance) -> Option { + let i = ap.items.iter().position(|i| matches!(i, AppearanceItem::Stroke(_)))?; + let AppearanceItem::Stroke(st) = ap.items.remove(i) else { return None }; + let path = PathData::from_bezpath(&piece.stroke_path()?); + let region = crate::stroke::outline_region(&path, FillRule::NonZero, &st); + if region.is_empty() { + return None; + } + let fill = vectorcraft_doc::FillLayer { + opacity: st.opacity, + blend: st.blend, + effects: st.effects.clone(), + overprint: st.overprint, + ..vectorcraft_doc::FillLayer::new(st.paint.stroke_as_fill()) + }; + Some(Node::path(piece.id, region, Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() })) } /// Type as glyph outlines in document space: one path per run with the run's fill and stroke, /// over its colour glyphs (images, art), and (when the object has its own fills/strokes) the whole /// outline with the object's items below the characters under them and the others over them, as /// the renderer paints them. Each run's path is placed by the type's transform, which also scales its stroke -/// weights and dashes and transforms its pattern tiles; its unplaced gradients are first fixed to +/// weights and dashes and transforms its pattern tiles (a transform that is not a similarity puts +/// the run's stroke on a filled path over it, [`paint_type_piece`]); its unplaced gradients are first fixed to /// the layout's bounds in text space. The object's own unplaced gradients are fixed to the /// bounding box of those bounds in the document. The group is marked as type's outlines /// ([`vectorcraft_doc::NodeExtras::type_outlines`]). @@ -542,8 +647,9 @@ pub fn outline_text(n: &Node) -> Option { continue; } let mut piece = Node::path(n.id, PathData::from_bezpath(bp), Appearance::default()); - paint_type_piece(&mut piece, &run.style, bounds, t.xf); + let stroke = paint_type_piece(&mut piece, &run.style, bounds, t.xf); children.push(Arc::new(piece)); + children.extend(stroke.map(Arc::new)); } if !n.appearance.items.is_empty() && !all.elements().is_empty() { let (below, above) = n.appearance.split_contents(); @@ -845,6 +951,16 @@ pub fn expand_outlined(doc: Option<&Document>, n: &Node, symbol_art: Option<&Nod as_art(doc, n, symbol_art) } +/// Symbol instance `n` as plain art for Expand Appearance, with or without geometry effects: the +/// art it places, reshaped by those effects when it has some, in the form [`expand_outlined`] +/// gives. `None` for other kinds of objects and for an instance without `symbol_art`. +pub fn instance_as_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option { + if !matches!(n.kind, NodeKind::SymbolInstance { .. }) { + return None; + } + as_art(doc, n, symbol_art) +} + /// [`reshape`] without its checks (no geometry effects: just the art). pub(crate) fn as_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option { as_art_with(doc, doc, n, symbol_art, &outline_text, &SymbolNodes::default()) @@ -876,7 +992,8 @@ fn as_art_opts( apart: bool, ) -> Option { if let Some(t) = copied_raster_at(n) { - return Some(dressed_keeping_effects(copied_raster_art(paint_doc, n, t, apart), n)); + let outlined = |s: &Node| as_art_opts(symbols, paint_doc, s, symbol_art, outline, nodes, apart); + return copied_raster_art(paint_doc, n, t, apart, &outlined).map(|art| dressed_keeping_effects(art, n)); } let fx = geometry_effects(n); let mut art = match &n.kind { @@ -933,7 +1050,7 @@ fn as_art_opts( } _ => outline_art_with(symbols, paint_doc, n, symbol_art, outline, nodes, apart)?, }; - reshape_leaves_apart(&mut art, &fx, &n.appearance.effects, Budget::EFFECTS, apart, paint_doc); + reshape_leaves_apart(&mut art, &fx, &n.appearance.effects, Budget::EFFECTS, (apart, has_copied_row_raster(n)), paint_doc); if apart { hoist_copies(&mut art); } @@ -971,23 +1088,39 @@ fn dressed_keeping_effects(mut art: Node, n: &Node) -> Node { art } -/// The art of path or compound path `n` whose own effects split at `t` ([`copied_raster_at`]): the -/// art the effects before the Transform effect at `t` make of `n`, with their raster effects, then -/// copied by that Transform effect, each copy an object of its own carrying those raster effects -/// moved, turned, reflected and scaled with it ([`follow_art`]), and then reshaped by the geometry -/// effects after it. The art keeps `n`'s id and carries the raster effects from `t` on, without -/// `n`'s name, visibility, transparency and opacity mask. The copies stop where [`copy_art`]'s do, -/// each with its raster effects. With `apart`, the Transform effects before `t` make each copy an -/// object of its own ([`copy_leaf`]). -fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool) -> Node { +/// The art of `n` whose own effects split at `t` ([`copied_raster_at`]): the art the effects before +/// the Transform effect at `t` make of `n`, with their raster effects, then copied by that +/// Transform effect, each copy an object of its own carrying those raster effects moved, turned, +/// reflected and scaled with it ([`follow_art`]), and then reshaped by the geometry effects after +/// it. The art keeps `n`'s id and carries the raster effects from `t` on, without `n`'s name, +/// visibility, transparency and opacity mask. The copies stop where [`copy_art`]'s do, each with +/// its raster effects. With `apart`, the Transform effects before `t` make each copy of a path an +/// object of its own ([`copy_leaf`]). Type, an image or a symbol instance becomes its art through +/// `outlined` ([`as_art_opts`]) before it is copied: type as its outlines, an image in its frame +/// and an instance as its symbol's art, whose members take their own geometry effects first +/// ([`crate::group::members_as_drawn`]). `None` when `outlined` gives no art. +fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool, outlined: &dyn Fn(&Node) -> Option) -> Option { let (before, rest) = n.appearance.effects.split_at(t); let mut source = n.clone(); source.appearance.effects = before.to_vec(); let piece = match copied_raster_at(&source) { - Some(at) => copied_raster_art(doc, &source, at, apart), + Some(at) => copied_raster_art(doc, &source, at, apart, outlined)?, + None if needs_outline(&source) => { + let mut art = outlined(&source)?; + if matches!(source.kind, NodeKind::SymbolInstance { .. }) && geometry_effects(&source).is_empty() { + // The copying Transform effect reshapes what the symbol's members draw. + crate::group::members_as_drawn(doc, &mut art); + } + art.name = None; + art.visible = true; + (art.opacity, art.blend, art.isolate, art.knockout_shape) = (1.0, Default::default(), false, false); + art.extras_mut().mask = None; + art + } None => { let mut art = one_piece(&source); - let carry = reshape_leaves_apart(&mut art, &geometry_effects(&source), &source.appearance.effects, Budget::EFFECTS, apart, doc); + let rows = has_copied_row_raster(&source); + let carry = reshape_leaves_apart(&mut art, &geometry_effects(&source), &source.appearance.effects, Budget::EFFECTS, (apart, rows), doc); if apart { hoist_copies(&mut art); } @@ -1028,17 +1161,18 @@ fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool) -> } } let later: Vec<&Effect> = rest.iter().skip(1).filter(|e| e.visible && is_geometry(&e.id)).collect(); - let carry = reshape_leaves_apart(&mut art, &later, &n.appearance.effects, Budget::EFFECTS, apart, doc); + let carry = reshape_leaves_apart(&mut art, &later, &n.appearance.effects, Budget::EFFECTS, (apart, has_copied_row_raster(n)), doc); let mut ran = n.appearance.effects.clone(); if carry.skipped() { carry.hide_skipped(&mut ran); } art.appearance.effects = crate::raster::without_geometry(ran.get(t..).unwrap_or_default()); - art + Some(art) } /// The effects of `n` that paint around its whole art: all of its own, or from the Transform effect -/// on for a path whose copies each carry the raster effects listed before it ([`copied_raster_at`]). +/// on for a path, compound path, type, image or symbol instance whose copies each carry the raster +/// effects listed before it ([`copied_raster_at`]). pub fn outer_effects(n: &Node) -> &[Effect] { match copied_raster_at(n) { Some(t) => n.appearance.effects.get(t..).unwrap_or_default(), @@ -1074,7 +1208,7 @@ pub(crate) fn own_effects_art(doc: Option<&Document>, n: &Node) -> Option return None; } if let Some(t) = copied_raster_at(n) { - return Some(dressed_keeping_effects(copied_raster_art(doc, n, t, false), n)); + return copied_raster_art(doc, n, t, false, &|_| None).map(|art| dressed_keeping_effects(art, n)); } if n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())) { // One element: its pieces never knock each other out. @@ -1158,19 +1292,19 @@ pub(crate) fn geometry_effects(n: &Node) -> Vec<&Effect> { /// that live-effect plug-ins painting their pieces name are looked up in `doc`, and a deferred one /// is listed by its index in `owner`, the effect list `fx` was taken from ([`reshape_leaves_apart`]). pub(crate) fn reshape_leaves(art: &mut Node, fx: &[&Effect], owner: &[Effect], doc: Option<&Document>) { - reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, false, doc); + reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, (false, false), doc); } /// [`reshape_leaves`], and how gradients that paint the art as a whole (a group's own fills and /// strokes) follow the effects ([`crate::Carry`]). pub(crate) fn reshape_leaves_carrying(art: &mut Node, fx: &[&Effect], owner: &[Effect], doc: Option<&Document>) -> crate::Carry { - reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, false, doc) + reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, (false, false), doc) } /// [`reshape_leaves_carrying`] whose paths keep to `budget` together, or to what they cost. #[cfg(test)] pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budget, doc: Option<&Document>) -> crate::Carry { - reshape_leaves_apart(art, fx, &[], budget, false, doc) + reshape_leaves_apart(art, fx, &[], budget, (false, false), doc) } /// `art`, the group of the one piece a path's copies are made from ([`outline_art_with`]), holding @@ -1191,7 +1325,10 @@ fn hoist_copies(art: &mut Node) { /// [`reshape_leaves_carrying`] whose paths keep to `budget` together, or to what they cost; with /// `apart`, a Transform effect's copies of each path are objects -/// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them. A live-effect +/// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them. With `rows`, +/// so are the copies of a path with a fill or stroke whose raster effects follow a Transform effect +/// ([`crate::raster::follows`]), and each copy's fills and strokes carry those raster effects moved, +/// turned, reflected and scaled with it ([`follow_copies`]). A live-effect /// plug-in that paints what it returns makes each path a group of its pieces ([`paint_leaf`]), /// whose swatches and patterns must be in `doc` (without one, pieces that name one are refused). /// Returns how gradients that paint the art as a whole follow the effects, and the Transform @@ -1202,7 +1339,14 @@ fn hoist_copies(art: &mut Node) { /// type and live objects in it outlined and evaluated first ([`outlined_members`]). When a mask /// stays as it was, or a Transform effect makes fewer copies than it asks for, art with linked /// masks keeps its shape under that effect. -fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget: Budget, apart: bool, doc: Option<&Document>) -> crate::Carry { +fn reshape_leaves_apart( + art: &mut Node, + fx: &[&Effect], + owner: &[Effect], + budget: Budget, + (apart, rows): (bool, bool), + doc: Option<&Document>, +) -> crate::Carry { let mut whole = crate::Carry::default(); if fx.is_empty() { return whole; @@ -1239,7 +1383,7 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget let params = merged_params(&e.id, &e.params); // Where a live-effect plug-in sits, which it is listed by when it is deferred. let effect = owner.iter().position(|x| std::ptr::eq(x, *e)).or_else(|| listed.iter().position(|x| std::ptr::eq(*x, *e))); - let step = Step { e, params: ¶ms, bounds, seed, effect, apart, doc, wholes: &wholes, held }; + let step = Step { e, params: ¶ms, bounds, seed, effect, apart, rows, doc, wholes: &wholes, held }; // Art with linked masks keeps its shape under an effect that a mask in it could not take // as the art it masks did, so no mask is left apart from its art. let before = masked.then(|| (art.clone(), used)); @@ -1283,6 +1427,7 @@ struct Step<'a> { seed: u64, effect: Option, apart: bool, + rows: bool, doc: Option<&'a Document>, wholes: &'a HashMap, held: bool, @@ -1447,8 +1592,12 @@ impl Step<'_> { // make together; and Expand Appearance (`apart`) makes each copy an object. // Fills and strokes that stack paint each copy below the one before (#5920, #6316). // Each copy of a path with a linked mask carries the mask, moved with it. + // With `rows`, each copy carries the raster effects of its fills and strokes, + // following that copy's map. + let rows = self.rows && copies > 0 && leaf.appearance.items.iter().any(follows_row_raster); let separate = copies > 0 && (self.apart + || rows || leaf.appearance.has_unplaced_gradient() || leaf.appearance.has_placed_gradient() || paints_copies_apart(&leaf.appearance, rule) @@ -1456,9 +1605,12 @@ impl Step<'_> { // The copies of a path replace it by a group of them, the path included. let copied = |leaf: &Node| leaf.children().map_or(0, Vec::len); if options.reach_appearance() { - let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, raster_map.is_some(), None); + let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, raster_map.is_some() || rows, None); *used = used.minus(before).plus(made); took |= moved; + if moved && rows { + follow_copies(leaf, map, None); + } if moved { // With Transform Objects off the path stays, and its mask takes the // effect's stroke and pattern changes as its own art. @@ -1474,6 +1626,9 @@ impl Step<'_> { if separate { let scaling = vectorcraft_doc::Scaling { keep_fit_when_flat: true, ..Default::default() }; let made = copy_leaf(leaf, &path, m, copies, scaling, room, None); + if rows { + follow_copies(leaf, m, None); + } *used = used.minus(before).plus(made); took = true; moved_ids.insert(leaf.id); @@ -1865,7 +2020,7 @@ fn transform_leaf( kept: Kept, ) -> (Budget, bool) { let mut scaling = copy_scaling(options); - if follows && copies == 0 { + if follows { scaling.effects = options.strokes.then_some(scale_unfollowed as fn(&mut Effect, f64)); } if !options.objects { @@ -2181,7 +2336,8 @@ fn paint_piece( /// Every path and compound path under `art` (other than clipping paths) with a fill or stroke whose /// own Transform effect has Transform Patterns or Scale Strokes & Effects on -/// ([`item_transform_options`]), or whose own live-effect plug-in paints what it returns +/// ([`item_transform_options`]) or makes copies that carry the raster effects before it +/// ([`copied_row_raster_at`]), or whose own live-effect plug-in paints what it returns /// ([`painted_plugin`]), made into a group of objects of its own ([`transform_item_leaf`]). The /// new paths keep to one [`Budget::EFFECTS`] together (or to what `art` costs, when that is more). /// The swatches and patterns painted pieces name must be in `doc`; without one they may name none. @@ -2198,9 +2354,20 @@ fn makes_piece(e: &Effect) -> bool { reaches_appearance(e) || painted_plugin(e).is_some() } -/// Does `item` paint and carry an effect that [`makes_piece`]? +/// Where the fill's or stroke's own effects `fx` make its piece of a path an object of its own: the +/// index of the first effect that [`makes_piece`], or of the Transform effect whose copies carry the +/// raster effects before it ([`copied_row_raster_at`]), whichever is listed first. +fn piece_at(fx: &[Effect]) -> Option { + let copied = copied_row_raster_at(fx); + match fx.iter().position(makes_piece) { + Some(at) => Some(copied.map_or(at, |t| t.min(at))), + None => copied, + } +} + +/// Does `item` paint and carry an effect that makes its piece an object of its own ([`piece_at`])? fn item_makes_piece(item: &AppearanceItem) -> bool { - crate::paints(item) && item.effects().iter().any(makes_piece) + crate::paints(item) && piece_at(item.effects()).is_some() } /// `leaf`, a path or compound path with a fill or stroke whose own Transform effect has Transform @@ -2210,12 +2377,17 @@ fn item_makes_piece(item: &AppearanceItem) -> bool { /// as [`transform_leaf`] transforms an object with that effect's map, copies and options, so the /// stroke's weight and dashes, the distances of the effects before the Transform effect and its /// pattern follow the map, and the raster effects before it that follow it take their followed -/// values ([`follow_piece`]). The effects after it keep their values and apply to what it made +/// values ([`follow_piece`]), on each copy the values that copy's map gives them +/// ([`follow_copies`]). The effects after it keep their values and apply to what it made /// ([`keep_listed`]), and with Transform Objects off so do the effects before it. The reference box /// is that geometry's bounds and the seed is the leaf's id, as the renderer draws a fill's or -/// stroke's own effects. The geometry effects after the Transform effect then +/// stroke's own effects. A fill or stroke whose first such Transform effect makes copies that carry +/// the raster effects before it ([`copied_row_raster_at`]) becomes a path of its own the same way, +/// with neither option. The geometry effects after the Transform effect then /// apply to the transformed path and its copies as one piece ([`transform_piece`]), and its other -/// effects stay on each of them. The other fills and strokes stay together on paths of the leaf's +/// effects stay on each of them, except that without either option the raster effects after a +/// Transform effect that makes copies paint once around all of them ([`lift_later_raster`]). The +/// other fills and strokes stay together on paths of the leaf's /// geometry between them, with their own effects. `max` is the budget of the whole art and `used` /// what it has spent. /// @@ -2261,7 +2433,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt let later = |i: usize| (i + 1..transformed.len()).filter(|&j| transformed[j] || j == i + 1 || transformed[j - 1]).count(); for (i, item) in original.appearance.items.iter().enumerate() { let fx = item.effects(); - let Some(at) = fx.iter().position(makes_piece).filter(|_| crate::paints(item)) else { + let Some(at) = piece_at(fx).filter(|_| crate::paints(item)) else { plain.push(item.clone()); continue; }; @@ -2339,13 +2511,24 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt set_geometry(&mut p, g.clone(), rule); let after = kept_before.len(); let keep = |k: usize| k >= after || !options.objects; - let (made, moved) = transform_leaf(&mut p, &g, map, copies, options, room, false, Some((&rest, &keep))); - *used = used.plus(made); let from = crate::raster::held_back(before); - if moved && !held_later { + // Each copy carries the raster effects before the Transform effect, following that copy's + // map, unless a Transform effect before or after it holds them back. + let copied = copies > 0 && !held_later && from == 0; + let (made, moved) = transform_leaf(&mut p, &g, map, copies, options, room, copied, Some((&rest, &keep))); + *used = used.plus(made); + if moved && copied { + follow_copies(&mut p, map, Some(0..after)); + } else if moved && !held_later { follow_piece(&mut p, kept_before.get(from..).unwrap_or_default(), from, &fx[at]); } transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(&fx[..=at]), false, limit, used, doc); + // Without Transform Patterns and Scale Strokes & Effects, the raster effects after the + // Transform effect paint once around all the copies, as they paint around the one path of + // every copy. + if copies > 0 && !options.reach_appearance() { + lift_later_raster(&mut p, after); + } pieces.push(Arc::new(p)); } if !plain.is_empty() { @@ -2396,6 +2579,7 @@ fn transform_piece( count = count.max(item.effects().len()); } }); + let outer = held; // The effects before a Transform effect among the piece's effects that makes copies or moves at // random are held back from the Transform effects before it too. let mut held = held; @@ -2416,7 +2600,7 @@ fn transform_piece( let from = held.min(j); let mut holds = false; let stage = vectorcraft_plugins::deferred::Stage { object: seed, effect: kept.get(j).copied().unwrap_or(j), item: Some(source) }; - let at = PieceStage { j, from, seed, bounds, doc, stage }; + let at = PieceStage { j, from, outer, seed, bounds, doc, stage }; // Stage `j` on `leaf`, a path `used` counts at `piece_cost` when `share`: whether `used` // counts each path it became so, or `None` when it stays as it was. let mut on_leaf = |leaf: &mut Node, share: bool| -> Option> { @@ -2637,12 +2821,14 @@ thread_local! { /// Where a stage of [`transform_piece`] runs: `j`, the index of its effect among the piece's /// effects; `from`, the first of the effects before it whose raster effects follow a Transform -/// effect; the object's `seed`; the reference box `bounds` of all the piece's paths; the document -/// that painted pieces' swatches and patterns must be in; and the `stage` a deferred live-effect -/// plug-in is listed by. +/// effect; `outer`, how many of the piece's effects a Transform effect before them holds back; the +/// object's `seed`; the reference box `bounds` of all the piece's paths; the document that painted +/// pieces' swatches and patterns must be in; and the `stage` a deferred live-effect plug-in is +/// listed by. struct PieceStage<'a> { j: usize, from: usize, + outer: usize, seed: u64, bounds: Rect, doc: Option<&'a Document>, @@ -2685,15 +2871,30 @@ fn piece_stage(leaf: &mut Node, e: &Effect, at: &PieceStage, (appearance, index) let params = merged_params(&e.id, &e.params); return paint_piece(leaf, &item, (appearance, index), (plugin, ¶ms), at.bounds, room, at.doc, Some(at.stage)); } - if reaches_appearance(e) { + let copied = copies_carry(item.effects(), e, at); + if reaches_appearance(e) || copied { let params = merged_params(&e.id, &e.params); let (_, copies) = crate::distort::transform_map(at.bounds, ¶ms, at.seed); let options = crate::distort::TransformOptions::of(¶ms); let map = crate::distort::transform_affine(at.bounds, ¶ms, at.seed); let j = at.j; let keep = |k: usize| k > j || (k < j && !options.objects); - let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, false, Some((item.effects(), &keep))); - if moved { + let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, copied, Some((item.effects(), &keep))); + if moved && copied { + // Each copy's raster effects before the Transform effect follow that copy's map. The + // Transform effects before it have already moved them, so each run between two of + // them follows on its own. + let fx = item.effects(); + let mut start = 0; + for k in 0..=j { + if k == j || fx.get(k).is_some_and(|f| f.id == "distort.transform") { + if start < k { + follow_copies(leaf, map, Some(start..k)); + } + start = k + 1; + } + } + } else if moved { follow_piece(leaf, was, at.from, e); } return Some(made); @@ -2718,6 +2919,37 @@ fn piece_stage(leaf: &mut Node, e: &Effect, at: &PieceStage, (appearance, index) Some(made) } +/// Does Transform effect `e`, at stage `at` of [`transform_piece`] of a fill or stroke whose effects +/// are `fx`, make copies that each carry the raster effects listed before it, following that copy's +/// map ([`follow_copies`]), as the copies of the piece's first Transform effect do +/// ([`transform_item_leaf`])? It does when it makes copies with Transform Objects on, a visible +/// raster effect that follows a Transform effect ([`crate::raster::follows`]) is listed before it, +/// and no Transform effect that makes copies or moves at random holds those raster effects back: +/// none before the piece's effects, none listed before it after such a raster effect, and none +/// after it. Without Transform Patterns and Scale Strokes & Effects, every other visible effect +/// before it must also be a geometry effect or such a raster effect, and no visible raster effect +/// may be listed after it, as for [`copied_row_raster_at`]. +fn copies_carry(fx: &[Effect], e: &Effect, at: &PieceStage) -> bool { + if !e.visible || e.id != "distort.transform" || at.outer > 0 { + return false; + } + let params = merged_params(&e.id, &e.params); + if !crate::distort::TransformOptions::of(¶ms).objects || crate::distort::transform_map(Rect::ZERO, ¶ms, 0).1 == 0 { + return false; + } + let before = fx.get(..at.j).unwrap_or_default(); + let after = fx.get(at.j + 1..).unwrap_or_default(); + if crate::raster::held_back(before) > 0 + || !before.iter().any(|f| f.visible && crate::raster::follows(&f.id)) + || after.iter().any(crate::raster::holds_back) + { + return false; + } + reaches_appearance(e) + || (before.iter().all(|f| !f.visible || is_geometry(&f.id) || crate::raster::follows(&f.id)) + && !after.iter().any(|f| f.visible && crate::is_raster(&f.id))) +} + /// Are `a` and `b` paths or compound paths that differ only in their fills and strokes? fn same_path(a: &Node, b: &Node) -> bool { let leaf = |n: &Node| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }); @@ -2790,6 +3022,52 @@ fn follow_piece(leaf: &mut Node, was: &[Effect], from: usize, t: &Effect) { } } +/// Make the raster effects that follow a Transform effect ([`crate::raster::follows`]) on the fills +/// and strokes of each copy [`copy_leaf`] made of `leaf` with map `m` follow that copy's map: the +/// copy `k` places below the original takes the linear part of `m` `k` times +/// ([`crate::raster::follow_contents`]), and the original, on top, keeps its effects. `range`, when +/// given, is which of each fill's or stroke's effects follow; the others keep their values. +fn follow_copies(leaf: &mut Node, m: Affine, range: Option>) { + let step = m.with_translation(vectorcraft_geom::Vec2::ZERO); + let Some(children) = leaf.children_mut() else { return }; + let mut a = Affine::IDENTITY; + for c in children.iter_mut().rev().skip(1) { + a *= step; + for item in &mut Arc::make_mut(c).appearance.items { + let fx = item.effects_mut(); + let fx = match &range { + Some(r) => fx.get_mut(r.clone()).unwrap_or_default(), + None => fx.as_mut_slice(), + }; + crate::raster::follow_contents(fx, a, Affine::IDENTITY); + } + } +} + +/// Move the raster effects from index `after` on of the fills and strokes of the paths under `p`, +/// a group of copies of one fill or stroke with the same effects, onto `p` itself, so they paint +/// once around all of the copies. The other effects stay where they are. +fn lift_later_raster(p: &mut Node, after: usize) { + if p.children().is_none() { + return; + } + let mut lifted: Option> = None; + for_each_leaf(p, &mut |l| { + for item in &mut l.appearance.items { + let fx = item.effects_mut(); + if fx.len() <= after { + continue; + } + let (raster, other): (Vec, Vec) = fx.split_off(after).into_iter().partition(|e| crate::is_raster(&e.id)); + fx.extend(other); + lifted.get_or_insert(raster); + } + }); + if let Some(raster) = lifted { + p.appearance.effects.extend(raster); + } +} + /// The bounds of each group of type's outlines under `n` ([`outline_text`]), `n` included, in /// order. A group inside one of them is part of it. fn type_outline_bounds(n: &Node, out: &mut Vec>) { diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index a49e817ef2..c065e507df 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use serde_json::Value; use vectorcraft_doc::color::{Color, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId, NodeKind}; -use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2}; +use vectorcraft_geom::{FillRule, PathData, PathEl, Point, Rect, Vec2}; use vectorcraft_three_d::{Edge, Revolve, SolidFaces}; use crate::solids::wireframe::{WireFace, wireframe_params}; @@ -105,6 +105,7 @@ pub fn revolve_options(p: &Value) -> Revolve { shade: flag(p, "shade", true), smooth_shading: true, cap_ends: flag(p, "cap", true), + fill_rule: FillRule::NonZero, curve_samples: None, map_surface: false, } @@ -231,7 +232,7 @@ fn check_shadow<'a>(p: &Value, paths: impl IntoIterator, b: return Ok(()); } let mut caster = vectorcraft_three_d::ShadowCaster::new(); - paths.into_iter().try_for_each(|path| caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options).map(|_| ())) + paths.into_iter().try_for_each(|path| caster.revolve(path, options.fill_rule, b, options).map(|_| ())) } /// [`validate_revolve`] for a Revolve with parameters `p` at index `index` of the effects of @@ -296,11 +297,35 @@ fn paint_copies(faces: usize, paint: &Paint) -> usize { faces.saturating_mul(4).saturating_mul(paint_bytes(paint)) } +/// Do Revolve's `options` light its surface with colored lights? +fn colored(options: &Revolve) -> bool { + options.light_color != [1.0; 3] || options.lights.is_some() +} + +/// Do Revolve's `faces` in `paint` lie over an underlay of themselves ([`sealed_run`])? Under +/// colored lights (`colored`), in a solid color or a gradient, when a face takes a smooth light +/// ramp ([`crate::lighting::rgb_gradient_art`], [`crate::lighting::gradient_art`], +/// [`crate::lighting::smooth_paint`]). Not in a gradient with transparent stops: its composed faces +/// carry its opacity mask, which the underlay does not take ([`crate::lighting::underlay`]). +fn seals(faces: &[vectorcraft_three_d::Face], paint: &Paint, colored: bool) -> bool { + colored + && (matches!(paint, Paint::Gradient(_)) || paint.color().is_some()) + && faces.iter().any(|f| f.rgb_gradient.is_some() || f.light_gradient.is_some()) + && crate::lighting::opaque_paint(paint).1.is_none() +} + +/// The bytes the copies of `paint` take on Revolve's `faces` ([`paint_copies`]), twice that when the +/// faces lie over an underlay of themselves ([`seals`]). +fn surface_copies(faces: &[vectorcraft_three_d::Face], paint: &Paint, colored: bool) -> usize { + let copies = paint_copies(faces.len(), paint); + if seals(faces, paint, colored) { copies.saturating_mul(2) } else { copies } +} + /// An error when `path` does not revolve or when its surface in `item`'s paint takes `copies`, the /// bytes of an object's paint copies so far, past [`MAX_PAINT_COPIES`]. fn check_surface(path: &PathData, b: Rect, options: Revolve, item: Option<&AppearanceItem>, copies: &mut usize) -> Result<(), String> { let faces = vectorcraft_three_d::revolve(path, b, options)?; - *copies = copies.saturating_add(item.map_or(0, |i| paint_copies(faces.len(), &paint_of(i).0))); + *copies = copies.saturating_add(item.map_or(0, |i| surface_copies(&faces, &paint_of(i).0, colored(&options)))); if *copies > MAX_PAINT_COPIES { return Err("Revolve paint is too complex for this surface; reduce Segments or simplify the gradient".into()); } @@ -394,7 +419,7 @@ fn cast_surface( None => { #[cfg(test)] crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); - caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options) + caster.revolve(path, options.fill_rule, b, options) } } } @@ -425,7 +450,7 @@ fn group_shadow( if !ink.casts() { continue; } - let faces = cast_surface(&mut caster, &s.path, b, options, kept)?; + let faces = cast_surface(&mut caster, &s.path, b, Revolve { fill_rule: s.rule, ..options }, kept)?; cast.push((s.scopes.as_slice(), ink, faces)); } Ok(crate::solids::shadow::scoped_art(id, &caster, settings, cast, crate::solids::has_masks(shapes))) @@ -438,7 +463,9 @@ fn group_shadow( /// with its classic surface, as Extrude & Bevel (Classic) does. Revolve's graphics, with the /// symbols of `doc`, are drawn on the faces of the side ([`crate::solids::graphics::surface_parts`]): /// a face with a part of a graphic is a group of the face and that part. With `cast`, the sweep -/// that draws the surface also keeps the faces its shadow is cast from ([`SolidFaces`]). +/// that draws the surface also keeps the faces its shadow is cast from ([`SolidFaces`]). The last +/// value is whether the faces go over an underlay of themselves ([`seals`]): the caller seals them +/// ([`sealed_surface`], [`sealed_runs`]) in the order it draws them. #[allow(clippy::too_many_arguments)] fn surface( doc: Option<&Document>, @@ -453,7 +480,7 @@ fn surface( expand: bool, copies: &mut Copies, cast: bool, -) -> Option<(Vec, Node, Option)> { +) -> Option<(Vec, Node, Option, bool)> { #[cfg(test)] crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); // A loaded file or a profile edited past the limits keeps drawing its source path instead @@ -473,15 +500,16 @@ fn surface( let drawn = facets.iter().map(|f| Drawn { depth: f.depth, points: f.contours.first().cloned().unwrap_or_default(), plane: f.plane }).collect(); let p = merged_params(&fx.id, &fx.params); - return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p), kept)); + return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p), kept, false)); } - let colored = options.light_color != [1.0; 3] || options.lights.is_some(); + let colored = colored(&options); let (faces, kept) = if cast { vectorcraft_three_d::revolve_shadowed(path, b, options).ok().map(|(f, kept)| (f, Some(kept)))? } else { (vectorcraft_three_d::revolve(path, b, options).ok()?, None) }; - copies.surfaces = copies.surfaces.saturating_add(paint_copies(faces.len(), &paint)); + let seal = seals(&faces, &paint, colored); + copies.surfaces = copies.surfaces.saturating_add(surface_copies(&faces, &paint, colored)); if copies.surfaces > MAX_PAINT_COPIES { return None; } @@ -604,7 +632,62 @@ fn surface( let mut group = Node::group(n.id, children); group.opacity = opacity; group.blend = blend; - Some((keys, group, kept)) + Some((keys, group, kept, seal)) +} + +/// Plain `surface` ([`surface`]: a group of its faces) over an underlay of its faces when `seal` +/// ([`sealed_run`]), keeping the surface's opacity and blending mode. +fn sealed_surface(id: NodeId, surface: Node, seal: bool) -> Node { + let NodeKind::Group { children, clip: false } = &surface.kind else { return surface }; + let Some(mut out) = seal.then(|| sealed_run(id, children)).flatten() else { return surface }; + out.opacity = surface.opacity; + out.blend = surface.blend; + out +} + +/// The faces `run` of one surface, in drawing order, over an underlay of themselves, all clipped +/// once to the faces' outline, as [`crate::lighting::sealed`] draws them. A face drawn with a part +/// of a graphic, a group of the face and that part, takes its face's underlay and stays in the +/// order with its part; the part is cut to its face's outline ([`crate::solids::graphics::surface_parts`]), +/// so the clip keeps it. `None` when [`crate::lighting::underlay`] does not take the faces. +fn sealed_run(id: NodeId, run: &[Arc]) -> Option { + let faces: Vec> = run + .iter() + .map(|face| match &face.kind { + NodeKind::Group { children, clip: false } => children.first().cloned(), + _ => Some(face.clone()), + }) + .collect::>()?; + if faces.is_empty() { + return None; + } + let (clip, mut underlay) = crate::lighting::underlay(id, &faces)?; + underlay.extend(run.iter().cloned()); + Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, underlay))], clip: true })) +} + +/// `faces` in their drawing order, each with the index of its surface. Each run of consecutive +/// faces of one surface that `seal` takes lies over an underlay of its own faces ([`sealed_run`]), +/// so no underlay reaches under another surface's faces, as Inflate's surfaces do +/// (`crate::solids::underlaid_runs`). A run the underlay does not take keeps its faces. +fn sealed_runs(id: NodeId, faces: Vec<(usize, Arc)>, seal: impl Fn(usize) -> bool) -> Vec> { + let mut out = Vec::with_capacity(faces.len()); + let mut run: Vec> = vec![]; + let mut faces = faces.into_iter().peekable(); + while let Some((surface, face)) = faces.next() { + run.push(face); + if faces.peek().is_some_and(|(next, _)| *next == surface) { + continue; + } + match seal(surface).then(|| sealed_run(id, &run)).flatten() { + Some(sealed) => { + out.push(Arc::new(sealed)); + run.clear(); + } + None => out.append(&mut run), + } + } + out } /// A face [`surface`] draws: its depth and, for [`crate::solids::surface_order`], its polygon on the @@ -621,13 +704,16 @@ fn in_order(items: Vec, order: &[usize]) -> Vec { order.iter().filter_map(|&k| slots.get_mut(k).and_then(Option::take)).collect() } -/// A surface of one object about the bounds of `path`, built with options derived from `fx`, and -/// when `fx` casts a shadow from it, the faces it is cast from ([`surface`]). `copies` is the count -/// [`surface`] adds to; its graphics take the symbols of `doc`. +/// A surface of one object about the bounds of `path`, filled with `rule`, built with options +/// derived from `fx` ([`rule_options`]), and when `fx` casts a shadow from it, the faces it is cast +/// from ([`surface`]). `copies` is the count [`surface`] adds to; its graphics take the symbols of +/// `doc`. +#[allow(clippy::too_many_arguments)] fn object_surface( doc: Option<&Document>, n: &Node, path: &PathData, + rule: FillRule, fx: &Effect, item: &AppearanceItem, expand: bool, @@ -636,7 +722,14 @@ fn object_surface( let b = path.bounds()?; let (paint, opacity, blend) = paint_of(item); let cast = casts(fx, opacity); - surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies, cast).map(|(_, art, kept)| (art, kept)) + surface(doc, n, path, b, rule_options(fx, rule), fx, paint, opacity, blend, expand, copies, cast) + .map(|(_, art, kept, seal)| (sealed_surface(n.id, art, seal), kept)) +} + +/// The options effect `fx` sweeps the surface of a profile filled with `rule` with: its cut sides +/// leave open the holes `rule` leaves in the profile. +fn rule_options(fx: &Effect, rule: FillRule) -> Revolve { + Revolve { fill_rule: rule, ..fx_options(fx) } } /// The paint of a graphic's solid color `c` on `face`, shaded as the face shades a solid fill of @@ -757,13 +850,13 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result, n: &Node) -> Result, n: &Node) -> Result Result Ok(vectorcraft_three_d::revolve(path, b, options)?.iter().map(|f| WireFace { path: f.path(), stroke: SEAM_WIDTH }).collect()) } -/// The art Revolve `fx` in wireframe mode draws for object `id` from the profiles `paths`, all swept -/// about the bounds `b` with `options`: the edges of their faces ([`crate::solids::wireframe::wire_art`]). -/// `None` when a profile can't be swept or past the edge limit, when the canvas draws the source art. -fn wire_art<'a>(id: NodeId, paths: impl IntoIterator, b: Rect, fx: &Effect, options: Revolve) -> Option> { +/// The art Revolve `fx` in wireframe mode draws for object `id` from the profiles `paths`, each with +/// its fill rule, all swept about the bounds `b` with `options`: the edges of their faces +/// ([`crate::solids::wireframe::wire_art`]). `None` when a profile can't be swept or past the edge +/// limit, when the canvas draws the source art. +fn wire_art<'a>(id: NodeId, paths: impl IntoIterator, b: Rect, fx: &Effect, options: Revolve) -> Option> { let mut faces = vec![]; - for path in paths { - faces.extend(wire_faces(path, b, fx, options).ok()?.into_iter().map(|f| f.path)); + for (path, rule) in paths { + faces.extend(wire_faces(path, b, fx, Revolve { fill_rule: rule, ..options }).ok()?.into_iter().map(|f| f.path)); } crate::solids::wireframe::wire_art(id, &faces) } @@ -857,11 +951,11 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); if crate::solids::renders_wireframe(fx) { // In wireframe mode the edges of the faces, with no shadow. - children.push(wire_art(n.id, [&path], path.bounds()?, fx, fx_options(fx))?); + children.push(wire_art(n.id, [(&path, rule)], path.bounds()?, fx, fx_options(fx))?); } else { - let (surface, kept) = object_surface(doc, n, &path, fx, item, expand, &mut copies)?; + let (surface, kept) = object_surface(doc, n, &path, rule, fx, item, expand, &mut copies)?; if let Some(b) = path.bounds() - && let Some(shadow) = shadow_of(n.id, fx, &path, item, b, fx_options(fx), kept).ok()? + && let Some(shadow) = shadow_of(n.id, fx, &path, item, b, rule_options(fx, rule), kept).ok()? { children.push(Arc::new(shadow)); } @@ -887,18 +981,19 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original)); let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); if crate::solids::renders_wireframe(fx) { - let mut art = wire_art(n.id, [&p], p.bounds()?, fx, fx_options(fx))?; + let mut art = wire_art(n.id, [(&p, rule)], p.bounds()?, fx, fx_options(fx))?; Arc::make_mut(&mut art).appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect(); children.push(art); continue; } - let (mut art, kept) = object_surface(doc, n, &p, fx, item, expand, &mut copies)?; + let (mut art, kept) = object_surface(doc, n, &p, rule, fx, item, expand, &mut copies)?; art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect(); if let Some(b) = p.bounds() - && let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, fx_options(fx), kept).ok()? + && let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, rule_options(fx, rule), kept).ok()? { - shadow.appearance.effects = art.appearance.effects.clone(); + // The shadow keeps its own blur (the light's Softness) below the later effects. + shadow.appearance.effects.extend(art.appearance.effects.iter().cloned()); shadows.push(Arc::new(shadow)); } children.push(Arc::new(art)); @@ -1044,7 +1139,7 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let options = shared_options(&shapes, fx_options(fx)).ok()?; if crate::solids::renders_wireframe(fx) { // In wireframe mode the edges of every member's faces, with no shadow. - let paths = shapes.iter().filter(|s| surface_item(&s.items).is_some()).map(|s| &s.path); + let paths = shapes.iter().filter(|s| surface_item(&s.items).is_some()).map(|s| (&s.path, s.rule)); let mut art = n.clone(); art.kind = NodeKind::Group { children: vec![wire_art(n.id, paths, b, fx, options)?], clip: false }; art.appearance = Appearance { effects: past_effect(&n.appearance.effects, index), ..Default::default() }.into(); @@ -1055,6 +1150,8 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let mut surfaces = vec![]; // The faces each member's surface kept for the shadow, member by member. let mut kept = vec![]; + // Whether each member's faces lie over an underlay of themselves ([`surface`]). + let mut seals = vec![]; let mut opaque = true; // The graphics go once, on the side of the member with the longest profile. Without graphics // no member is measured for them. @@ -1072,10 +1169,15 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let expand = expand && s.scopes.is_empty(); let doc = doc.filter(|_| longest == Some(k)); let cast = casts(fx, opacity * s.opacity); - let (depths, art, faces) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies, cast)?; + let options = Revolve { fill_rule: s.rule, ..options }; + let (depths, art, faces, seal) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies, cast)?; surfaces.push((depths, art, s.scopes.as_slice())); kept.push(faces); + seals.push(seal); } + // The faces of a member whose surface takes an underlay lie over one, run by run in the one + // order of every member's faces ([`sealed_runs`]). + let seal = |member: usize| seals.get(member) == Some(&true); if surfaces.is_empty() { return None; } @@ -1101,7 +1203,7 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let order = crate::solids::surface_order(faces.iter().map(|(d, ..)| (d.points.as_slice(), d.plane, d.depth))); let faces = in_order(faces, &order); if opaque { - vec![Arc::new(Node::group(n.id, faces.into_iter().map(|(.., face)| face).collect()))] + vec![Arc::new(Node::group(n.id, sealed_runs(n.id, faces.into_iter().map(|(_, member, .., face)| (member, face)).collect(), seal)))] } else { // An opaque member's face goes in the order on its own. The faces of a member with // transparency share a run, one group with the opacity and blending mode of its fill or @@ -1110,6 +1212,8 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { // where one group can't be both behind and in front of another face. struct Run<'a> { member: Option, + // The member the faces are of. + of: usize, scopes: &'a [Scope], bounds: Rect, faces: Vec>, @@ -1125,12 +1229,12 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let paints = opacity > 0.0 && scopes.iter().all(|s| s.opacity > 0.0); let Some(cover) = Coverage::of(&face).filter(|_| paints) else { // A face that paints nothing goes in the order on its own and overlaps nothing. - runs.push(Run { member: None, scopes, bounds: Rect::ZERO, faces: vec![face], cover: vec![], opacity, blend }); + runs.push(Run { member: None, of: member, scopes, bounds: Rect::ZERO, faces: vec![face], cover: vec![], opacity, blend }); continue; }; let masked = masks.get(member).is_some_and(Option::is_some); if opacity >= 1.0 && blend == Default::default() && scopes.is_empty() && !masked { - runs.push(Run { member: None, scopes, bounds: cover.bounds, faces: vec![face], cover: vec![cover], opacity, blend }); + runs.push(Run { member: None, of: member, scopes, bounds: cover.bounds, faces: vec![face], cover: vec![cover], opacity, blend }); continue; } let mut clear = |r: &Run| { @@ -1153,24 +1257,49 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { if let Some(last) = last_run.get_mut(member) { *last = Some(runs.len()); } - runs.push(Run { member: Some(member), scopes, bounds: cover.bounds, faces: vec![face], cover: vec![cover], opacity, blend }); + runs.push(Run { + member: Some(member), + of: member, + scopes, + bounds: cover.bounds, + faces: vec![face], + cover: vec![cover], + opacity, + blend, + }); } } } - let runs = runs.into_iter().filter_map(|mut r| { + // Consecutive faces of opaque members on their own wait in `solo` and go over an + // underlay of their member's faces, run by run ([`sealed_runs`]). + let mut out: Vec<(&[Scope], Arc)> = Vec::with_capacity(runs.len()); + let mut solo: Vec<(usize, Arc)> = vec![]; + for mut r in runs { // A face on its own needs a group only for the opacity or blending mode of its fill or stroke. if r.member.is_none() && r.opacity >= 1.0 && r.blend == Default::default() { - return r.faces.pop().map(|face| (r.scopes, face)); + let Some(face) = r.faces.pop() else { continue }; + if r.scopes.is_empty() && !r.cover.is_empty() { + solo.push((r.of, face)); + } else { + out.extend(sealed_runs(n.id, std::mem::take(&mut solo), seal).into_iter().map(|face| (&[][..], face))); + out.push((r.scopes, face)); + } + continue; } - let mut group = Node::group(n.id, r.faces); + out.extend(sealed_runs(n.id, std::mem::take(&mut solo), seal).into_iter().map(|face| (&[][..], face))); + let mut group = match r.member.filter(|m| seal(*m)).and_then(|_| sealed_run(n.id, &r.faces)) { + Some(sealed) => sealed, + None => Node::group(n.id, r.faces), + }; group.opacity = r.opacity; group.blend = r.blend; if let Some(mask) = r.member.and_then(|m| masks.get(m)).cloned().flatten() { group.extras_mut().mask = Some(mask); } - Some((r.scopes, Arc::new(group))) - }); - scoped(n.id, runs.collect(), 0) + out.push((r.scopes, Arc::new(group))); + } + out.extend(sealed_runs(n.id, solo, seal).into_iter().map(|face| (&[][..], face))); + scoped(n.id, out, 0) } }; // One shadow for every member's surface, behind them all. @@ -1693,6 +1822,156 @@ mod tests { assert_eq!(revolve_art(&two), None, "past the budget the source draws"); let object = painted(3, 0.0, stops * 2); assert!(validate_revolve(&object, &json!({})).is_err(), "one object past the budget"); + // Under a colored light the faces lie over an underlay of themselves, which copies their + // paints again: the gradient that fits in white light is past the budget. + let lit = json!({"lightColor": "#ff0000"}); + let object = painted(4, 0.0, stops); + assert_eq!(validate_revolve(&object, &json!({})), Ok(())); + let refused = validate_revolve(&object, &lit).unwrap_err(); + assert!(refused.contains("simplify the gradient"), "{refused}"); + let mut drawn = (*object).clone(); + drawn.appearance.effects.push(crate::new_effect(REVOLVE, &lit).unwrap()); + assert_eq!(revolve_art(&drawn), None, "past the budget the source draws"); + } + + /// Is `u` the underlay [`crate::lighting::underlay`] draws for `face`, a face [`surface`] draws? + fn underlies(u: &Node, face: &Node) -> bool { + match (&u.kind, &face.kind) { + (NodeKind::Path { .. }, NodeKind::Path { .. }) => { + u.path_data() == face.path_data() + && u.appearance.items.iter().all(|i| !matches!(i, AppearanceItem::Stroke(s) if s.width != crate::lighting::UNDERLAY_SEAM)) + } + (NodeKind::Group { children: under, clip: true }, NodeKind::Group { children, clip: true }) => { + matches!((under.get(1), children.get(1)), (Some(a), Some(b)) if Arc::ptr_eq(a, b)) + } + (_, NodeKind::Group { children, clip: false }) => children.first().is_some_and(|f| underlies(u, f)), + _ => false, + } + } + + /// The runs of faces in `art` that lie over an underlay of themselves ([`sealed_run`]), each + /// run's faces in drawing order. + pub(super) fn sealed_faces(art: &Node) -> Vec>> { + let mut out = vec![]; + art.walk(&mut |n| { + let NodeKind::Group { children, clip: true } = &n.kind else { return }; + let [clip, inner] = &children[..] else { return }; + let NodeKind::Group { children: drawn, clip: false } = &inner.kind else { return }; + let (under, faces) = drawn.split_at(drawn.len() / 2); + if clip.path_data().is_some() && !inner.isolate && drawn.len() % 2 == 0 && under.iter().zip(faces).all(|(u, f)| underlies(u, f)) { + out.push(faces.to_vec()); + } + }); + out + } + + /// `n`'s surface as [`surface`] draws it before its faces are sealed, and whether they are. + fn unsealed(n: &Node) -> (Node, bool) { + let path = n.path_data().unwrap(); + let fx = n.appearance.effects.first().unwrap(); + let (paint, opacity, blend) = paint_of(n.appearance.items.first().unwrap()); + let (_, art, _, seal) = + surface(None, n, path, path.bounds().unwrap(), fx_options(fx), fx, paint, opacity, blend, false, &mut Copies::default(), false).unwrap(); + (art, seal) + } + + #[test] + fn colored_light_faces_lie_over_an_underlay_of_themselves_once_per_surface() { + use vectorcraft_doc::color::{BlendMode, Gradient, GradientKind, GradientPaint, GradientStop}; + let lit = |params: Value, paint: Paint| { + let mut n = profile_node(); + n.appearance = Appearance::basic(paint, Paint::None, 0.0).into(); + n.appearance.effects.push(crate::new_effect(REVOLVE, ¶ms).unwrap()); + n + }; + let red = Paint::solid(Color::rgb(0.8, 0.2, 0.1)); + let ramp = |opacity: f32| { + let stops = [Color::WHITE, Color::rgb(0.5, 0.5, 0.5)].into_iter().enumerate(); + let stops = stops.map(|(i, c)| GradientStop { opacity, ..GradientStop::new(i as f32, c) }).collect(); + Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))) + }; + let lights = json!([{"color": "#ff8080", "rotation": 120.0}, {"color": "#8080ff", "rotation": -30.0}]); + // In white light nothing is sealed. + let white = lit(json!({}), red.clone()); + assert!(!unsealed(&white).1); + assert!(sealed_faces(&revolve_art(&white).unwrap()).is_empty()); + for (name, n) in [ + ("solid", lit(json!({"lightColor": "#ff0000"}), red.clone())), + ("gradient", lit(json!({"lightColor": "#ff0000"}), ramp(1.0))), + ("two lights", lit(json!({"lights": lights}), ramp(1.0))), + ("edge-on", lit(json!({"lightColor": "#ff0000", "rotationX": -80}), red.clone())), + ] { + // Every face of the surface, in its order, lies over its underlay, once. + let (plain, seal) = unsealed(&n); + assert!(seal, "{name}"); + let faces = plain.children().unwrap().to_vec(); + assert_eq!(sealed_faces(&revolve_art(&n).unwrap()), vec![faces], "{name}"); + } + // The surface's opacity and blending mode apply once, to the sealed surface. + let mut n = lit(json!({"lightColor": "#ff0000"}), ramp(1.0)); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.opacity = 0.5; + f.blend = BlendMode::Multiply; + } + let art = revolve_art(&n).unwrap(); + assert_eq!(sealed_faces(&art).len(), 1); + // Inside the surface only a face's own lit art blends (its light multiplied over its paint). + let once = |chain: &Chain| chain.first() == Some(&(0.5, BlendMode::Multiply)) && chain.iter().skip(1).all(|(o, _)| *o == 1.0); + let faces = faces_in_order(&art); + assert!(faces.iter().all(|(_, chain)| once(chain)), "{:?}", faces.iter().map(|f| &f.1).find(|c| !once(c))); + // Faces in a gradient with transparent stops carry its opacity mask, which the underlay + // does not take: the surface keeps its faces as they are, and their paints are not + // counted twice. + let n = lit(json!({"lightColor": "#ff0000"}), ramp(0.6)); + let (plain, seal) = unsealed(&n); + assert!(!seal); + assert_eq!(sealed_surface(n.id, plain.clone(), true), plain); + assert!(sealed_faces(&revolve_art(&n).unwrap()).is_empty()); + let path = n.path_data().unwrap(); + let faces = vectorcraft_three_d::revolve(path, path.bounds().unwrap(), fx_options(&n.appearance.effects[0])).unwrap(); + assert_eq!(surface_copies(&faces, &ramp(0.6), true), paint_copies(faces.len(), &ramp(0.6))); + assert_eq!(surface_copies(&faces, &ramp(1.0), true), 2 * paint_copies(faces.len(), &ramp(1.0))); + // Revolve (Classic) takes no colored light, so none of its faces are sealed. + assert!(!colored(&classic::options(&json!({"lightColor": "#ff0000"})))); + } + + #[test] + fn each_members_run_of_faces_lies_over_an_underlay_of_its_own() { + // Rings one above the other: their faces alternate in the one order, so each ring's + // faces go over underlays run by run, and no run holds faces of both. + let ring = |id, y: f64, opacity: f32| { + let mut n = (*member(id, 40.0)).clone(); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.opacity = opacity; + } + if let NodeKind::Path { path, .. } = &mut n.kind { + *path = PathData::from_bezpath(&(Affine::translate((0.0, y)) * path.to_bezpath())); + } + Arc::new(n) + }; + let lit = json!({"segments": 16, "lightColor": "#ff0000"}); + for opacity in [1.0, 0.5] { + let members = vec![ring(1, 0.0, 1.0), ring(2, 200.0, opacity)]; + let art = revolve_art(&group_with(lit.clone(), members.clone())).unwrap(); + let runs = sealed_faces(&art); + assert!(runs.len() >= 2, "{opacity}: {} runs", runs.len()); + for run in &runs { + let ys: Vec = run.iter().filter_map(|f| f.visual_bounds()).map(|b| b.center().y).collect(); + assert!(ys.iter().all(|y| *y < 100.0) || ys.iter().all(|y| *y > 100.0), "{opacity}: a run holds one ring's faces: {ys:?}"); + } + // Each ring's opacity applies once, to its faces and their underlays; inside, only a + // face's own lit art blends. + let faded = |chain: &Chain| chain.iter().filter(|(o, _)| *o != 1.0).count(); + let chains: Vec = faces_in_order(&art).into_iter().map(|(_, c)| c).collect(); + assert!(chains.iter().all(|c| faded(c) <= 1 && c.iter().all(|(o, _)| *o == 1.0 || *o == opacity)), "{opacity}"); + assert_eq!(chains.iter().any(|c| faded(c) == 1), opacity < 1.0, "{opacity}"); + if opacity == 1.0 { + // Opaque rings share one order, and every face in it lies over an underlay. + let white = revolve_art(&group_with(json!({"segments": 16}), members)).unwrap(); + let count = white.children().unwrap()[0].children().unwrap().len(); + assert_eq!(runs.iter().map(Vec::len).sum::(), count); + } + } } #[test] @@ -1822,7 +2101,7 @@ mod tests { let mut fx = crate::new_effect(id, &json!({})).unwrap(); fx.params = params.clone(); let n = profile_node(); - let (path, _) = profile(&n).unwrap(); + let (path, rule) = profile(&n).unwrap(); let b = path.bounds().unwrap(); let mut half = n.clone(); if let AppearanceItem::Fill(f) = &mut half.appearance.items[0] { @@ -1830,9 +2109,9 @@ mod tests { } for n in [n, half] { let item = surface_item(&n.appearance.items).unwrap(); - let (_, kept) = object_surface(None, &n, &path, &fx, item, false, &mut Copies::default()).unwrap(); - let drawn = shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), kept).unwrap(); - let alone = shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), None).unwrap(); + let (_, kept) = object_surface(None, &n, &path, rule, &fx, item, false, &mut Copies::default()).unwrap(); + let drawn = shadow_of(n.id, &fx, &path, item, b, rule_options(&fx, rule), kept).unwrap(); + let alone = shadow_of(n.id, &fx, &path, item, b, rule_options(&fx, rule), None).unwrap(); assert!(alone.is_some() || id == CLASSIC_REVOLVE, "{id} {params}"); assert_eq!(format!("{drawn:?}"), format!("{alone:?}"), "{id} {params}"); } @@ -1898,11 +2177,11 @@ mod tests { if let AppearanceItem::Fill(f) = &mut n.appearance.items[0] { f.opacity = bad; } - let (path, _) = profile(&n).unwrap(); + let (path, rule) = profile(&n).unwrap(); let b = path.bounds().unwrap(); let item = surface_item(&n.appearance.items).unwrap(); assert!(!casts(&fx, bad), "{bad}: the surface keeps no faces for a shadow"); - let (_, kept) = object_surface(None, &n, &path, &fx, item, false, &mut Copies::default()).unwrap(); + let (_, kept) = object_surface(None, &n, &path, rule, &fx, item, false, &mut Copies::default()).unwrap(); assert_eq!(shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), kept).unwrap(), None, "{bad} drawn"); assert_eq!(shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), None).unwrap(), None, "{bad} alone"); let shadows = group_shadows(&group(bad)); diff --git a/crates/effects/src/revolve/classic.rs b/crates/effects/src/revolve/classic.rs index 8dc013e9dc..4aefb13eef 100644 --- a/crates/effects/src/revolve/classic.rs +++ b/crates/effects/src/revolve/classic.rs @@ -164,6 +164,41 @@ mod tests { } } + /// With Black Overprint every face keeps the blue, and the faces that darken get black over it, + /// overprinting, as strong as the darkening of the shading color Black. + #[test] + fn black_overprint_keeps_the_blue_under_overprinting_black() { + let darkened = revolved(json!({"surface": "diffuse"})); + let art = revolved(json!({"surface": "diffuse", "shadingColor": "blackOverprint"})); + let (darkened, drawn) = (faces(&darkened), faces(&art)); + assert_eq!(darkened.len(), drawn.len()); + let mut shaded = 0; + for (face, black) in drawn.iter().zip(&darkened) { + let fills: Vec<&vectorcraft_doc::FillLayer> = face + .appearance + .items + .iter() + .filter_map(|i| match i { + AppearanceItem::Fill(f) => Some(f), + AppearanceItem::Stroke(_) => None, + }) + .collect(); + assert_eq!((fills[0].paint.color(), fills[0].overprint), (Some(BLUE), false)); + let k = match fills.get(1) { + Some(shadow) => { + let Some(Color::Gray { k }) = shadow.paint.color() else { panic!("black shading: {:?}", shadow.paint) }; + assert_eq!((shadow.blend, shadow.overprint), (vectorcraft_doc::color::BlendMode::Multiply, true)); + shaded += 1; + k + } + None => 0.0, + }; + let b = fill(black).unwrap().to_rgb()[2]; + assert!((b - 0.8 * (1.0 - k)).abs() < 1e-3, "black at {k} matches the darkened blue {b}"); + } + assert!(shaded > 0, "faces turned from the light get black"); + } + #[test] fn angle_offset_edge_and_cap_shape_the_surface() { let full = revolved(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0})).visual_bounds().unwrap(); diff --git a/crates/effects/src/revolve/tests_graphics.rs b/crates/effects/src/revolve/tests_graphics.rs index 5d9500628b..e21a88a26e 100644 --- a/crates/effects/src/revolve/tests_graphics.rs +++ b/crates/effects/src/revolve/tests_graphics.rs @@ -279,6 +279,23 @@ fn under_several_lights_a_graphic_takes_each_faces_own_lit_art() { assert!(translucent > base && opaque - base == 2 * (translucent - base), "{base} {opaque} {translucent}"); } +#[test] +fn under_a_colored_light_each_part_of_a_graphic_stays_right_after_its_face_over_the_underlay() { + let d = document(); + let n = revolved(&CYLINDER, json!({"shade": true, "lightColor": "#ff8040", "graphics": [{"symbol": "Red"}]})); + let art = revolve_art_in(Some(&d), &n).unwrap(); + // One run holds every face; a face with a part of the bar is a group of the face and that part. + let runs = super::tests::sealed_faces(&art); + assert_eq!(runs.len(), 1); + let carrying: Vec<&Arc> = runs[0].iter().filter(|f| matches!(f.kind, NodeKind::Group { clip: false, .. })).collect(); + assert!(!carrying.is_empty()); + assert!(carrying.iter().all(|f| f.children().is_some_and(|c| c.len() > 1 && parts(&c[0], false).is_empty()))); + // Every part of the bar is drawn in the run, after its face, and none in the underlay. + let in_run: usize = carrying.iter().map(|f| parts(f, false).len()).sum(); + assert!(in_run > 0); + assert_eq!(in_run, parts(&art, false).len()); +} + #[test] fn graphics_past_the_point_limit_are_refused() { let mut d = document(); diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 5a2a179437..19b134f53b 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -102,6 +102,21 @@ pub fn has_solid(n: &Node) -> bool { solid(&n.appearance.effects).is_some() || n.appearance.items.iter().any(|i| i.visible() && solid(i.effects()).is_some()) } +/// Does `n` carry a 3D effect that [`three_d_meshes`] builds solids from: a visible Revolve, or +/// else a visible Extrude & Bevel, Inflate or Rotate effect, which on a group or layer must be on +/// the object itself (one on a group's fill or stroke draws nothing to export)? It does not build +/// the solids, so [`three_d_meshes`] can still refuse an object it passes. +pub fn exports_three_d(n: &Node) -> bool { + let container = is_container(n); + if crate::has_revolve(n) { + !container || n.appearance.effects.iter().any(|e| e.visible && crate::is_revolve(&e.id)) + } else if container { + solid(&n.appearance.effects).is_some() + } else { + has_solid(n) + } +} + /// The Position presets: (id, [rotation X, Y, Z]). Front, Back, Left, Right, Top and Bottom face /// the art that way; Off-Axis tilts each 20° down and 25° aside (showing the top and right); /// Isometric lays the art on the left, right, top or bottom plane of an isometric view (the @@ -625,7 +640,9 @@ pub fn validate_three_d_params(id: &str, p: &Value) -> Result<(), String> { /// blend mode (so overlapping facets don't add up their transparency). Under colored lights a solid /// color with smooth facets is one composite of all its facets ([`composites_facets`]) unless /// `faces`: then each facet is a face of its own, as in a gradient, so the faces can go in one order -/// with the faces of other solids. +/// with the faces of other solids. Under colored lights a gradient with transparent stops is drawn +/// opaque under one mask of its transparency, placed once on all the facets when it has no +/// placement of its own ([`crate::lighting::opaque_surface_paint`]). fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: BlendMode, colored: bool, faces: bool) -> Node { if !faces && composites_facets(&facets, paint, colored) { let mut group = crate::lighting::solid_surface(n.id, &facets, paint); @@ -634,7 +651,7 @@ fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: Ble return group; } // Preserve existing white-light paints and alpha composition exactly. - let (opaque, mask) = if colored { crate::lighting::opaque_paint(paint) } else { (paint.clone(), None) }; + let (opaque, mask) = if colored { crate::lighting::opaque_surface_paint(paint, || facets_bounds(&facets)) } else { (paint.clone(), None) }; let paint = &opaque; let children = facets .into_iter() @@ -671,6 +688,11 @@ fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: Ble group } +/// The bounds of every facet of `facets` together (`Rect::ZERO` when none has any). +pub(crate) fn facets_bounds(facets: &[Facet]) -> Rect { + facets.iter().filter_map(|f| f.path().bounds()).reduce(|a, c| a.union(c)).unwrap_or(Rect::ZERO) +} + /// The width of the stroke of a facet's own paint that closes the seams between `face` and its /// neighbors. No wider than the facet is thick: seen at a grazing angle a facet can be thinner than /// the stroke, and its stroke would then paint over its neighbors. @@ -2155,7 +2177,11 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option { Arc::make_mut(&mut art).appearance.effects = later.clone(); art }; - shadows.extend(shadow.into_iter().map(with_later)); + // A shadow keeps its own blur (the light's Softness) below the later effects. + shadows.extend(shadow.into_iter().map(|mut art| { + Arc::make_mut(&mut art).appearance.effects.extend(later.iter().cloned()); + art + })); children.extend(surfaces.into_iter().map(with_later)); } else { let flat = Appearance { items: vec![item.clone()], ..Default::default() }; diff --git a/crates/effects/src/solids/classic.rs b/crates/effects/src/solids/classic.rs index f48b94bce9..79d87fdb25 100644 --- a/crates/effects/src/solids/classic.rs +++ b/crates/effects/src/solids/classic.rs @@ -20,8 +20,8 @@ pub const ROTATE_SURFACES: [&str; 2] = ["none", "diffuse"]; /// The width of a Wireframe edge, in points. const WIRE: f64 = 0.5; -/// The Shading Color choices: black, a custom color, or none. -pub const SHADING_COLORS: [&str; 3] = ["black", "custom", "none"]; +/// The Shading Color choices: black, a custom color, none, or black overprinting the paint. +pub const SHADING_COLORS: [&str; 4] = ["black", "custom", "none", "blackOverprint"]; /// The surface settings of Extrude & Bevel (Classic)'s parameters. pub fn classic_shading(p: &Value) -> ClassicShading { @@ -55,8 +55,8 @@ pub fn classic_extrude_options(p: &Value) -> Extrude { } } -/// The color faces darken toward: black, the custom color, or none (faces keep their paint and only -/// the highlight lightens them). +/// The color faces darken toward: black (for Black Overprint too), the custom color, or none (faces +/// keep their paint and only the highlight lightens them). fn shading_color(p: &Value) -> Option { match text(p, "shadingColor", "black") { "none" => None, @@ -200,27 +200,54 @@ fn preserves_spot_colors(p: &Value) -> bool { /// A face of `paint`, a color linked to a swatch, with Preserve Spot Colors: the swatch at a lower /// tint for the highlight `spec`, its link kept so a spot color stays on its own plate, and, where -/// tone `tone` is below full light and the faces darken (`shade`), black over it at `1 - tone`, -/// multiplied and overprinting, so it prints on the black plate. `seam` is the width of the seam +/// tone `tone` is below full light and the faces darken (`shade`), black over it as +/// [`overprinting_black`] draws it, so it prints on the black plate. `seam` is the width of the seam /// stroke each layer draws around the face. fn linked_face(paint: &Paint, tone: f64, spec: f64, shade: Option, seam: f64) -> Vec { let Paint::Solid { color, swatch, tint } = paint else { return vec![] }; let keep = (1.0 - spec).clamp(0.0, 1.0) as f32; let fill = Paint::Solid { color: color.tinted(keep), swatch: swatch.clone(), tint: tint * keep }; let mut items = vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(fill, seam))]; - if shade.is_some() && tone < 1.0 { - let black = Paint::solid(Color::gray((1.0 - tone).clamp(0.0, 1.0) as f32)); - let mut layer = FillLayer::new(black.clone()); - layer.blend = BlendMode::Multiply; - layer.overprint = true; - let mut edge = crate::lighting::seam_stroke(black, seam); - edge.blend = BlendMode::Multiply; - edge.overprint = true; - items.extend([AppearanceItem::Fill(layer), AppearanceItem::Stroke(edge)]); + if shade.is_some() { + items.extend(overprinting_black(tone, seam)); } items } +/// The black that shades a face at tone `tone` on the black plate, when the tone is below full +/// light: a fill of black at `1 - tone`, multiplied and overprinting, and its seam stroke `seam` +/// wide, overprinting with Darken, so where the stroke lies over the face's own black, or over a +/// neighbor's, the face is not darkened twice. +fn overprinting_black(tone: f64, seam: f64) -> Vec { + if tone >= 1.0 { + return vec![]; + } + let black = Paint::solid(Color::gray((1.0 - tone).clamp(0.0, 1.0) as f32)); + let mut layer = FillLayer::new(black.clone()); + layer.blend = BlendMode::Multiply; + layer.overprint = true; + let mut edge = crate::lighting::seam_stroke(black, seam); + edge.blend = BlendMode::Darken; + edge.overprint = true; + vec![AppearanceItem::Fill(layer), AppearanceItem::Stroke(edge)] +} + +/// Whether the shading color of parameters `p` is Black Overprint. +fn black_overprint(p: &Value) -> bool { + text(p, "shadingColor", "black") == "blackOverprint" +} + +/// A face of `paint` with Black Overprint: the paint unchanged, and where tone `tone` is below full +/// light, black over it as [`overprinting_black`] draws it, so the paint's own inks print as they +/// are and the shading prints on the black plate. The highlight is not drawn. `seam` is the width of +/// the seam stroke each layer draws around the face. +fn overprinted_face(paint: &Paint, tone: f64, seam: f64) -> Vec { + let mut items = + vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam))]; + items.extend(overprinting_black(tone, seam)); + items +} + /// The width of the stroke [`surface`] draws around `face` with parameters `p`: a wire edge on /// Wireframe, else the seam between faces. pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 { @@ -229,16 +256,19 @@ pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 { /// One solid's faces in paint `paint`, as a group with the paint's opacity and blend mode, one child /// for each facet: the edges of the faces on Wireframe, else each face filled in its paint shaded by -/// its tone and highlight (with Preserve Spot Colors, a color linked to a swatch as [`linked_face`] -/// draws it). A gradient with transparent stops is shaded opaque and then masked by -/// its own transparency, so the shading follows the gradient's coverage. +/// its tone and highlight (with Black Overprint, as [`overprinted_face`] draws it; with Preserve Spot +/// Colors, a color linked to a swatch as [`linked_face`] draws it). A gradient with transparent stops +/// is shaded opaque and then masked by its own transparency, so the shading follows the gradient's +/// coverage; without a placement of its own, it is placed once on all the faces +/// ([`crate::lighting::opaque_surface_paint`]). pub(crate) fn surface(n: &Node, facets: Vec, source: &Paint, opacity: f32, blend: BlendMode, p: &Value) -> Node { let shading = classic_shading(p); let lights = lights(p); let shade = shading_color(p); let preserve = preserves_spot_colors(p); + let overprint = black_overprint(p); let wire = shading.surface == ClassicSurface::Wireframe; - let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_paint(source) }; + let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_surface_paint(source, || super::facets_bounds(&facets)) }; let paint = &paint; let children = facets .into_iter() @@ -251,6 +281,10 @@ pub(crate) fn surface(n: &Node, facets: Vec, source: &Paint, opacity: f32 let (tone, spec) = shading.tone(face.normal, &lights); // A narrow stroke of the face's own paint closes the hairline seams between faces. let seam = super::seam_width(&face); + if overprint { + let items = overprinted_face(paint, tone, seam); + return Arc::new(Node::path(n.id, face.path(), Appearance { items, ..Default::default() })); + } let items = match paint.color() { // Unshaded (No Shading, no shading color, or a face in full light) with no // highlight: the paint itself, its color space and swatch kept. diff --git a/crates/effects/src/solids/shadow.rs b/crates/effects/src/solids/shadow.rs index 81542a3722..7b84214d29 100644 --- a/crates/effects/src/solids/shadow.rs +++ b/crates/effects/src/solids/shadow.rs @@ -1,12 +1,12 @@ //! The shadow of the 3D and Materials effects (Extrude & Bevel, Inflate, Rotate and Revolve): the //! `shadow` switch with `shadowPosition`, `shadowDistance` and `shadowBounds`, and the shape it -//! draws behind the solids. +//! draws behind the solids, blurred by the first light's Softness. use std::ops::Range; use std::sync::Arc; -use serde_json::Value; +use serde_json::{Value, json}; use vectorcraft_doc::color::{BlendMode, Color, Paint}; -use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, Node, NodeId}; +use vectorcraft_doc::{Appearance, AppearanceItem, Effect, FillLayer, Node, NodeId}; use vectorcraft_three_d::{Shadow, ShadowCaster, ShadowPlane, ShadowPosition}; use super::Scope; @@ -15,15 +15,21 @@ use crate::util::{flag, num, text}; /// The shadow's paint: black at this opacity. VectorCraft's own values. const SHADOW_OPACITY: f32 = 0.5; +/// Blur radii below this, in points, leave the shadow hard-edged. +const MIN_BLUR: f64 = 0.01; + /// The shadow `p` asks for, or `None` with the switch off or when the first light lights nothing -/// (Shading is off or its intensity is 0), so that no shadow is built. +/// (Shading is off or its intensity is 0), so that no shadow is built. Its softness is the first +/// light's. pub(crate) fn options(p: &Value) -> Option { - let intensity = crate::lighting::lights(p).and_then(|l| l.iter().next().map(|l| l.intensity)).unwrap_or_else(|| num(p, "lightIntensity", 80.0)); + let first = crate::lighting::lights(p).and_then(|l| l.iter().next().copied()); + let intensity = first.map_or_else(|| num(p, "lightIntensity", 80.0), |l| l.intensity); let lit = flag(p, "shade", true) && intensity > 0.0; (lit && flag(p, "shadow", false)).then(|| Shadow { position: ShadowPosition::parse(text(p, "shadowPosition", "behind")).unwrap_or_default(), distance: num(p, "shadowDistance", 0.0) / 100.0, bounds: num(p, "shadowBounds", 100.0) / 100.0, + softness: first.map_or_else(|| num(p, "lightSoftness", 0.0) / 100.0, |l| l.softness), }) } @@ -64,8 +70,9 @@ pub(crate) fn casts(opacity: f32) -> bool { } /// The shadow of the faces in `caster` as a path of object `id`, cast by art in `ink`: filled -/// black at [`SHADOW_OPACITY`] times its opacity, in its blending mode, with the nonzero rule; -/// `None` when it casts nothing. +/// black at [`SHADOW_OPACITY`] times its opacity, in its blending mode, with the nonzero rule, and +/// with the light's Softness a Gaussian Blur of the plane's radius ([`ShadowPlane::blur`]), which +/// is drawn, measured, exported and expanded as that effect is; `None` when it casts nothing. pub(crate) fn art(id: NodeId, caster: &ShadowCaster, shadow: Shadow, ink: Ink) -> Option { let all = 0..caster.len(); let all = std::slice::from_ref(&all); @@ -78,7 +85,9 @@ fn piece(id: NodeId, caster: &ShadowCaster, plane: &ShadowPlane, faces: &[Range< let mut fill = FillLayer::new(Paint::solid(Color::BLACK)); fill.opacity = SHADOW_OPACITY * ink.opacity.clamp(0.0, 1.0); fill.blend = ink.blend; - Some(Node::path(id, path, Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() })) + let blur = plane.blur(); + let effects = if blur >= MIN_BLUR { vec![Effect { id: "blur.gaussian".into(), params: json!({"radius": blur}), visible: true }] } else { vec![] }; + Some(Node::path(id, path, Appearance { items: vec![AppearanceItem::Fill(fill)], effects, ..Default::default() })) } /// Whether `a` and `b` are the same objects' scopes (each member holds its own copies). diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index 9b57c989c6..378299d514 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -1766,11 +1766,24 @@ fn a_colored_solid_face_on_its_own_keeps_the_composites_colors() { assert_eq!(ramps, one.iter().skip(1).collect::>(), "the same light ramps"); // The single face's clip holds its seam: the clip reaches past the facet by half the seam. let seam = (face.thickness() / 2.0).clamp(0.05, 0.75); - let widths: Vec = paints(&batch).into_iter().filter_map(|(_, w)| w).filter(|w| *w > 0.0 && *w != crate::lighting::UNDERLAY_SEAM).collect(); - assert!(widths.len() == 3 && widths.iter().all(|w| (w - seam).abs() < 1e-12), "{widths:?}"); let NodeKind::Group { children, .. } = &single.kind else { panic!("a clip group") }; let (clip, facet) = (children[0].path_data().and_then(PathData::bounds).unwrap(), face.path().bounds().unwrap()); - assert!((clip.x0 - (facet.x0 - seam / 2.0)).abs() < 0.1 && (clip.x1 - (facet.x1 + seam / 2.0)).abs() < 0.1, "{clip:?} {facet:?}"); + let reaches = |b: Rect| (b.x0 - (facet.x0 - seam / 2.0)).abs() < 0.1 && (b.x1 - (facet.x1 + seam / 2.0)).abs() < 0.1; + assert!(reaches(clip), "{clip:?} {facet:?}"); + // In the composite, the facet over the underlay is one fill of the facet and its seam in each + // channel: no seam stroke of its own, and a path that reaches past the facet by half the seam. + let widths: Vec = paints(&batch).into_iter().filter_map(|(_, w)| w).filter(|w| *w > 0.0 && *w != crate::lighting::UNDERLAY_SEAM).collect(); + assert!(widths.is_empty(), "{widths:?}"); + let mut seamed = vec![]; + batch.walk(&mut |n| { + if let [AppearanceItem::Fill(f)] = n.appearance.items.as_slice() + && f.paint != Paint::solid(Color::BLACK) + && f.paint != paint + { + seamed.extend(n.path_data().and_then(PathData::bounds)); + } + }); + assert!(seamed.len() == 3 && seamed.iter().all(|b| reaches(*b)), "{seamed:?} {facet:?}"); } /// `square_node` moved right by `dx`, with id `id` and fill `fill`. @@ -1908,6 +1921,89 @@ fn classic_shading_color_blend_steps_and_lights() { assert_eq!(with(json!({"drawHiddenFaces": true})).len(), 6); } +/// The fills, then the strokes, of face `face`. +fn layers_of(face: &Node) -> (Vec<&vectorcraft_doc::FillLayer>, Vec<&StrokeLayer>) { + let fills = face.appearance.items.iter().filter_map(|i| if let AppearanceItem::Fill(f) = i { Some(f) } else { None }).collect(); + let strokes = face.appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s) } else { None }).collect(); + (fills, strokes) +} + +/// The black over face `face` with Black Overprint, checked to be opaque and overprinting in +/// both its fill (multiplied) and its seam stroke (Darken, so it does not darken the face twice); +/// `None` when the face has none. +fn overprinted_black(face: &Node) -> Option { + let (fills, strokes) = layers_of(face); + assert_eq!(fills.len(), strokes.len(), "each fill has its seam stroke"); + let shadow = fills.get(1)?; + let Some(Color::Gray { k }) = shadow.paint.color() else { panic!("black shading: {:?}", shadow.paint) }; + assert_eq!((shadow.blend, shadow.overprint, shadow.opacity), (BlendMode::Multiply, true, 1.0)); + assert_eq!((strokes[1].paint.clone(), strokes[1].blend, strokes[1].overprint), (shadow.paint.clone(), BlendMode::Darken, true)); + assert!(!fills[0].overprint && !strokes[0].overprint, "the paint itself knocks out"); + Some(k) +} + +/// Black Overprint keeps the paint on every face and draws the shading over it as black, +/// overprinting, as strong as the darkening of the shading color Black; the +/// highlight is not drawn, and No Shading adds no black. +#[test] +fn classic_black_overprint_keeps_the_paint_under_overprinting_black() { + let diffuse = json!({"surface": "diffuse", "ambient": 20}); + let mut over = diffuse.clone(); + over["shadingColor"] = json!("blackOverprint"); + let darkened: Vec<[f32; 3]> = classic_faces(diffuse).iter().map(fill_rgb).collect(); + let faces = classic_faces(over); + assert_eq!(faces.len(), darkened.len()); + let mut shaded = 0; + for (face, rgb) in faces.iter().zip(&darkened) { + assert_eq!(layers_of(face).0[0].paint, Paint::solid(RED), "the paint is kept"); + let k = overprinted_black(face).unwrap_or(0.0); + assert!((rgb[0] - 0.8 * (1.0 - k)).abs() < 1e-3, "black at {k} matches the darkened {rgb:?}"); + shaded += usize::from(k > 0.0); + } + assert!(shaded > 0, "faces turned from the light get black"); + // Plastic: no white layer for the highlight. + let shiny = json!({"shadingColor": "blackOverprint", "highlightIntensity": 100, "highlightSize": 100, "lightHeight": 60}); + for face in classic_faces(shiny) { + let (fills, _) = layers_of(&face); + assert_eq!(fills[0].paint, Paint::solid(RED)); + assert!(fills.len() <= 2 && overprinted_black(&face).is_none_or(|k| k > 0.0), "{fills:?}"); + } + // No Shading: the paint alone. + for face in classic_faces(json!({"surface": "none", "shadingColor": "blackOverprint"})) { + assert_eq!(overprinted_black(&face), None); + assert_eq!(layers_of(&face).0[0].paint, Paint::solid(RED)); + } +} + +/// Black Overprint keeps a gradient fill on every face, with the black over it, and Rotate +/// (Classic) draws its plane the same way. +#[test] +fn classic_black_overprint_keeps_gradients_and_shades_rotate() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint}; + let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new( + GradientKind::Linear, + vec![vectorcraft_doc::color::GradientStop::new(0.0, RED), vectorcraft_doc::color::GradientStop::new(1.0, BLUE)], + )))); + let mut n = classic(json!({"shadingColor": "blackOverprint", "surface": "diffuse"})); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.paint = gradient.clone(); + } + let art = solid_art(&n).unwrap(); + let mut shaded = 0; + for face in faces(&art) { + assert_eq!(layers_of(face).0[0].paint, gradient); + shaded += usize::from(overprinted_black(face).is_some()); + } + assert!(shaded > 0); + // Rotate (Classic), turned from the light: red with black over it; facing it: red alone. + let turned = classic_rotate(json!({"rotationX": 0, "rotationY": 70, "rotationZ": 0, "lightHeight": 90, "shadingColor": "blackOverprint"})); + let face = &turned[0].children().unwrap()[0]; + assert_eq!(layers_of(face).0[0].paint, Paint::solid(RED)); + assert!(overprinted_black(face).is_some_and(|k| k > 0.05)); + let lit = classic_rotate(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": 90, "shadingColor": "blackOverprint"})); + assert_eq!(overprinted_black(&lit[0].children().unwrap()[0]), None); +} + #[test] fn classic_bevel_height_extent_and_cap_shape_the_solid() { let bounds = |p: Value| solid_art(&classic(p)).unwrap().visual_bounds().unwrap(); @@ -1960,6 +2056,57 @@ fn classic_shading_keeps_a_gradients_transparency() { } } +/// A gradient without a placement and with a transparent stop, under colored lights or classic +/// shading, is placed once for the whole surface: every face's color and the surface's opacity mask +/// share one placement, so the color and transparency ramps line up across the faces. A gradient +/// placed in the document keeps its placement. +#[test] +fn a_transparent_unplaced_gradient_has_one_placement_for_color_and_mask() { + use vectorcraft_doc::color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; + // The source's stops carry an unusual midpoint, so its color and mask copies can be told from + // the light ramps. + const MARK: f32 = 0.37; + let mut first = GradientStop::new(0.0, RED); + first.midpoint = MARK; + let mut end = GradientStop::new(1.0, Color::BLACK); + end.opacity = 0.25; + let unplaced = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![first, end])); + let placed = GradientGeom { start: Point::new(90.0, 100.0), end: Point::new(230.0, 140.0), aspect: 1.0, focal: None }; + // The placement of each copy of the source gradient: its own, else its fit on the path it fills. + fn placements(n: &Node, out: &mut Vec) { + n.walk(&mut |c| { + if let Some(mask) = &c.extras().mask { + placements(&mask.art, out); + } + let bounds = c.path_data().and_then(|p| p.bounds()).unwrap_or(Rect::ZERO); + for item in &c.appearance.items { + if let Paint::Gradient(g) = paint_ref(item) + && g.gradient.stops.first().is_some_and(|s| s.midpoint == MARK) + { + out.push(g.resolve(bounds)); + } + } + }); + } + let lit = json!({"lights": [{"color": "#ff8080"}]}); + for (id, params) in [(EXTRUDE, lit.clone()), (INFLATE, lit.clone()), (ROTATE, lit), (CLASSIC_EXTRUDE, json!({}))] { + for geom in [None, Some(placed)] { + let mut n = square_node(); + n.appearance.items = vec![AppearanceItem::Fill(FillLayer::new(Paint::Gradient(Box::new(GradientPaint { geom, ..unplaced.clone() }))))]; + n.appearance.effects.push(fx(id, params.clone())); + let art = solid_art(&n).unwrap_or_else(|| panic!("{id}")); + let mut masks = 0; + art.walk(&mut |c| masks += usize::from(c.extras().mask.is_some())); + assert!(masks > 0, "{id}: the surface carries the gradient's transparency as a mask"); + let mut found = vec![]; + placements(&art, &mut found); + assert!(found.len() > 2, "{id}: the faces' colors and the mask"); + let expected = geom.unwrap_or(found[0]); + assert!(found.iter().all(|g| *g == expected), "{id} {geom:?}: {found:?}"); + } + } +} + /// A group member in a gradient with transparent stops keeps the shared back-to-front order of /// every member's faces: its faces go in runs that carry its opacity mask, and the other member's /// faces are drawn between them where they are in front of some and behind others. Here a square @@ -2083,9 +2230,12 @@ fn classic_parameters_are_checked() { let check = |p: Value| validate_solid(&n, CLASSIC_EXTRUDE, &crate::merged_params(CLASSIC_EXTRUDE, &p)); assert!(check(json!({})).is_ok()); assert!(check(json!({"surface": "wireframe", "shadingColor": "custom", "shadingCustom": "#12aBcd", "blendSteps": 256, "bevel": "ogee"})).is_ok()); + assert!(check(json!({"shadingColor": "blackOverprint"})).is_ok()); for (p, says) in [ (json!({"surface": "glossy"}), "`surface` must be one of wireframe, none, diffuse, plastic"), - (json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none"), + (json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none, blackOverprint"), + (json!({"shadingColor": "blackoverprint"}), "`shadingColor` must be one of"), + (json!({"shadingColor": true}), "`shadingColor` must be one of"), (json!({"shadingCustom": "blue"}), "`shadingCustom` must be a #rrggbb color"), (json!({"shadingCustom": "#fff"}), "`shadingCustom` must be a #rrggbb color"), (json!({"depth": 2001}), "`depth` must be between 0 and 2000 (got 2001)"), @@ -2162,11 +2312,12 @@ fn classic_rotate_parameters_are_checked() { let check = |p: Value| validate_solid(&n, CLASSIC_ROTATE, &crate::merged_params(CLASSIC_ROTATE, &p)); assert!(check(json!({})).is_ok()); assert!(check(json!({"surface": "none", "shadingColor": "custom", "shadingCustom": "#12aBcd", "blendSteps": 1})).is_ok()); + assert!(check(json!({"shadingColor": "blackOverprint"})).is_ok()); for (p, says) in [ (json!({"surface": "plastic"}), "`surface` must be one of none, diffuse"), (json!({"surface": "wireframe"}), "`surface` must be one of none, diffuse"), (json!({"surface": 2}), "`surface` must be one of"), - (json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none"), + (json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none, blackOverprint"), (json!({"shadingCustom": "#fff"}), "`shadingCustom` must be a #rrggbb color"), (json!({"rotationX": 181}), "`rotationX` must be between -180 and 180 (got 181)"), (json!({"perspectiveAngle": 161}), "`perspectiveAngle` must be between 0 and 160 (got 161)"), diff --git a/crates/effects/src/solids/tests_shadow.rs b/crates/effects/src/solids/tests_shadow.rs index d24cd6e86f..2d82d571c8 100644 --- a/crates/effects/src/solids/tests_shadow.rs +++ b/crates/effects/src/solids/tests_shadow.rs @@ -87,6 +87,40 @@ fn the_shadow_moves_with_its_settings() { } } +/// The radius of the Gaussian Blur on shadow `n`; `None` without one. +fn shadow_blur(n: &Node) -> Option { + match n.appearance.effects.as_slice() { + [] => None, + [e] if e.id == "blur.gaussian" && e.visible => e.params["radius"].as_f64(), + other => panic!("unexpected effects on the shadow: {other:?}"), + } +} + +/// The first light's Softness blurs the shadow, more with Softness and with Distance from Object; +/// at 0 % it stays the hard-edged path. A list of lights takes the first light's Softness. +#[test] +fn the_first_lights_softness_blurs_the_shadow() { + for id in CASTING { + let blur = |params: Value| { + let mut n = square_node(1, 0.0); + n.appearance.effects.push(crate::new_effect(id, ¶ms).unwrap()); + let lit = art(&n, id).unwrap(); + let shadow = &lit.children().unwrap()[0]; + assert!(is_shadow(shadow), "{id} {params}"); + shadow_blur(shadow) + }; + assert_eq!(blur(json!({"shadow": true})), None, "{id}: hard at 0 %"); + let soft = blur(json!({"shadow": true, "lightSoftness": 50})).unwrap_or_else(|| panic!("{id}")); + let softer = blur(json!({"shadow": true, "lightSoftness": 100})).unwrap(); + let far = blur(json!({"shadow": true, "lightSoftness": 100, "shadowDistance": 100})).unwrap(); + assert!(soft > 0.0 && softer > soft && far > softer, "{id}: {soft} {softer} {far}"); + let first = json!({"shadow": true, "lightSoftness": 0, "lights": [{"softness": 100}, {"softness": 0}]}); + assert_eq!(blur(first), Some(softer), "{id}: the first light's"); + let second = json!({"shadow": true, "lightSoftness": 100, "lights": [{"softness": 0}, {"softness": 100}]}); + assert_eq!(blur(second), None, "{id}: only the first light casts"); + } +} + #[test] fn shadow_settings_out_of_range_or_of_the_wrong_kind_are_refused() { for id in CASTING { @@ -203,6 +237,26 @@ fn the_shadows_of_every_fill_go_behind_every_fill_s_solid() { } } +/// A fill's own 3D effect blurs its shadow by the light's Softness too, and the effects after it +/// in the fill's list follow the blur. +#[test] +fn a_fills_own_3d_effect_keeps_the_blur_below_its_later_effects() { + for id in CASTING { + for later in [None, Some(crate::new_effect("distort.roughen", &json!({})).unwrap())] { + let mut n = square_node(1, 0.0); + let fill = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))).unwrap(); + fill.effects_mut().push(crate::new_effect(id, &json!({"shadow": true, "lightSoftness": 100})).unwrap()); + fill.effects_mut().extend(later.clone()); + let lit = art(&n, id).unwrap_or_else(|| panic!("{id}")); + let shadow = &lit.children().unwrap()[0]; + assert!(is_shadow(shadow), "{id}"); + let ids: Vec<&str> = shadow.appearance.effects.iter().map(|e| e.id.as_str()).collect(); + let want: Vec<&str> = std::iter::once("blur.gaussian").chain(later.as_ref().map(|e| e.id.as_str())).collect(); + assert_eq!(ids, want, "{id}"); + } + } +} + #[test] fn expand_appearance_keeps_the_shadow_as_a_path() { for id in CASTING { 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.rs b/crates/effects/src/tests.rs index c605b6461f..ac340224c6 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -11,6 +11,7 @@ mod rasterfollow; mod scale; mod solidcontext; mod transformfx; +mod typestroke; fn fx(id: &str, params: Value) -> Effect { Effect { id: id.into(), params, visible: true } 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/effects/src/tests/rasterfollow.rs b/crates/effects/src/tests/rasterfollow.rs index 9fbb37a39d..e463fb5332 100644 --- a/crates/effects/src/tests/rasterfollow.rs +++ b/crates/effects/src/tests/rasterfollow.rs @@ -7,7 +7,8 @@ use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId}; use vectorcraft_geom::{Affine, Anchor, PathData, Point, Rect, SubPath, shapes}; use crate::geometry::{Budget, MAX_EFFECT_LINES, apply_geometry_carrying_within}; -use crate::{Carry, GeomContext, RasterFx, apply_geometry_carrying, bake_document, expand_outlined, raster_effects}; +use crate::pixel::{Light, StrokeDirection}; +use crate::{Carry, GeomContext, PixelFx, RasterFx, apply_geometry_carrying, bake_document, expand_outlined, raster_effects}; fn fx(id: &str, params: Value) -> Effect { Effect { id: id.into(), params, visible: true } @@ -436,6 +437,230 @@ fn pixel_filter_sizes_scale_with_the_transform_after_them() { assert!(matches!(drawn.get(1), Some(RasterFx::Pixel(crate::PixelFx::PaintDaubs { size, .. })) if (size - 20.0).abs() < 1e-9), "{drawn:?}"); } +/// The light direction of the first pixel filter `effects` draw, if it has one. +fn drawn_light(effects: &[Effect]) -> Option { + raster_effects(effects).into_iter().find_map(|r| match r { + RasterFx::Pixel( + PixelFx::Underpainting { light, .. } + | PixelFx::RoughPastels { light, .. } + | PixelFx::ConteCrayon { light, .. } + | PixelFx::BasRelief { light, .. } + | PixelFx::Plaster { light, .. } + | PixelFx::Texturizer { light, .. }, + ) => Some(light), + _ => None, + }) +} + +/// The stroke direction of the first pixel filter `effects` draw, if it has one. +fn drawn_strokes(effects: &[Effect]) -> Option { + raster_effects(effects).into_iter().find_map(|r| match r { + RasterFx::Pixel(PixelFx::SprayedStrokes { direction, .. } | PixelFx::GraphicPen { direction, .. }) => Some(direction), + _ => None, + }) +} + +/// The screen angles of the first Color Halftone `effects` draw. +fn drawn_screens(effects: &[Effect]) -> [f64; 4] { + match raster_effects(effects).into_iter().next() { + Some(RasterFx::Pixel(PixelFx::ColorHalftone { angles, .. })) => angles, + other => panic!("expected a Color Halftone, got {other:?}"), + } +} + +/// A Bas Relief lit from `light`, then a Transform effect with `params`: the light it draws with. +fn relief_then(light: &str, params: Value) -> Option { + drawn_light(&[fx("sketch.basRelief", json!({ "lightDirection": light })), transform(params)]) +} + +/// A light direction before a Transform effect turns and reflects with the art (y down on the +/// page), to the nearest of the eight directions, the clockwise one at a tie. +#[test] +fn bas_relief_light_follows_rotation_and_reflection() { + assert_eq!(relief_then("top", json!({"rotate": 90})), Some(Light::Left)); + assert_eq!(relief_then("top", json!({"reflectY": true})), Some(Light::Bottom)); + assert_eq!(relief_then("top", json!({"reflectX": true})), Some(Light::Top)); + assert_eq!(relief_then("left", json!({"reflectX": true})), Some(Light::Right)); + // 22.5° clockwise lies halfway between Top and Top Right; 22.5° counterclockwise halfway + // between Top and Top Left. + assert_eq!(relief_then("top", json!({"rotate": -22.5})), Some(Light::TopRight)); + assert_eq!(relief_then("top", json!({"rotate": 22.5})), Some(Light::Top)); + assert_eq!(relief_then("top", json!({"rotate": 30})), Some(Light::TopLeft)); + // A turn of 90° counterclockwise, from each direction. + for (from, to) in [ + ("bottom", Light::Right), + ("bottomLeft", Light::BottomRight), + ("left", Light::Bottom), + ("topLeft", Light::BottomLeft), + ("top", Light::Left), + ("topRight", Light::TopLeft), + ("right", Light::Top), + ("bottomRight", Light::TopRight), + ] { + assert_eq!(relief_then(from, json!({"rotate": 90})), Some(to), "{from}"); + } + // Every filter with a light direction, and Bas Relief's default light (Bottom). + for id in ["artistic.underpainting", "artistic.roughPastels", "sketch.conteCrayon", "sketch.basRelief", "sketch.plaster", "texture.texturizer"] { + let effects = [fx(id, json!({"lightDirection": "top"})), transform(json!({"rotate": 90}))]; + assert_eq!(drawn_light(&effects), Some(Light::Left), "{id}"); + } + assert_eq!(drawn_light(&[fx("sketch.basRelief", json!({})), transform(json!({"rotate": 90}))]), Some(Light::Right)); + // The Transform effects after the filter turn it together, with one rounding at the end. + let twice = [fx("sketch.basRelief", json!({"lightDirection": "top"})), transform(json!({"rotate": -22.5})), transform(json!({"rotate": -22.5}))]; + assert_eq!(drawn_light(&twice), Some(Light::TopRight)); +} + +/// A stroke direction before a Transform effect turns and reflects with the art, to the nearest +/// of the four, a stroke and its reverse being the same, the clockwise one at a tie. +#[test] +fn stroke_axis_follows_transform() { + let strokes = |id: &str, way: Option<&str>, params: Value| { + let p = way.map_or(json!({}), |w| json!({ "strokeDirection": w })); + drawn_strokes(&[fx(id, p), transform(params)]) + }; + let sprayed = "brushStrokes.sprayedStrokes"; + let pen = "sketch.graphicPen"; + assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": 90})), Some(StrokeDirection::Vertical)); + assert_eq!(strokes(sprayed, Some("vertical"), json!({"rotate": 90})), Some(StrokeDirection::Horizontal)); + assert_eq!(strokes(pen, Some("rightDiagonal"), json!({"rotate": 90})), Some(StrokeDirection::LeftDiagonal)); + assert_eq!(strokes(pen, Some("rightDiagonal"), json!({"reflectX": true})), Some(StrokeDirection::LeftDiagonal)); + assert_eq!(strokes(pen, Some("leftDiagonal"), json!({"reflectY": true})), Some(StrokeDirection::RightDiagonal)); + assert_eq!(strokes(pen, None, json!({"rotate": 90})), Some(StrokeDirection::LeftDiagonal)); + assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": -22.5})), Some(StrokeDirection::LeftDiagonal)); + assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": 22.5})), Some(StrokeDirection::Horizontal)); + assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": -44})), Some(StrokeDirection::LeftDiagonal)); + assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": 180})), Some(StrokeDirection::Horizontal)); +} + +fn near4(a: [f64; 4], b: [f64; 4]) -> bool { + a.iter().zip(b).all(|(p, q)| (p - q).abs() < 1e-6) +} + +/// Color Halftone's screen angles before a Transform effect turn and reflect with the art. +#[test] +fn halftone_channels_follow_rotation_and_reflection() { + let screens = |p: Value, transforms: &[Value]| { + let mut effects = vec![fx("pixelate.colorHalftone", p)]; + effects.extend(transforms.iter().cloned().map(transform)); + drawn_screens(&effects) + }; + let defaults = screens(json!({}), &[json!({"rotate": 90})]); + assert!(near4(defaults, [198.0, 252.0, 180.0, 135.0]), "{defaults:?}"); + let reflected = screens(json!({"channel1": 45, "channel2": 30, "channel3": 0, "channel4": 270}), &[json!({"reflectX": true})]); + assert!(near4(reflected, [135.0, 150.0, 180.0, 270.0]), "{reflected:?}"); + let flipped = screens(json!({"channel1": 45, "channel2": 30, "channel3": 0, "channel4": 270}), &[json!({"reflectY": true})]); + assert!(near4(flipped, [315.0, 330.0, 0.0, 90.0]), "{flipped:?}"); + // One Transform effect reflects, then turns; two apply in the order they are listed. + let p = json!({"channel1": 10.5, "channel2": -30, "channel3": 0, "channel4": 359.25}); + let one = screens(p.clone(), &[json!({"rotate": 30, "reflectX": true})]); + assert!(near4(one, [199.5, 240.0, 210.0, 210.75]), "{one:?}"); + let two = screens(p, &[json!({"rotate": 30}), json!({"reflectX": true})]); + assert!(near4(two, [139.5, 180.0, 150.0, 150.75]), "{two:?}"); +} + +/// Only the visible Transform effects listed after a filter that move the art once turn its +/// direction; a hidden filter turns too, and a zero scale leaves it as it is. +#[test] +fn only_earlier_visible_single_map_effects_follow() { + let relief = fx("sketch.basRelief", json!({"lightDirection": "top"})); + assert_eq!(drawn_light(&[transform(json!({"rotate": 90})), relief.clone()]), Some(Light::Top)); + for params in [ + json!({"rotate": 90, "objects": false}), + json!({"rotate": 90, "copies": 1}), + json!({"rotate": 90, "random": true}), + json!({"scaleH": 0, "scaleV": 0}), + ] { + assert_eq!(drawn_light(&[relief.clone(), transform(params.clone())]), Some(Light::Top), "{params}"); + } + let mut hidden = transform(json!({"rotate": 90})); + hidden.visible = false; + assert_eq!(drawn_light(&[relief.clone(), hidden]), Some(Light::Top)); + let zero = [fx("pixelate.colorHalftone", json!({"channel1": 20})), transform(json!({"scaleH": 0, "scaleV": 0}))]; + assert!(near4(drawn_screens(&zero), [20.0, 162.0, 90.0, 45.0]), "{:?}", drawn_screens(&zero)); + // A hidden filter kept when the Transform effect is applied draws turned once it is shown. + let mut off = relief; + off.visible = false; + let kept = crate::raster::without_geometry(&[off, transform(json!({"rotate": 90}))]); + assert_eq!(kept.len(), 1); + let mut shown = kept[0].clone(); + shown.visible = true; + assert_eq!(drawn_light(&[shown]), Some(Light::Left)); +} + +/// The light direction of every Bas Relief drawn on `n` and the nodes under it, from the object's +/// effects and from each fill's and stroke's. +fn lights_in(n: &Node) -> Vec { + let mut out = vec![]; + n.walk(&mut |m| { + let lists = std::iter::once(&m.appearance.effects).chain(m.appearance.items.iter().map(|i| i.effects())); + for list in lists { + out.extend(drawn_light(list)); + } + }); + out +} + +/// The canvas, a fill's own effects, a group's members and export turn the light the same way. +#[test] +fn nested_and_baked_directions_match_canvas() { + let relief = || fx("sketch.basRelief", json!({"lightDirection": "top"})); + let turn = || transform(json!({"rotate": 90})); + // A fill's own Transform effect, and the object's Transform effect over its fill. + let fill = fill_square(31, vec![relief(), turn()]); + let item = fill.appearance.items.first().unwrap(); + assert_eq!(drawn_light(item.effects()), Some(Light::Left)); + let mut over = fill_square(32, vec![relief()]); + over.appearance.effects = vec![turn()]; + let item = over.appearance.items.first().unwrap(); + assert_eq!(drawn_light(&crate::item_effects_in(&over.appearance.effects, item.effects())), Some(Light::Left)); + // A fill's own turn of 30° and the object's turn of 30° make 60°, rounded once: Top Left, not + // Left (Top Left after the first turn, then Left after the second). + let thirty = || transform(json!({"rotate": 30})); + let mut both = fill_square(37, vec![relief(), thirty()]); + both.appearance.effects = vec![thirty()]; + let item = both.appearance.items.first().unwrap(); + assert_eq!(drawn_light(&crate::item_effects_in(&both.appearance.effects, item.effects())), Some(Light::TopLeft)); + // A group's Transform effect over a member's own filter and its fill's. + let g = group(33, vec![square(34, vec![relief()]), fill_square(35, vec![relief()])], vec![turn()]); + let art = crate::evaluate_container(None, &g).unwrap(); + assert_eq!(lights_in(&art), vec![Light::Left; 2]); + // Baked for export: the Transform effect is applied and the filter keeps the turned light. + let mut d = Document::new(800.0, 800.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, square(36, vec![relief(), turn()])).unwrap(); + d.insert(Some(layer), 1, g).unwrap(); + let baked = bake_document(&d).unwrap(); + let b = baked.node(NodeId(36)).unwrap(); + assert!(!b.appearance.effects.iter().any(|e| e.id == "distort.transform"), "{:?}", b.appearance.effects); + assert_eq!(drawn_light(&b.appearance.effects), Some(Light::Left)); + for id in [34, 35] { + assert_eq!(lights_in(baked.node(NodeId(id)).unwrap()), vec![Light::Left], "{id}"); + } +} + +/// A member's light under two nested groups that each turn 30° turns 60° in all, rounded once: +/// Top Left, not Left (Top Left after the inner group's turn, then Left after the outer one's). +#[test] +fn nested_group_turns_round_the_light_once() { + let relief = || fx("sketch.basRelief", json!({"lightDirection": "top"})); + let thirty = || transform(json!({"rotate": 30})); + let inner = group(41, vec![square(42, vec![relief()]), fill_square(43, vec![relief()])], vec![thirty()]); + let outer = group(40, vec![inner], vec![thirty()]); + let art = crate::evaluate_container(None, &outer).unwrap(); + assert_eq!(lights_in(&art), vec![Light::TopLeft; 2]); + let mut d = Document::new(800.0, 800.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, outer).unwrap(); + let baked = bake_document(&d).unwrap(); + for id in [42, 43] { + assert_eq!(lights_in(baked.node(NodeId(id)).unwrap()), vec![Light::TopLeft], "{id}"); + } + // Three groups make 90°: Left, not Bottom Left. + let three = group(44, vec![group(45, vec![group(46, vec![square(47, vec![relief()])], vec![thirty()])], vec![thirty()])], vec![thirty()]); + let art = crate::evaluate_container(None, &three).unwrap(); + assert_eq!(lights_in(&art), vec![Light::Left]); +} + /// A Transform effect after a 3D effect that makes copies or moves at random holds back the shadow /// before the 3D effect, as it does without the 3D effect. #[test] @@ -591,8 +816,8 @@ fn a_groups_transform_applies_after_its_members_own() { } /// An object's Transform effect transforms the raster effects of its fills and strokes with the -/// art, whatever its options: drawn, drawn through the art an option makes, and baked. One that -/// makes copies leaves them. +/// art, whatever its options: drawn, drawn through the art an option makes, and baked. For one that +/// makes copies, see [`each_copy_of_an_objects_transform_carries_its_fills_or_strokes_shadow`]. #[test] fn an_objects_transform_moves_its_fills_shadows() { let cases = [ @@ -600,7 +825,6 @@ fn an_objects_transform_moves_its_fills_shadows() { (json!({"scaleH": 200, "scaleV": 100, "strokes": true}), (20.0, 10.0)), (json!({"rotate": 90, "patterns": true}), (10.0, -10.0)), (json!({"rotate": 90, "strokes": true}), (10.0, -10.0)), - (json!({"scaleH": 200, "scaleV": 200, "copies": 1}), (10.0, 10.0)), ]; for (params, want) in cases { let mut n = fill_square(40, vec![shadow(10.0, 10.0, 0.0)]); @@ -991,3 +1215,300 @@ fn copies_past_the_budget_each_keep_their_shadow() { assert!(paths > 1 && paths < 1001, "{paths}"); assert_eq!(shadows_in(&art).len(), paths); } + +/// `n` with only its fill (or only a 4 pt blue stroke, with `stroke`), whose own effects are +/// `effects`. +fn one_row(mut n: Node, stroke: bool, effects: Vec) -> Node { + let mut item = if stroke { + vectorcraft_doc::AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0)) + } else { + n.appearance.items.remove(0) + }; + *item.effects_mut() = effects; + n.appearance.items = vec![item]; + n +} + +/// A case of [`copying_cases`]: the params, each copy's offset and each copy's blur. +type CopyingCase = (Value, Vec<(f64, f64)>, Vec); + +/// The cases of a Transform effect that makes copies with a drop shadow (10, 0) and a blur of 4 +/// before it: the params, each copy's offset and each copy's blur, the last copy first. +fn copying_cases() -> Vec { + vec![ + (json!({"moveH": 100, "copies": 2}), vec![(10.0, 0.0), (10.0, 0.0), (10.0, 0.0)], vec![4.0, 4.0, 4.0]), + // A turn of 90° counterclockwise on screen takes an offset to the right to one upward. + (json!({"rotate": 90, "copies": 2}), vec![(-10.0, 0.0), (0.0, -10.0), (10.0, 0.0)], vec![4.0, 4.0, 4.0]), + (json!({"reflectX": true, "moveH": 100, "copies": 1}), vec![(-10.0, 0.0), (10.0, 0.0)], vec![4.0, 4.0]), + (json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1}), vec![(20.0, 0.0), (10.0, 0.0)], vec![8.0, 4.0]), + // Scale Strokes & Effects does not scale the shadow a second time, nor leave it unturned. + ( + json!({"scaleH": 200, "scaleV": 200, "rotate": 90, "moveH": 100, "copies": 1, "strokes": true}), + vec![(0.0, -20.0), (10.0, 0.0)], + vec![8.0, 4.0], + ), + ( + json!({"scaleH": 200, "scaleV": 200, "rotate": 90, "moveH": 100, "copies": 1, "patterns": true}), + vec![(0.0, -20.0), (10.0, 0.0)], + vec![8.0, 4.0], + ), + ] +} + +/// Check that `n` is drawn, expanded and baked as `want.len()` paths, each with one shadow at the +/// offset and blur `want` and `blurs` give it, the last copy first. +fn assert_copies_carry(n: &Node, want: &[(f64, f64)], blurs: &[f64], what: &str) { + assert!(crate::has_transform_art(n), "{what}"); + for (how, art) in + [("drawn", crate::reshape(None, n, None).unwrap()), ("expanded", expand_outlined(None, n, None).unwrap()), ("baked", baked(n.clone()))] + { + assert_eq!(paths_in(&art), want.len(), "{what}: {how} {art:?}"); + let drawn = shadows_in(&art); + assert!(near(&drawn, want), "{what}: {how} {drawn:?}"); + let b = shadow_blurs_in(&art); + assert!(b.len() == blurs.len() && b.iter().zip(blurs).all(|(x, y)| (x - y).abs() < 1e-9), "{what}: {how} blurs {b:?}"); + } +} + +/// A fill's or stroke's own Transform effect that makes copies gives each copy the shadow listed +/// before it in that fill's or stroke's effects, moved, turned, reflected and scaled with that copy, +/// the last copy lowest: drawn, expanded and baked. The original keeps the shadow as it is. +#[test] +fn each_copy_of_a_fills_or_strokes_own_transform_carries_the_shadow_before_it() { + for stroke in [false, true] { + for (params, want, blurs) in copying_cases() { + let n = one_row(square(95, vec![]), stroke, vec![shadow(10.0, 0.0, 4.0), transform(params.clone())]); + assert_copies_carry(&n, &want, &blurs, &format!("stroke {stroke}: {params}")); + } + // A Transform effect that makes copies before the shadow: its copies make one piece, which + // the Transform effect after the shadow copies, each copy with its own shadow. + let effects = + vec![transform(json!({"moveV": 100, "copies": 1})), shadow(10.0, 0.0, 4.0), transform(json!({"rotate": 90, "moveH": 200, "copies": 1}))]; + let n = one_row(square(95, vec![]), stroke, effects); + assert!(crate::has_transform_art(&n), "stroke {stroke}"); + for (how, art) in + [("drawn", crate::reshape(None, &n, None).unwrap()), ("expanded", expand_outlined(None, &n, None).unwrap()), ("baked", baked(n.clone()))] + { + let drawn = shadows_in(&art); + assert!(near(&drawn, &[(0.0, -10.0), (10.0, 0.0)]), "stroke {stroke}: two copying Transform effects, {how} {drawn:?}"); + } + } +} + +/// A Transform effect that makes copies, listed after a fill's or stroke's first Transform effect +/// with Transform Patterns on, gives each copy the shadow listed before it, as the first one's +/// copies do, with or without options of its own: drawn, expanded and baked. +#[test] +fn each_copy_of_a_later_copying_transform_carries_the_shadow_before_it() { + for stroke in [false, true] { + for (params, want, blurs) in copying_cases() { + let effects = vec![transform(json!({"patterns": true})), shadow(10.0, 0.0, 4.0), transform(params.clone())]; + let n = one_row(square(102, vec![]), stroke, effects); + assert_copies_carry(&n, &want, &blurs, &format!("stroke {stroke}: {params}")); + } + } +} + +/// A fill's or stroke's shadow under its object's Transform effect that makes copies is carried by +/// each copy, moved, turned, reflected and scaled with it: for a single fill, a single stroke, and +/// a fill and a stroke that paint each copy below the one before. Drawn, expanded and baked. +#[test] +fn each_copy_of_an_objects_transform_carries_its_fills_or_strokes_shadow() { + for (params, want, blurs) in copying_cases() { + for stroke in [false, true] { + let mut n = one_row(square(96, vec![]), stroke, vec![shadow(10.0, 0.0, 4.0)]); + n.appearance.effects = vec![transform(params.clone())]; + assert_copies_carry(&n, &want, &blurs, &format!("stroke {stroke}: {params}")); + } + // Both a fill and a stroke: only the fill has the shadow. + let mut n = square(97, vec![transform(params.clone())]); + if let Some(vectorcraft_doc::AppearanceItem::Stroke(s)) = n.appearance.items.get_mut(1) { + s.paint = Paint::solid(Color::BLACK); + s.width = 2.0; + } + *n.appearance.items[0].effects_mut() = vec![shadow(10.0, 0.0, 4.0)]; + assert!(crate::has_transform_art(&n), "{params}"); + for (how, art) in + [("drawn", crate::reshape(None, &n, None).unwrap()), ("expanded", expand_outlined(None, &n, None).unwrap()), ("baked", baked(n.clone()))] + { + let drawn = shadows_in(&art); + assert!(near(&drawn, &want), "layered {params}: {how} {drawn:?}"); + } + } +} + +/// A shadow listed after a fill's own Transform effect that makes copies paints once around all of +/// them, and one listed before it on each copy. A Transform effect that makes no copies, or has +/// Transform Objects off, draws the fill as before, without art. +#[test] +fn a_fills_shadow_after_its_own_copying_transform_paints_once_around_the_copies() { + let effects = vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1})), shadow(0.0, 5.0, 0.0)]; + let n = one_row(square(98, vec![]), false, effects); + for (how, art) in + [("drawn", crate::reshape(None, &n, None).unwrap()), ("expanded", expand_outlined(None, &n, None).unwrap()), ("baked", baked(n.clone()))] + { + assert!(near(&shadows_in(&art), &[(0.0, 5.0), (0.0, -10.0), (10.0, 0.0)]), "{how}: {:?}", shadows_in(&art)); + assert_eq!(paths_in(&art), 2, "{how}"); + } + for params in [json!({"rotate": 90}), json!({"rotate": 90, "copies": 1, "objects": false})] { + let n = one_row(square(99, vec![]), false, vec![shadow(10.0, 0.0, 0.0), transform(params.clone())]); + assert!(!crate::has_transform_art(&n), "{params}"); + assert!(!crate::has_copied_row_raster(&n), "{params}"); + } + // A shadow between two Transform effects that make copies paints on what the second one + // copies, so the fill is drawn as before, without art. + let copies = transform(json!({"rotate": 90, "copies": 1})); + let n = one_row(square(99, vec![]), false, vec![shadow(10.0, 0.0, 0.0), copies.clone(), shadow(0.0, 5.0, 0.0), copies]); + assert!(!crate::has_copied_row_raster(&n)); + assert!(!crate::has_transform_art(&n)); +} + +/// Copies of a fill's own Transform effect that stop at the effect budget each keep their shadow, +/// and so do those of an object's Transform effect for its fill's shadow. +#[test] +fn row_copies_past_the_budget_each_keep_their_shadow() { + let copies = transform(json!({"moveV": 50, "copies": 1000})); + let own = one_row(path_node(100, wavy(30_000), vec![]), false, vec![shadow(1.0, 0.5, 0.0), copies.clone()]); + let mut owner = one_row(path_node(101, wavy(30_000), vec![]), false, vec![shadow(1.0, 0.5, 0.0)]); + owner.appearance.effects = vec![copies]; + for n in [own, owner] { + let art = crate::reshape(None, &n, None).unwrap(); + let paths = paths_in(&art); + assert!(paths > 1 && paths < 1001, "{paths}"); + assert_eq!(shadows_in(&art).len(), paths); + } +} + +/// Black 40 pt "IIII" with its baseline at (5, 60) and `effects`. +fn type_node(id: u64, effects: Vec) -> Node { + use vectorcraft_doc::text::{CharStyle, TextObject}; + let style = CharStyle { size: 40.0, fill: Paint::solid(Color::BLACK), ..Default::default() }; + let mut n = Node::new(NodeId(id), vectorcraft_doc::NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style)))); + n.appearance.effects = effects; + n +} + +/// An instance at (50, 50) with `effects` of a symbol, and the symbol's art: a black 20 pt square +/// centered on its origin. +fn instance(id: u64, effects: Vec) -> (Node, Node) { + let art = Node::path( + NodeId(900), + shapes::rectangle(Rect::new(-10.0, -10.0, 10.0, 10.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + let mut n = Node::new(NodeId(id), vectorcraft_doc::NodeKind::SymbolInstance { symbol: "Square".into(), xf: Affine::translate((50.0, 50.0)) }); + n.appearance.effects = effects; + (n, art) +} + +/// Type, an image and a symbol instance with a Transform effect that makes copies give each copy +/// the shadow listed before it, turned and scaled with that copy, the last copy lowest: drawn and +/// expanded. The object paints none around all of them, and a shadow listed after the Transform +/// effect still paints once around them. Built without fonts, type lays out no glyphs and only the +/// image and the instance are checked. +#[test] +fn each_copy_of_type_an_image_or_a_symbol_instance_carries_the_shadow_listed_before_it() { + let fonts = crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0); + if !fonts { + eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); + } + let objects = |effects: Vec| { + let (inst, art) = instance(96, effects.clone()); + let mut out = vec![("image", image(97, effects.clone()), None), ("instance", inst, Some(art))]; + if fonts { + out.push(("type", type_node(95, effects), None)); + } + out + }; + let cases = [ + (json!({"rotate": 90, "copies": 2}), vec![(-10.0, 0.0), (0.0, -10.0), (10.0, 0.0)], vec![4.0, 4.0, 4.0]), + (json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1}), vec![(20.0, 0.0), (10.0, 0.0)], vec![8.0, 4.0]), + ]; + for (params, want, blurs) in cases { + for (kind, n, symbol) in objects(vec![shadow(10.0, 0.0, 4.0), transform(params.clone())]) { + assert!(crate::outer_effects(&n).iter().all(|e| e.id != "stylize.dropShadow"), "{kind} {params}"); + let symbol = symbol.as_ref(); + for (how, drawn) in [("drawn", crate::reshape(None, &n, symbol)), ("expanded", expand_outlined(None, &n, symbol))] { + let drawn = drawn.unwrap_or_else(|| panic!("{kind} {params}: {how}")); + assert_eq!(drawn.children().map_or(0, Vec::len), want.len(), "{kind} {params}: {how} copies"); + assert!(drawn.appearance.effects.is_empty(), "{kind} {params}: {how} {:?}", drawn.appearance.effects); + assert!(near(&shadows_in(&drawn), &want), "{kind} {params}: {how} {:?}", shadows_in(&drawn)); + let b = shadow_blurs_in(&drawn); + assert!(b.len() == blurs.len() && b.iter().zip(&blurs).all(|(x, y)| (x - y).abs() < 1e-9), "{kind} {params}: {how} blurs {b:?}"); + } + } + } + let effects = vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1})), shadow(0.0, 5.0, 0.0)]; + for (kind, n, symbol) in objects(effects) { + assert_eq!(crate::outer_effects(&n).len(), 2, "{kind}"); + let drawn = crate::reshape(None, &n, symbol.as_ref()).unwrap(); + assert!(near(&shadows_in(&drawn), &[(0.0, 5.0), (0.0, -10.0), (10.0, 0.0)]), "{kind}: {:?}", shadows_in(&drawn)); + } +} + +/// Type whose Transform effect only moves its copies, baked for export, gives each copy the shadow +/// listed before that effect, as the canvas draws it, rather than staying type under one shadow. +#[test] +fn baked_type_whose_transform_moves_its_copies_keeps_a_shadow_on_each() { + if !crate::outline_text(&type_node(99, vec![])).is_some_and(|o| paths_in(&o) > 0) { + eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); + return; + } + let n = type_node(99, vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 150, "copies": 1}))]); + let drawn = baked(n); + assert!(near(&shadows_in(&drawn), &[(10.0, 0.0), (10.0, 0.0)]), "{:?}", shadows_in(&drawn)); +} + +/// Type with a fill whose own geometry effects reshape it keeps one set of raster effects around +/// all the copies. +#[test] +fn type_with_a_reshaped_fill_keeps_one_shadow_around_its_copies() { + let effects = vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))]; + let mut filled = type_node(98, effects.clone()); + filled.appearance.items.push(vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer { + effects: vec![fx("path.offsetPath", json!({"offset": 2}))], + ..vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK)) + })); + assert_eq!(crate::outer_effects(&filled).len(), 2); +} + +/// Type whose own fill's Transform effect makes copies is drawn as its outlines, and each copy +/// carries the shadow listed before that Transform effect, as a path's copies do: for the fill's +/// first Transform effect and for one listed after a Transform effect with Transform Patterns on. +/// Drawn, expanded and baked. +#[test] +fn type_carries_its_fills_shadow_on_each_copy() { + let filled = |mut n: Node, effects: Vec| { + n.appearance.items.push(vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer { + effects, + ..vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK)) + })); + n + }; + let copying = vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))]; + if !crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0) { + eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); + return; + } + let later = vec![transform(json!({"patterns": true})), shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))]; + for (what, effects) in [("first", copying), ("later", later)] { + let n = filled(type_node(95, vec![]), effects); + for (how, art) in + [("drawn", crate::reshape(None, &n, None)), ("expanded", expand_outlined(None, &n, None)), ("baked", Some(baked(n.clone())))] + { + let art = art.unwrap_or_else(|| panic!("{what}: {how}")); + assert!(near(&shadows_in(&art), &[(10.0, 0.0), (10.0, 0.0)]), "{what}: {how} {:?}", shadows_in(&art)); + // The two shadows are on two objects 100 pt apart: the type and its copy. + let mut lefts = vec![]; + art.walk(&mut |m| { + let lists = std::iter::once(&m.appearance.effects).chain(m.appearance.items.iter().map(|i| i.effects())); + let shadows = lists.map(|l| l.iter().filter(|e| e.id == "stylize.dropShadow").count()).sum::(); + if let Some(b) = m.geometric_bounds() { + lefts.extend(std::iter::repeat_n(b.x0, shadows)); + } + }); + lefts.sort_by(f64::total_cmp); + assert!(lefts.len() == 2 && (lefts[1] - lefts[0] - 100.0).abs() < 1e-6, "{what}: {how} {lefts:?}"); + } + } +} diff --git a/crates/effects/src/tests/typestroke.rs b/crates/effects/src/tests/typestroke.rs new file mode 100644 index 0000000000..d6c8e82cec --- /dev/null +++ b/crates/effects/src/tests/typestroke.rs @@ -0,0 +1,123 @@ +//! Character strokes of outlined type under the type's transform ([`paint_type_piece`]): a live +//! stroke with a scaled weight under a similarity, otherwise the area the stroke paints in text +//! space, placed by the transform and filled. + +use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint}; +use vectorcraft_doc::{Appearance, CharStyle, Dash, LineJoin, Node, NodeId, StrokeAlign}; +use vectorcraft_geom::{Affine, FillRule, Rect, shapes}; + +use crate::*; + +const BOX: Rect = Rect::new(0.0, 0.0, 10.0, 10.0); + +fn red() -> Color { + Color::rgb(1.0, 0.0, 0.0) +} + +/// A black run with a red stroke of `width` and round joins. +fn style(width: f64) -> CharStyle { + CharStyle { + fill: Paint::solid(Color::BLACK), + stroke: Paint::solid(red()), + stroke_width: width, + stroke_join: LineJoin::Round, + ..CharStyle::default() + } +} + +/// A 10 x 10 square in text space standing in for a glyph. +fn square() -> Node { + Node::path(NodeId(7), shapes::rectangle(BOX), Appearance::default()) +} + +fn area(n: &Node) -> f64 { + vectorcraft_pathops::area(n.path_data().unwrap(), FillRule::NonZero).abs() +} + +fn near(a: Rect, b: Rect) -> bool { + [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 0.05) +} + +#[test] +fn an_uneven_scale_fills_the_stroke_the_canvas_paints() { + let mut piece = square(); + let stroke = paint_type_piece(&mut piece, &style(4.0), BOX, Affine::scale_non_uniform(3.0, 1.0)).expect("a filled stroke"); + assert!(piece.appearance.stroke().is_none(), "the piece keeps only its fill"); + assert_eq!(piece.appearance.fill_paint(), Paint::solid(Color::BLACK)); + assert_eq!(piece.geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 30.0, 10.0)); + assert!(stroke.appearance.stroke().is_none()); + assert_eq!(stroke.appearance.fill_paint(), Paint::solid(red())); + assert_eq!(stroke.id, NodeId(7)); + // 4 pt across in text space: 12 pt across the upright sides and 4 pt across the level ones. + let b = stroke.geometric_bounds().unwrap(); + assert!(near(b, Rect::new(-6.0, -2.0, 36.0, 12.0)), "{b:?}"); + // The ring of a 10 pt square stroked 4 pt with round joins (180 + 4π outside, 36 inside), 3 times as wide. + let ring = 180.0 + 4.0 * std::f64::consts::PI - 36.0; + assert!((area(&stroke) - 3.0 * ring).abs() < 0.5, "{}", area(&stroke)); +} + +#[test] +fn a_similarity_keeps_the_live_stroke_with_a_scaled_weight() { + for (xf, weight) in [ + (Affine::translate((5.0, 5.0)), 4.0), + (Affine::scale(2.0), 8.0), + (Affine::rotate(0.5) * Affine::scale(2.0), 8.0), + (Affine::scale_non_uniform(-2.0, 2.0), 8.0), + ] { + let mut piece = square(); + assert!(paint_type_piece(&mut piece, &style(4.0), BOX, xf).is_none(), "{xf:?}"); + let st = piece.appearance.stroke().expect("a live stroke"); + assert!((st.width - weight).abs() < 1e-9, "{xf:?}: {}", st.width); + assert_eq!(st.join, LineJoin::Round); + } +} + +#[test] +fn shears_and_flattening_transforms_fill_the_stroke() { + // A shear keeps the area. + let mut piece = square(); + let stroke = paint_type_piece(&mut piece, &style(4.0), BOX, Affine::skew(0.5, 0.0)).expect("a filled stroke"); + let ring = 180.0 + 4.0 * std::f64::consts::PI - 36.0; + assert!((area(&stroke) - ring).abs() < 0.5, "{}", area(&stroke)); + // Flattened to a line or a point: no division by the determinant, nothing non-finite. + for xf in [Affine::scale_non_uniform(2.0, 0.0), Affine::scale(0.0)] { + let mut piece = square(); + let stroke = paint_type_piece(&mut piece, &style(4.0), BOX, xf).expect("a filled stroke"); + assert!(piece.appearance.stroke().is_none()); + if let Some(b) = stroke.geometric_bounds() { + assert!([b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()) && b.height().abs() < 1e-9, "{xf:?}: {b:?}"); + } + } +} + +#[test] +fn the_stroke_options_shape_the_filled_stroke_in_text_space() { + let xf = Affine::scale_non_uniform(3.0, 1.0); + let filled = |st: CharStyle| paint_type_piece(&mut square(), &st, BOX, xf); + // No stroke, or no weight: nothing is filled. + assert!(filled(style(0.0)).is_none()); + assert!(filled(CharStyle { stroke: Paint::None, ..style(4.0) }).is_none()); + // Inside and outside alignment are kept to their side of the square before it is scaled. + let inside = filled(CharStyle { stroke_align: StrokeAlign::Inside, ..style(4.0) }).unwrap(); + assert!(near(inside.geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 30.0, 10.0))); + assert!((area(&inside) - 3.0 * (100.0 - 4.0)).abs() < 0.5, "{}", area(&inside)); + let outside = filled(CharStyle { stroke_align: StrokeAlign::Outside, ..style(4.0) }).unwrap(); + assert!(near(outside.geometric_bounds().unwrap(), Rect::new(-12.0, -4.0, 42.0, 14.0)), "{:?}", outside.geometric_bounds()); + // Dashes are laid out along the square in text space: half of each 10 pt is painted. + let solid = area(&filled(style(1.0)).unwrap()); + let dash = Dash { pattern: vec![5.0, 5.0], ..Default::default() }; + let dashed = area(&filled(CharStyle { stroke_dash: Some(dash), ..style(1.0) }).unwrap()); + assert!(dashed < 0.7 * solid && dashed > 0.3 * solid, "{dashed} of {solid}"); +} + +#[test] +fn a_gradient_on_the_stroke_stays_where_the_stroke_had_it() { + let stops = vec![GradientStop::new(0.0, red()), GradientStop::new(1.0, Color::BLACK)]; + let ramp = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let mut piece = square(); + let stroke = paint_type_piece(&mut piece, &CharStyle { stroke: ramp, ..style(4.0) }, BOX, Affine::scale_non_uniform(3.0, 1.0)).unwrap(); + let Paint::Gradient(g) = stroke.appearance.fill_paint() else { panic!("a gradient fill") }; + // Fitted across the stroke's box in text space (the square grown by half the weight), then scaled. + let geom = g.geom.expect("placed"); + assert!((geom.start.x + 6.0).abs() < 1e-6 && (geom.end.x - 36.0).abs() < 1e-6, "{geom:?}"); +} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 0fccbcdecb..f972cbb7b3 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -29,6 +29,8 @@ vectorcraft-tools = { workspace = true } vectorcraft-text = { workspace = true } vectorcraft-render = { workspace = true } vectorcraft-pathops = { workspace = true } +# The panels and hinges of a packaging blank (Packaging Tools' Check Fold Lines). +vectorcraft-three-d = { workspace = true } vectorcraft-brush = { workspace = true } vectorcraft-trace = { workspace = true } vectorcraft-svg = { workspace = true } @@ -44,16 +46,16 @@ 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 } chrono = { workspace = true } # The XML parts of Word documents placed as type (place/docx.rs). -roxmltree = "0.21" +craft-xml = { workspace = true } # The compound file that holds a Word 97-2003 document placed as type (place/doc.rs). cfb = "0.15" kurbo = { workspace = true } @@ -78,6 +80,16 @@ heic-rs = { version = "=0.1.4", default-features = false, features = ["std", "pa rayon = { version = "1.12", optional = true } [dev-dependencies] +# JPEG XL files for the `.jxl` open and place tests. +zune-jpegxl = { workspace = true } +zune-core = { workspace = true } +# JPEG XL files for the import fuzz tests (tests/import_fuzz.rs). +craft-jxl = { workspace = true } +# vectorcraft-doc's Group 3 TIFF reader before craft-stream-codecs, the reference +# tests/group3_reference.rs compares it with. +hayro-ccitt = { workspace = true } +tiff = { workspace = true } +craft-stream-codecs = { workspace = true } vectorcraft-affinity = { workspace = true, features = ["synth"] } crc32fast = { workspace = true } vectorcraft-testkit = { workspace = true } @@ -89,9 +101,6 @@ vectorcraft-pdf = { workspace = true, features = ["read-count"] } wat = { workspace = true } # Zstandard streams for the Illustrator editing data fuzz tests. ruzstd = { workspace = true } -# JPEG XL files for the `.jxl` open and place tests. -zune-jpegxl = { workspace = true } -zune-core = { workspace = true } # The JavaScript parser's lexer, compared with the script checker's on the same scripts. vectorcraft-js = { workspace = true } # A bundled font's own glyph boxes, for the glyph bounds tests. diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index c6aed0a644..c4a86dd3a5 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -98,6 +98,8 @@ pub(crate) mod symboledit; pub mod symbollib; pub(crate) mod tabs; mod textedit; +mod xmlattrs; + pub use textedit::effective_kerning; pub mod textstyles; pub(crate) mod textwrap; @@ -233,11 +235,7 @@ pub fn has_multi(s: &Session) -> std::result::Result<(), String> { /// editing and symbol editing mode isolate their own layer, which does not count here; an object /// isolated inside them counts. pub(crate) fn ordinary_isolation(st: &crate::DocState) -> Option { - st.isolation.filter(|l| { - !st.doc.pattern_edit.as_ref().is_some_and(|e| e.layer == *l) - && !st.doc.mask_edit.as_ref().is_some_and(|e| e.layer == *l) - && !st.doc.symbol_edit.as_ref().is_some_and(|e| e.layer == *l) - }) + vectorcraft_tools::ordinary_isolation(&st.doc, st.isolation) } /// Objects are selected ([`has_selection`]), and in isolation mode ([`ordinary_isolation`]) at /// least one of them is inside the isolated object: Object › Lock's and Object › Hide's items. @@ -895,6 +893,10 @@ pub use buildcmds::live_paint_gaps; /// Control bar enable it when it changes one). pub use brushsym::reset_transformation_changes; +/// The Symbols panel's current symbol, as `symbol.list` answers it (the panel reads it on every +/// frame without running the command). +pub use brushsym::current_symbol; + /// The byte order of UTF-16 text without a byte-order mark, by Import Data Sets' rule (the Graph /// Data window reads files by it too). pub use variablecmds::utf16_order_without_mark; diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 66c67651a3..8c310878fd 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -8,6 +8,7 @@ mod contour; mod cutting; mod document; mod image; +mod packaging; mod pathtools; mod pen; mod select; @@ -15,6 +16,7 @@ mod shapes; mod typetools; pub(crate) use image::{DecodedImages, refresh_color_masks}; +pub(crate) use packaging::{role_swatch_edited, role_swatches_merged}; use super::CommandSpec; @@ -27,6 +29,7 @@ pub fn specs() -> Vec { v.extend(cutting::specs()); v.extend(document::specs()); v.extend(image::specs()); + v.extend(packaging::specs()); v.extend(pathtools::specs()); v.extend(pen::specs()); v.extend(select::specs()); diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index 6eb21c9a63..703d81ddc3 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -43,7 +43,7 @@ pub fn specs() -> Vec { "Apply as Filter", ["Object", "Plug-ins", "Color Effects"], None, - "{effect: a colour adjustment's effect id (adjust.brightnessContrast, adjust.curves, adjust.hueSaturation, adjust.levels, adjust.shiftToColor, adjust.temperatureTint, addon.color.exposure, addon.color.desaturate, addon.color.duotone or addon.color.invert), params?: {…} (as effect.apply; missing keys take the dialog defaults), fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?: [id…] (default: the selection)} recolour the objects and everything inside them as the live effect would draw them, but in their colours, as edit.colors.invert does (fills, strokes, type, gradient meshes, embedded images and pattern tiles), as one undo step (none when nothing changes); their effects stay. Duotone links a colour to its one tone's swatch as the live effect does. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed}", + "{effect: a colour adjustment's effect id (adjust.brightnessContrast, adjust.curves, adjust.hueSaturation, adjust.levels, adjust.shiftToColor, adjust.temperatureTint, addon.color.exposure, addon.color.desaturate, addon.color.duotone or addon.color.invert), params?: {…} (as effect.apply; missing keys take the dialog defaults), fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?: [id…] (default: the selection)} recolour the objects and everything inside them as the live effect would draw them, but in their colours, as edit.colors.invert does (fills, strokes, type, gradient meshes, embedded images and pattern tiles), as one undo step (none when nothing changes); their effects stay. Duotone links a colour to its one tone's swatch as the live effect does. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed}", has_selection, filter ), @@ -52,7 +52,7 @@ pub fn specs() -> Vec { "Print Ink Fixes", ["Object", "Plug-ins", "Color Effects"], None, - "{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes stop overprinting), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first). On a path directly in a graph series, the graph also stores a paint the ink limit changes on the topmost visible fill or stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}", + "{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes stop overprinting), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first). On a path directly in a graph series, the graph also stores a paint the ink limit changes on the topmost visible fill or stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}", has_doc, print_fixes::run ), @@ -70,7 +70,7 @@ pub fn specs() -> Vec { "Apply Nearest Swatch", ["Object", "Plug-ins", "Color Effects"], None, - "{library?: as addon.color.nearestSwatch (default: \"document\"), fill?: true, stroke?: true, ids?: [id…] (default: the selection)} give each solid colour and gradient stop of the selected objects' fills and strokes (their type's and those of the objects inside them; gradient meshes too) the colour of its nearest swatch in the library, as addon.color.nearestSwatch finds it, as one undo step (none when nothing changes): a global or spot swatch's colour links to it. A library's swatches the colours take are added to the document's first, as swatch.library.add adds them (a spot colour stays spot); images and patterns keep their colours. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed: paints changed, swatches: [the document swatches the colours took], added: [swatches added to the document]}", + "{library?: as addon.color.nearestSwatch (default: \"document\"), fill?: true, stroke?: true, ids?: [id…] (default: the selection)} give each solid colour and gradient stop of the selected objects' fills and strokes (their type's and those of the objects inside them; gradient meshes too) the colour of its nearest swatch in the library, as addon.color.nearestSwatch finds it, as one undo step (none when nothing changes): a global or spot swatch's colour links to it. A library's swatches the colours take are added to the document's first, as swatch.library.add adds them (a spot colour stays spot); images and patterns keep their colours. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed: paints changed, swatches: [the document swatches the colours took], added: [swatches added to the document]}", has_selection, nearest::apply ), @@ -79,7 +79,7 @@ pub fn specs() -> Vec { "Apply Fill to Stroke", ["Object", "Plug-ins", "Color Effects"], None, - "{ids?|id?, skipNone?: bool} each target's top stroke takes its own top fill, as it is (a colour in its model, a global or spot colour linked at its tint, a gradient or pattern with its placement, None); a stroke given paint at width 0 gets 1 pt, as Swap Fill and Stroke does. Type: each run's stroke takes its own fill, and while the Type tool has characters selected (no ids), only those. A graph's labels keep the paint when the graph is drawn again. On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row (exceptions: docs/mcp.md). skipNone: leave alone a target whose fill is None. A target whose stroke already has that paint is left as it is, and when nothing changes no undo step is recorded. The default stroke takes the default fill the same way → {objects}", + "{ids?|id?, skipNone?: bool} each target's top stroke takes its own top fill, as it is (a colour in its model, a global or spot colour linked at its tint, a gradient or pattern with its placement, None); a stroke given paint at width 0 gets 1 pt, as Swap Fill and Stroke does. Type: each run's stroke takes its own fill, and while the Type tool has characters selected (no ids), only those. A graph's labels keep the paint when the graph is drawn again, and its axis lines, tick marks and radar rings keep their new rows for every line of their kind. On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row (exceptions: docs/mcp.md). skipNone: leave alone a target whose fill is None. A target whose stroke already has that paint is left as it is, and when nothing changes no undo step is recorded. The default stroke takes the default fill the same way → {objects}", has_doc, |s, p| copy_paint(s, p, true) ), @@ -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 { @@ -259,7 +258,10 @@ fn copy_paint(s: &mut Session, p: &Value, to_stroke: bool) -> Result { // The graph keeps the paint its series marks and labels now have. let series = super::super::appearance::capture_series_paint_writes(&before, d, &ids, &written); let labels = super::super::graph::capture_label_styles(d, &ids, ©_run); - Ok(objects + usize::from(series || labels)) + let painted: Vec = written.iter().map(|(id, _)| *id).collect(); + // A line keeps the paint written to it, also when it already showed it, and the rest stays as its kind keeps it. + let lines = super::super::graph::capture_line_changes(&before, d, &painted) | super::super::graph::capture_line_paint_writes(d, &written); + Ok(objects + usize::from(series || labels || lines)) })?; } // The defaults for new art change the same way, as Swap Fill and Stroke changes them. 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/addons/packaging.rs b/crates/engine/src/cmd/addons/packaging.rs new file mode 100644 index 0000000000..6099386b98 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging.rs @@ -0,0 +1,22 @@ +//! Packaging Tools (`addon.packaging.*`), a built-in add-on for the dielines of boxes and other +//! folded packaging. A path is a fold line when its top stroke is painted with the swatch of a line +//! role: Cut, Crease, Partial Cut or Perforation ([`roles`]). The document's role table maps each +//! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Check Fold +//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Its submenu +//! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's. + +mod check; +mod roles; + +pub(crate) use roles::{role_swatch_edited, role_swatches_merged}; + +use super::super::CommandSpec; + +pub fn specs() -> Vec { + let mut v = roles::specs(); + v.extend(check::specs()); + v +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/packaging/check.rs b/crates/engine/src/cmd/addons/packaging/check.rs new file mode 100644 index 0000000000..da8f7f25dd --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/check.rs @@ -0,0 +1,179 @@ +//! Check Fold Lines (`addon.packaging.check`): the blanks the fold lines make, their panels and +//! hinges, and what is wrong with the lines, found by [`vectorcraft_three_d::fold::blanks`]. + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_geom::PathData; +use vectorcraft_three_d::fold::{FoldLine, IssueCode, LineKind, MAX_SEGMENTS, blanks}; + +use super::super::super::pathops::length_given; +use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or}; +use super::roles::{Role, RoleTable, can_carry, role_targets}; +use crate::{Result, Session}; + +const CHECK: &str = "addon.packaging.check"; + +/// How far apart the ends of two lines may be and still be joined, in points. +const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0); + +pub fn specs() -> Vec { + vec![cmd!( + "addon.packaging.check", + "Check Fold Lines", + ["Object", "Plug-ins", "Packaging Tools"], + None, + "{ids?: [id…] (default: the selection), select?: bool (false), tolerance?: pt 0.01..10 (0.1)} check the fold lines (addon.packaging.roles) among the objects (through groups and clip groups), or, while nothing is selected and ids is left out, every fold line of the document; hidden lines are left out, also in a selected group. Cut lines bound the blanks: each connected piece of them that encloses material is one blank, its outline is its largest closed cut line, and a closed cut line inside it is a hole, so a slot drawn as a rectangle across the outline leaves the same material as a notch drawn in it; open cut lines that meet end to end count as one closed cut line. Crease, Partial Cut and Perforation lines divide a blank into panels; the pieces of them between two panels are that pair's hinge. A cut line end that comes within tolerance of another cut line is joined to it. Issues, in this order: noCut, open, looseEnd (errors), gap (a warning: the gap is closed), tooComplex (an error: more than 65,536 segments or 256 panels in a blank), cutOverCrease (an error), duplicate (two cut lines, or two lines that fold of any role), danglingCrease, noSplit, outside (wholly, or in part for tolerance or more), notStraight (a hinge's pieces are not on one straight line), sliver, ambiguous, loosePanel (joined to the largest panel by no chain of hinges), nonPrinting (warnings). With select, the objects the issues name become the selection, unless no issue names one. Changes nothing in the document → {ok (no error), blanks, panels, hinges, holes, issues: [{severity: error|warning, code, message (English), ids, at?: [x, y]}], scope: ids|selection|document}", + has_doc, + check + )] +} + +/// The English message for an issue (the Fold Lines panel shows it in the interface language). +fn message(code: IssueCode, scope: &str) -> &'static str { + match code { + IssueCode::NoCut if scope == "document" => "No cut lines are in the document.", + IssueCode::NoCut if scope == "ids" => "No cut lines are among the given objects.", + IssueCode::NoCut => "No cut lines are in the selection.", + IssueCode::Open => "The cut lines do not enclose an area.", + IssueCode::LooseEnd => "A cut line ends without meeting another cut line.", + IssueCode::Gap => "A gap between cut lines was closed.", + IssueCode::TooComplex => "The fold lines are too complex to check.", + IssueCode::CutOverCrease => "A cut line and a crease lie on top of each other.", + IssueCode::Duplicate => "Two fold lines lie on top of each other.", + IssueCode::DanglingCrease => "A crease ends inside a panel.", + IssueCode::NoSplit => "A crease does not divide two panels.", + IssueCode::Outside => "A crease lies outside the cut outline, wholly or in part.", + IssueCode::NotStraight => "The pieces of a hinge are not on one straight line.", + IssueCode::Sliver => "A gap between cut lines is too narrow to tell apart.", + IssueCode::Ambiguous => "A cut-out area holds other fold lines or another blank.", + IssueCode::LoosePanel => "A panel is not joined to the rest by a crease.", + IssueCode::NonPrinting => "A fold line is on a non-printing layer.", + } +} + +/// Every object of the document that can carry a role and is shown: on a shown layer, in shown +/// groups, and shown itself. +fn shown_targets(d: &Document) -> Vec { + fn walk(n: &Node, out: &mut Vec) { + if !n.visible { + return; + } + match &n.kind { + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)), + _ if can_carry(n) => out.push(n.id), + _ => {} + } + } + let mut out = vec![]; + d.layers.iter().for_each(|l| walk(l, &mut out)); + out +} + +/// The path of object `n` in document coordinates: a path's own, or a compound path's members'. +fn path_of(n: &Node) -> Option { + match &n.kind { + NodeKind::Path { path, .. } => Some(path.clone()), + NodeKind::Compound { children, .. } => Some(PathData::new( + children + .iter() + .filter_map(|c| match &c.kind { + NodeKind::Path { path, .. } => Some(path.subpaths.iter().cloned()), + _ => None, + }) + .flatten() + .collect(), + )), + _ => None, + } +} + +/// Whether object `id` is on a layer, or a sublayer, that does not print. +fn on_non_printing_layer(d: &Document, id: NodeId) -> bool { + d.ancestry(id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(|n| matches!(n.kind, NodeKind::Layer { printable: false, .. })) +} + +fn kind(role: Role) -> LineKind { + match role { + Role::Cut => LineKind::Cut, + Role::Crease => LineKind::Crease, + Role::PartialCut => LineKind::PartialCut, + Role::Perforation => LineKind::Perforation, + } +} + +fn check(s: &mut Session, p: &Value) -> Result { + let select = switch_or(p, "select", false, CHECK)?; + let tolerance = match length_given(p, "tolerance", CHECK)? { + None => TOLERANCE.1, + Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => t, + Some(_) => return Err(bad(CHECK, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))), + }; + let given = p.get("ids").is_some_and(|v| !v.is_null()); + let roots = checked_ids_or_selection(s, p, CHECK)?; + let d = &s.doc()?.doc; + // Hidden lines are left out in every scope, members of a selected group included. + let shown = |ids: Vec| ids.into_iter().filter(|id| d.is_visible(*id)).collect::>(); + let (scope, targets) = match (given, roots.is_empty()) { + (true, _) => ("ids", shown(role_targets(d, &roots, false).0)), + (false, false) => ("selection", shown(role_targets(d, &roots, false).0)), + (false, true) => ("document", shown_targets(d)), + }; + let table = RoleTable::of(d); + let mut lines = vec![]; + let mut non_printing = vec![]; + let mut segments = 0usize; + for id in targets { + // Once the lines have more segments than the check takes, it reports them as too complex: + // the rest are not copied. + if segments > MAX_SEGMENTS { + break; + } + let Some(n) = d.node(id) else { continue }; + let (Some(role), Some(path)) = (table.role_of(n), path_of(n)) else { continue }; + if on_non_printing_layer(d, id) { + non_printing.push(id.0); + } + segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum()); + lines.push(FoldLine { path, kind: kind(role), key: id.0 }); + } + let (found, mut issues) = blanks(&lines, tolerance); + if !non_printing.is_empty() { + issues.push(vectorcraft_three_d::fold::Issue { code: IssueCode::NonPrinting, keys: non_printing, at: None }); + } + let ok = !issues.iter().any(|i| i.code.is_error()); + let rows: Vec = issues + .iter() + .map(|i| { + let mut row = json!({ + "severity": if i.code.is_error() { "error" } else { "warning" }, + "code": i.code.id(), + "message": message(i.code, scope), + "ids": i.keys, + }); + if let (Some(at), Some(o)) = (i.at, row.as_object_mut()) { + o.insert("at".into(), json!([at.x, at.y])); + } + row + }) + .collect(); + if select { + let mut ids: Vec = issues.iter().flat_map(|i| i.keys.iter().map(|k| NodeId(*k))).filter(|id| d.node(*id).is_some()).collect(); + ids.sort_unstable_by_key(|id| id.0); + ids.dedup(); + if !ids.is_empty() { + s.select(|_, sel| sel.set(ids.iter().copied()))?; + } + } + Ok(json!({ + "ok": ok, + "blanks": found.len(), + "panels": found.iter().map(|b| b.panels.len()).sum::(), + "hinges": found.iter().map(|b| b.hinges.len()).sum::(), + "holes": found.iter().map(|b| b.holes.len()).sum::(), + "issues": rows, + "scope": scope, + })) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/packaging/check/tests.rs b/crates/engine/src/cmd/addons/packaging/check/tests.rs new file mode 100644 index 0000000000..9940761dea --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/check/tests.rs @@ -0,0 +1,180 @@ +//! Tests for Check Fold Lines: the blanks, panels, hinges and issues of fold lines drawn in a +//! document. + +use serde_json::{Value, json}; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + s +} + +fn path(s: &mut Session, d: &str) -> u64 { + s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap() +} + +fn role(s: &mut Session, role: &str, ids: &[u64]) { + s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap(); +} + +fn check(s: &mut Session, p: Value) -> Value { + s.execute("addon.packaging.check", &p).unwrap() +} + +fn codes(r: &Value) -> Vec<&str> { + r["issues"].as_array().unwrap().iter().map(|i| i["code"].as_str().unwrap()).collect() +} + +/// A tray blank: a 100 pt base with a 40 pt wall on each side, its outline a cut line and the +/// base's four sides creases → (outline, creases). +fn tray(s: &mut Session) -> (u64, Vec) { + let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z"); + let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")]; + role(s, "cut", &[outline]); + role(s, "crease", &creases); + s.execute("select.none", &json!({})).unwrap(); + (outline, creases) +} + +#[test] +fn a_tray_checks_clean_with_five_panels_and_four_hinges() { + let mut s = session(); + tray(&mut s); + let steps = s.doc().unwrap().history.undo.len(); + let r = check(&mut s, json!({})); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!((r["blanks"].as_u64(), r["panels"].as_u64(), r["hinges"].as_u64(), r["holes"].as_u64()), (Some(1), Some(5), Some(4), Some(0)), "{r}"); + assert!(codes(&r).is_empty(), "{r}"); + assert_eq!(r["scope"], "document"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "a check records no undo step"); +} + +#[test] +fn the_selection_or_ids_limit_the_check_to_their_lines() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + s.execute("select.set", &json!({ "ids": [creases[0]] })).unwrap(); + let r = check(&mut s, json!({})); + assert_eq!((r["scope"].as_str(), r["ok"].as_bool()), (Some("selection"), Some(false))); + assert_eq!(codes(&r), ["noCut"]); + assert_eq!(r["issues"][0]["message"], "No cut lines are in the selection."); + let r = check(&mut s, json!({ "ids": [outline] })); + assert_eq!((r["scope"].as_str(), r["ok"].as_bool(), r["panels"].as_u64()), (Some("ids"), Some(true), Some(1)), "{r}"); + let r = check(&mut s, json!({ "ids": [creases[1]] })); + assert_eq!((r["scope"].as_str(), codes(&r)), (Some("ids"), vec!["noCut"])); + assert_eq!(r["issues"][0]["message"], "No cut lines are among the given objects."); + // No fold lines at all in the document. + let mut s = session(); + let r = check(&mut s, json!({})); + assert_eq!(codes(&r), ["noCut"]); + assert_eq!(r["issues"][0]["message"], "No cut lines are in the document."); +} + +#[test] +fn issues_name_their_lines_and_select_selects_them() { + let mut s = session(); + let (_, creases) = tray(&mut s); + // A slit from the outline that stops in the middle of the base. + let slit = path(&mut s, "M190 100 L190 190"); + role(&mut s, "cut", &[slit]); + s.execute("select.none", &json!({})).unwrap(); + let r = check(&mut s, json!({})); + assert_eq!(r["ok"], false); + let loose = r["issues"].as_array().unwrap().iter().find(|i| i["code"] == "looseEnd").cloned().unwrap(); + assert_eq!((loose["severity"].as_str(), loose["ids"].clone()), (Some("error"), json!([slit])), "{r}"); + assert_eq!(loose["at"], json!([190.0, 190.0])); + assert!(s.doc().unwrap().selection.objects.is_empty(), "without select, the selection stays"); + let r = check(&mut s, json!({ "select": true })); + let named: std::collections::BTreeSet = + r["issues"].as_array().unwrap().iter().flat_map(|i| i["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap())).collect(); + let selected: std::collections::BTreeSet = s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect(); + assert!(selected.contains(&slit) && selected == named, "{selected:?} {named:?}"); + assert!(!selected.contains(&creases[1])); +} + +#[test] +fn a_clean_check_with_select_leaves_the_selection_alone() { + let mut s = session(); + let (outline, _) = tray(&mut s); + s.execute("select.set", &json!({ "ids": [outline] })).unwrap(); + let r = check(&mut s, json!({ "ids": [outline], "select": true })); + assert!(codes(&r).is_empty(), "{r}"); + assert_eq!(s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect::>(), [outline]); +} + +#[test] +fn tolerance_is_checked_and_joins_gaps_up_to_it() { + let mut s = session(); + tray(&mut s); + for bad in [json!(0.005), json!(10.5), json!("x"), json!(true)] { + let e = s.execute("addon.packaging.check", &json!({ "tolerance": bad })).unwrap_err().to_string(); + assert!(e.contains("tolerance"), "{e}"); + } + let e = s.execute("addon.packaging.check", &json!({ "select": 1 })).unwrap_err().to_string(); + assert!(e.contains("select"), "{e}"); + for edge in [json!(0.01), json!(10), json!("2 mm")] { + assert_eq!(check(&mut s, json!({ "tolerance": edge }))["ok"], true); + } + // A slit that stops 0.5 pt short of a crease: a gap at a tolerance of 1 pt, a loose end at 0.1 pt. + let mut s = session(); + tray(&mut s); + let slit = path(&mut s, "M190 100 L190 139.5"); + role(&mut s, "cut", &[slit]); + s.execute("select.none", &json!({})).unwrap(); + assert!(codes(&check(&mut s, json!({ "tolerance": 0.1 }))).contains(&"looseEnd")); + let near = check(&mut s, json!({ "tolerance": 1 })); + assert!(!codes(&near).contains(&"looseEnd"), "{near}"); +} + +#[test] +fn hidden_lines_are_left_out_and_lines_on_a_non_printing_layer_are_noted() { + let mut s = session(); + let (_, creases) = tray(&mut s); + // A hidden crease is not checked while nothing is selected: the tray has three hinges and a + // panel joined by none. + s.execute("layer.setProps", &json!({ "ids": [creases[0]], "visible": false })).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let r = check(&mut s, json!({})); + assert_eq!((r["panels"].as_u64(), r["hinges"].as_u64()), (Some(4), Some(3)), "{r}"); + // The same in a selected group, and with the group named by `ids`: the hidden member is left + // out too. + let mut s = session(); + let (outline, creases) = tray(&mut s); + s.execute("select.set", &json!({ "ids": [outline, creases[0], creases[1], creases[2], creases[3]] })).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.setProps", &json!({ "ids": [creases[0]], "visible": false })).unwrap(); + s.execute("select.set", &json!({ "ids": [group] })).unwrap(); + for p in [json!({}), json!({ "ids": [group] })] { + let r = check(&mut s, p); + assert_eq!((r["panels"].as_u64(), r["hinges"].as_u64()), (Some(4), Some(3)), "{r}"); + } + // A cut line on a layer that does not print. + let mut s = session(); + s.execute("layer.new", &json!({ "printable": false })).unwrap(); + let (outline, _) = tray(&mut s); + let r = check(&mut s, json!({})); + assert_eq!(r["ok"], true, "a warning only"); + let note = r["issues"].as_array().unwrap().iter().find(|i| i["code"] == "nonPrinting").cloned().unwrap(); + assert_eq!(note["severity"], "warning"); + assert!(note["ids"].as_array().unwrap().contains(&json!(outline)), "{note}"); + assert_eq!(note["message"], "A fold line is on a non-printing layer."); +} + +#[test] +fn a_compound_path_and_a_grouped_line_are_checked() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + // A window: a closed cut line in the base, made a compound path with nothing else. + let window = path(&mut s, "M170 170 L210 170 L210 210 L170 210 Z"); + s.execute("select.set", &json!({ "ids": [window] })).unwrap(); + let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64(); + let window = compound.unwrap_or(window); + role(&mut s, "cut", &[window]); + s.execute("select.set", &json!({ "ids": [outline, creases[0], creases[1], creases[2], creases[3], window] })).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let r = check(&mut s, json!({})); + assert_eq!(r["scope"], "selection"); + assert_eq!((r["ok"].as_bool(), r["panels"].as_u64(), r["holes"].as_u64()), (Some(true), Some(5), Some(1)), "{r}"); +} diff --git a/crates/engine/src/cmd/addons/packaging/roles.rs b/crates/engine/src/cmd/addons/packaging/roles.rs new file mode 100644 index 0000000000..2b3c7696f3 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/roles.rs @@ -0,0 +1,454 @@ +//! Fold line roles (`addon.packaging.setRole`, `addon.packaging.roles`, +//! `addon.packaging.setRoleSwatch`). A path, compound path or live shape has a role when its top +//! stroke is painted with the swatch the document's role table gives that role, at any tint. The +//! table lives in [`Document::unknown`] under [`ROLES_KEY`], `{cut, crease, partialCut, +//! perforation}` each naming a swatch; a role it leaves out, or names with something other than a +//! string, takes its default swatch, named after the role. + +use serde_json::{Map, Value, json}; +use vectorcraft_color::swatch::REGISTRATION; +use vectorcraft_color::{Color, Paint, Swatch}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; + +use super::super::super::overprint::edit_counted; +use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param}; +use crate::{Result, Session}; + +/// Document unknown key: the role table, `{role id: swatch name}`. +pub(crate) const ROLES_KEY: &str = "packagingRoles"; + +const SET_ROLE: &str = "addon.packaging.setRole"; +const ROLES: &str = "addon.packaging.roles"; +const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch"; + +/// What a fold line does when the blank is cut and folded. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Role { + /// Separates the material. + Cut, + /// A fold. + Crease, + /// A fold cut part way through the board. + PartialCut, + /// A fold along a line of cuts. + Perforation, +} + +impl Role { + pub(crate) const ALL: [Role; 4] = [Role::Cut, Role::Crease, Role::PartialCut, Role::Perforation]; + + /// The role's id in params and in the role table. + pub(crate) fn id(self) -> &'static str { + match self { + Role::Cut => "cut", + Role::Crease => "crease", + Role::PartialCut => "partialCut", + Role::Perforation => "perforation", + } + } + + /// The role's name, which is also its default swatch's name. + pub(crate) fn name(self) -> &'static str { + match self { + Role::Cut => "Cut", + Role::Crease => "Crease", + Role::PartialCut => "Partial Cut", + Role::Perforation => "Perforation", + } + } + + pub(crate) fn from_id(id: &str) -> Option { + Role::ALL.into_iter().find(|r| r.id() == id) + } + + /// The color a missing role swatch is made with (VectorCraft's own values): Cut 100% magenta, + /// Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan. + fn color(self) -> Color { + match self { + Role::Cut => Color::cmyk(0.0, 1.0, 0.0, 0.0), + Role::Crease => Color::cmyk(1.0, 0.0, 0.0, 0.0), + Role::PartialCut => Color::cmyk(0.0, 0.0, 1.0, 0.0), + Role::Perforation => Color::cmyk(0.5, 0.5, 0.0, 0.0), + } + } + + fn index(self) -> usize { + Role::ALL.iter().position(|r| *r == self).unwrap_or(0) + } +} + +/// The swatch each role is carried by, in [`Role::ALL`] order. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct RoleTable([String; 4]); + +impl RoleTable { + /// The document's role table, with each missing or damaged entry at its default. When a damaged + /// table names one swatch for two roles, the later role takes its default name instead, or + /// "Crease 2" and so on when an earlier role has that. + pub(crate) fn of(d: &Document) -> RoleTable { + let stored = d.unknown.get(ROLES_KEY).and_then(Value::as_object); + let mut names: Vec = Vec::with_capacity(Role::ALL.len()); + for r in Role::ALL { + let name = match stored.and_then(|m| m.get(r.id())).and_then(Value::as_str) { + Some(name) if !name.is_empty() && !names.iter().any(|n| n == name) => name.to_string(), + _ => { + let base = r.name(); + std::iter::once(base.to_string()) + .chain((2..).map(|i| format!("{base} {i}"))) + .find(|n| !names.contains(n)) + .unwrap_or_else(|| base.to_string()) + } + }; + names.push(name); + } + RoleTable(Role::ALL.map(|r| names.get(r.index()).cloned().unwrap_or_else(|| r.name().to_string()))) + } + + /// The swatch of `role`. + pub(crate) fn swatch(&self, role: Role) -> &str { + self.0.get(role.index()).map_or("", String::as_str) + } + + /// The role swatch `name` carries. + pub(crate) fn role_of_swatch(&self, name: &str) -> Option { + Role::ALL.into_iter().find(|r| self.swatch(*r) == name) + } + + /// The role of object `n`: the role of the swatch its top stroke is painted with. + pub(crate) fn role_of(&self, n: &Node) -> Option { + if !can_carry(n) { + return None; + } + match &n.appearance.stroke()?.paint { + Paint::Solid { swatch: Some(name), .. } => self.role_of_swatch(name), + _ => None, + } + } + + fn to_value(&self) -> Value { + Value::Object(Role::ALL.into_iter().map(|r| (r.id().to_string(), json!(self.swatch(r)))).collect::>()) + } +} + +/// Swatch `from` of `d` is now named `to`, and `global` says whether it is still a global color. +/// A role it carried keeps it under the new name, as the strokes linked to it do; when it stopped +/// being global, which unlinks those strokes, the role moves to a new name that `setRole` makes a +/// swatch for. Another role that named `to` without such a swatch moves to a new name too, so no +/// two roles share a swatch. +pub(crate) fn role_swatch_edited(d: &mut Document, from: &str, to: &str, global: bool) { + let before = RoleTable::of(d); + let mut table = before.clone(); + for r in Role::ALL { + let name = table.swatch(r).to_string(); + let moved = if name == from && global { + Some(to.to_string()) + } else if name == from || (name == to && from != to) { + Some(free_role_name(d, &table, r)) + } else { + None + }; + if let (Some(new), Some(slot)) = (moved, table.0.get_mut(r.index())) { + *slot = new; + } + } + if table != before { + d.unknown.insert(ROLES_KEY.to_string(), table.to_value()); + } +} + +/// Swatches `merged` of `d` were merged into swatch `kept`, and `linked` says whether their strokes +/// now link to it (it is a global color). When `kept` carries no role, it takes the role of the +/// first merged swatch that carried one, so the lines of that role keep it; a merged swatch's other +/// role keeps its name, which the next `setRole` makes a swatch for. +pub(crate) fn role_swatches_merged(d: &mut Document, merged: &[String], kept: &str, linked: bool) { + let mut table = RoleTable::of(d); + if !linked || table.role_of_swatch(kept).is_some() { + return; + } + let Some(role) = merged.iter().find_map(|m| table.role_of_swatch(m)) else { return }; + if let Some(slot) = table.0.get_mut(role.index()) { + *slot = kept.to_string(); + } + d.unknown.insert(ROLES_KEY.to_string(), table.to_value()); +} + +/// A name for `role`'s swatch that no swatch, color group or other role of `table` uses: the +/// role's name, else "Cut 2", "Cut 3"… The document holds finitely many names, so the search +/// always ends at a free one. +fn free_role_name(d: &Document, table: &RoleTable, role: Role) -> String { + let free = |n: &str| !d.swatch_name_taken(n) && Role::ALL.into_iter().all(|r| r == role || table.swatch(r) != n); + let base = role.name(); + if free(base) { + return base.to_string(); + } + (2usize..).map(|i| format!("{base} {i}")).find(|n| free(n)).unwrap_or_else(|| base.to_string()) +} + +/// Whether `n` can carry a role: a path (a live shape too) that is neither a clipping path nor a +/// guide, or a compound path. +pub(super) fn can_carry(n: &Node) -> bool { + match &n.kind { + NodeKind::Path { clipping, guide, .. } => !clipping && !guide, + NodeKind::Compound { .. } => true, + _ => false, + } +} + +/// The objects under the outermost objects `roots` that can carry a role, through groups and clip +/// groups, each once, and +/// how many of `roots` and their members can't (text, images, symbol instances and other objects). +/// With `editable`, objects that are locked or hidden, are in a locked or hidden group or layer, or +/// are on a locked artboard are left out and counted as skipped. +pub(super) fn role_targets(d: &Document, roots: &[NodeId], editable: bool) -> (Vec, usize) { + fn walk(n: &Node, out: &mut Vec, skipped: &mut usize) { + match &n.kind { + NodeKind::Group { children, .. } => { + for c in children { + // A group's clipping path draws no stroke: it is skipped. + if matches!(c.kind, NodeKind::Path { clipping: true, .. }) { + *skipped += 1; + } else { + walk(c, out, skipped); + } + } + } + _ if can_carry(n) => out.push(n.id), + _ => *skipped += 1, + } + } + let (mut out, mut skipped) = (vec![], 0); + // A path of a compound path is painted with the compound's appearance: the compound takes the + // role. `roots` come from `checked_ids_or_selection`, which keeps only outermost objects, so a + // group and its member are never both roots. + let mut seen = std::collections::HashSet::new(); + let compound_of = |id: NodeId| d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); + for n in roots.iter().map(|id| compound_of(*id).unwrap_or(*id)).filter(|id| seen.insert(*id)).filter_map(|id| d.node(id)) { + walk(n, &mut out, &mut skipped); + } + if editable { + // Named directly or not, a locked or hidden object, or one in a locked or hidden group or + // layer or on a locked artboard, stays as it is. + let ok = d.editable(); + let before = out.len(); + out.retain(|id| ok(*id)); + skipped += before - out.len(); + } + (out, skipped) +} + +/// Every object of the document that can carry a role, through layers and groups. +fn document_targets(d: &Document) -> Vec { + fn walk(n: &Node, out: &mut Vec) { + match &n.kind { + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)), + _ if can_carry(n) => out.push(n.id), + _ => {} + } + } + let mut out = vec![]; + d.layers.iter().for_each(|l| walk(l, &mut out)); + out +} + +pub fn specs() -> Vec { + vec![ + cmd!( + "addon.packaging.setRole", + "Make Fold Line", + ["Object", "Plug-ins", "Packaging Tools"], + None, + "{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}", + has_selection, + set_role + ), + cmd!( + query "addon.packaging.roles", + "Fold Lines", + [], + None, + "{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected)}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out", + has_doc, + roles + ), + cmd!( + "addon.packaging.setRoleSwatch", + "Role Swatches…", + ["Object", "Plug-ins", "Packaging Tools"], + None, + "{role: cut|crease|partialCut|perforation, swatch: a global or spot color swatch's name} make the swatch carry the role, in the document's role table, as one undo step (none when it already does). Objects stroked with the role's old swatch keep their color and no longer have the role. Refused: a missing swatch, a gradient or pattern swatch, a process color that is not global, a tint swatch, [None], [Registration], and a swatch another role has → {role, swatch, changed}", + has_doc, + set_role_swatch + ), + ] +} + +/// The role `p` gives: `Some(None)` for `none` when `none` is allowed. +fn role_param(p: &Value, cmd: &str, none: bool) -> Result> { + let id = text_param(p, "role", cmd)?.ok_or_else(|| bad(cmd, "missing `role`"))?; + match Role::from_id(id) { + Some(r) => Ok(Some(r)), + None if none && id == "none" => Ok(None), + None if none => Err(bad(cmd, format!("unknown role `{id}`: cut, crease, partialCut, perforation or none"))), + None => Err(bad(cmd, format!("unknown role `{id}`: cut, crease, partialCut or perforation"))), + } +} + +/// Why swatch `name` of `d` can't carry a role, if it can't. +fn unfit_swatch(d: &Document, name: &str) -> Option { + if name == REGISTRATION || name == "[None]" { + return Some(format!("`{name}` can't carry a role")); + } + let Some(sw) = d.swatch(name) else { return Some(format!("no swatch `{name}`")) }; + match &sw.paint { + Paint::Solid { swatch: Some(_), .. } => Some(format!("`{name}` is a tint swatch: pick its base or another global or spot color")), + Paint::Solid { .. } if sw.global => None, + Paint::Solid { .. } => Some(format!("`{name}` is a process color: pick a global or spot color")), + _ => Some(format!("`{name}` isn't a color swatch")), + } +} + +/// `role`'s swatch in `d`, made as a global spot swatch in the document's color mode when `d` +/// lacks it → its paint at 100%. When a color group or a swatch that can't carry a role (a process +/// color that is not global, a tint, a gradient) has the swatch's name, the swatch is made under a +/// free name, which the role table then gives the role. +fn role_paint(d: &mut Document, role: Role) -> Result { + let mut table = RoleTable::of(d); + let current = table.swatch(role); + let taken = match d.swatch(current) { + Some(_) => unfit_swatch(d, current).is_some(), + None => d.swatch_name_taken(current), + }; + if taken { + let free = free_role_name(d, &table, role); + if let Some(slot) = table.0.get_mut(role.index()) { + *slot = free; + } + d.unknown.insert(ROLES_KEY.to_string(), table.to_value()); + } + let name = table.swatch(role); + if d.swatch(name).is_none() { + let model = d.color_mode.model(); + let color = role.color(); + let color = if color.model() == model { + color + } else { + let cms = vectorcraft_color::cms::active(); + cms.convert(&color, model, cms.settings().intent) + }; + d.swatches.push(Swatch { name: name.to_string(), paint: Paint::solid(color), global: true, spot: true }); + } + if let Some(why) = unfit_swatch(d, name) { + return Err(bad(SET_ROLE, format!("{why} (the {} role's swatch; addon.packaging.setRoleSwatch picks another)", role.name()))); + } + d.tint_paint(name, 1.0).ok_or_else(|| bad(SET_ROLE, format!("`{name}` isn't a global or spot color"))) +} + +/// Gives object `id` of `d` `role`'s `paint` (`None`: takes its role away) → whether it changed. +fn give_role(d: &mut Document, table: &RoleTable, id: NodeId, paint: Option<&Paint>, overprint: bool) -> bool { + let Some(n) = d.node_mut(id) else { return false }; + let had = table.role_of(n); + let mut a = (*n.appearance).clone(); + match paint { + Some(paint) => { + a.set_stroke(paint.clone()); + if let Some(st) = a.stroke_mut() { + if st.width <= 0.0 { + st.width = 1.0; + } + // A hidden stroke would carry the role without drawing or printing the line. + st.visible = true; + st.overprint = overprint; + } + } + None => { + if had.is_none() { + return false; + } + if let Some(st) = a.stroke_mut() { + if let Paint::Solid { color, .. } = st.paint { + st.paint = Paint::solid(color); + } + st.overprint = false; + } + } + } + if a == *n.appearance { + return false; + } + n.appearance = vectorcraft_doc::Shared::new(a); + true +} + +fn set_role(s: &mut Session, p: &Value) -> Result { + let role = role_param(p, SET_ROLE, true)?; + let overprint = switch_or(p, "overprint", true, SET_ROLE)?; + let roots = checked_ids_or_selection(s, p, SET_ROLE)?; + let (ids, skipped) = role_targets(&s.doc()?.doc, &roots, true); + if ids.is_empty() { + return Err(bad(SET_ROLE, "select a path that is neither locked nor hidden: text, images and symbol instances can't have a fold line role")); + } + let label = role.map_or("Remove Fold Line Role", |_| "Make Fold Line"); + let mut changed = 0; + edit_counted(s, label, |d| { + let before = (d.swatches.len(), d.unknown.get(ROLES_KEY).cloned()); + let paint = role.map(|r| role_paint(d, r)).transpose()?; + // A role swatch made again (its strokes may still name it) is a change of its own. + let made = (d.swatches.len(), d.unknown.get(ROLES_KEY).cloned()) != before; + let table = RoleTable::of(d); + changed = ids.iter().filter(|id| give_role(d, &table, **id, paint.as_ref(), overprint)).count(); + Ok(changed + usize::from(made)) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "changed": changed, "skipped": skipped })) +} + +fn roles(s: &mut Session, p: &Value) -> Result { + let given = p.get("ids").is_some_and(|v| !v.is_null()); + let roots = checked_ids_or_selection(s, p, ROLES)?; + let d = &s.doc()?.doc; + let (scope, ids) = match (given, roots.is_empty()) { + (true, _) => ("ids", role_targets(d, &roots, false).0), + (false, false) => ("selection", role_targets(d, &roots, false).0), + (false, true) => ("document", document_targets(d)), + }; + let table = RoleTable::of(d); + let mut counts = [0usize; 4]; + for r in ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| table.role_of(n)) { + if let Some(c) = counts.get_mut(r.index()) { + *c += 1; + } + } + let rows: Vec = Role::ALL + .into_iter() + .zip(counts) + .map(|(r, count)| { + let swatch = table.swatch(r); + json!({ "role": r.id(), "name": r.name(), "swatch": swatch, "exists": d.swatch(swatch).is_some(), "count": count }) + }) + .collect(); + Ok(json!({ "roles": rows, "scope": scope, "selected": roots.len() })) +} + +fn set_role_swatch(s: &mut Session, p: &Value) -> Result { + let Some(role) = role_param(p, SET_ROLE_SWATCH, false)? else { return Err(bad(SET_ROLE_SWATCH, "missing `role`")) }; + let name = text_param(p, "swatch", SET_ROLE_SWATCH)?.ok_or_else(|| bad(SET_ROLE_SWATCH, "missing `swatch`"))?; + let d = &s.doc()?.doc; + if let Some(why) = unfit_swatch(d, name) { + return Err(bad(SET_ROLE_SWATCH, why)); + } + let mut table = RoleTable::of(d); + if let Some(other) = Role::ALL.into_iter().find(|r| *r != role && table.swatch(*r) == name) { + return Err(bad(SET_ROLE_SWATCH, format!("`{name}` already carries the {} role", other.name()))); + } + if let Some(slot) = table.0.get_mut(role.index()) { + *slot = name.to_string(); + } + let value = table.to_value(); + let changed = RoleTable::of(d) != table; + if changed { + s.edit("Role Swatches", |d, _| { + d.unknown.insert(ROLES_KEY.to_string(), value); + Ok(()) + })?; + } + Ok(json!({ "role": role.id(), "swatch": name, "changed": changed })) +} diff --git a/crates/engine/src/cmd/addons/packaging/tests.rs b/crates/engine/src/cmd/addons/packaging/tests.rs new file mode 100644 index 0000000000..07a8bd3a30 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/tests.rs @@ -0,0 +1,540 @@ +//! Tests for Packaging Tools: fold line roles, their swatches and the role table. + +use std::collections::BTreeSet; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{AppearanceItem, Node, NodeKind}; + +use crate::*; + +fn session(mode: &str) -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400, "colorMode": mode})).unwrap(); + s +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn rect(s: &mut Session, x: f64) -> NodeId { + id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 20, "width": 40, "height": 40})).unwrap()) +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).cloned().unwrap() +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn set_role(s: &mut Session, p: Value) -> Value { + s.execute("addon.packaging.setRole", &p).unwrap() +} + +fn err(s: &mut Session, cmd: &str, p: Value) -> String { + s.execute(cmd, &p).unwrap_err().to_string() +} + +fn b64(v: &Value) -> Vec { + vectorcraft_format::base64_decode(v["dataBase64"].as_str().expect("dataBase64")).unwrap() +} + +/// The `roles` query's counts, in role order. +fn counts(s: &mut Session, p: Value) -> Vec { + let r = s.execute("addon.packaging.roles", &p).unwrap(); + r["roles"].as_array().unwrap().iter().map(|r| r["count"].as_u64().unwrap()).collect() +} + +#[test] +fn set_role_makes_the_spot_swatch_and_links_the_top_stroke() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + assert!(s.doc().unwrap().doc.swatch("Cut").is_none()); + let before = steps(&s); + let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0))); + assert_eq!(steps(&s), before + 1, "one undo step"); + let d = &s.doc().unwrap().doc; + let sw = d.swatch("Cut").unwrap(); + assert!(sw.global && sw.spot, "{sw:?}"); + assert_eq!(sw.paint, Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)), "100% magenta in a CMYK document"); + let st = node(&s, a).appearance.stroke().cloned().unwrap(); + assert!(matches!(&st.paint, Paint::Solid { swatch: Some(n), tint, .. } if n == "Cut" && *tint == 1.0), "{:?}", st.paint); + assert!(st.overprint, "role strokes overprint by default"); + // Again: nothing changes, and no undo step is recorded. + let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + assert_eq!(r["changed"].as_u64(), Some(0)); + assert_eq!(steps(&s), before + 1); + // Undo takes the swatch away with the role. + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.swatch("Cut").is_none()); +} + +#[test] +fn each_role_gets_its_own_swatch_color_in_the_document_s_mode() { + let mut s = session("rgb"); + for (i, role) in ["cut", "crease", "partialCut", "perforation"].into_iter().enumerate() { + let id = rect(&mut s, 20.0 + 60.0 * i as f64); + set_role(&mut s, json!({"role": role, "ids": [id.0]})); + } + let d = &s.doc().unwrap().doc; + let colors: Vec = ["Cut", "Crease", "Partial Cut", "Perforation"].iter().map(|n| d.swatch(n).unwrap().paint.color().unwrap()).collect(); + assert!(colors.iter().all(|c| matches!(c, Color::Rgb { .. })), "an RGB document's swatches are RGB: {colors:?}"); + assert_eq!(colors.iter().map(|c| c.to_hex()).collect::>().len(), 4, "four colors: {colors:?}"); +} + +#[test] +fn a_path_without_a_stroke_gets_one_and_overprint_can_be_left_off() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + s.edit("strip", |d, _| { + let n = d.node_mut(a).unwrap(); + n.appearance.items.retain(AppearanceItem::is_fill); + Ok(()) + }) + .unwrap(); + assert!(node(&s, a).appearance.stroke().is_none()); + set_role(&mut s, json!({"role": "crease", "ids": [a.0], "overprint": false})); + let st = node(&s, a).appearance.stroke().cloned().unwrap(); + assert_eq!(st.width, 1.0, "a 1 pt stroke"); + assert!(!st.overprint); + assert!(matches!(&st.paint, Paint::Solid { swatch: Some(n), .. } if n == "Crease")); + assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [a.0], "overprint": "yes"})).contains("overprint")); +} + +#[test] +fn none_takes_the_role_away_and_keeps_the_color() { + let mut s = session("cmyk"); + let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0)); + set_role(&mut s, json!({"role": "perforation", "ids": [a.0]})); + let shown = node(&s, a).appearance.stroke().unwrap().paint.color().unwrap(); + let before = steps(&s); + let r = set_role(&mut s, json!({"role": "none", "ids": [a.0, b.0]})); + assert_eq!(r["changed"].as_u64(), Some(1), "the plain rectangle has no role to take away"); + assert_eq!(steps(&s), before + 1); + let st = node(&s, a).appearance.stroke().cloned().unwrap(); + assert_eq!(st.paint, Paint::solid(shown)); + assert!(!st.overprint); + assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [0, 0, 0, 0]); + // Nothing left with a role: no undo step. + set_role(&mut s, json!({"role": "none", "ids": [a.0, b.0]})); + assert_eq!(steps(&s), before + 1); +} + +#[test] +fn bad_roles_and_targets_are_refused() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "fold", "ids": [a.0]})).contains("unknown role")); + assert!(err(&mut s, "addon.packaging.setRole", json!({"ids": [a.0]})).contains("role")); + assert!(err(&mut s, "addon.packaging.setRole", json!({"role": 3, "ids": [a.0]})).contains("role")); + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute("addon.packaging.setRole", &json!({"role": "cut"})).is_err(), "nothing selected"); + let t = id_of(&s.execute("text.create", &json!({"x": 20, "y": 200, "text": "Lid", "size": 20})).unwrap()); + let before = steps(&s); + assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [t.0]})).contains("select a path")); + assert_eq!(steps(&s), before); + assert!(s.doc().unwrap().doc.swatch("Cut").is_none(), "a refused run makes no swatch"); + // Text beside a path is skipped and counted. + let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, t.0]})); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(1))); +} + +#[test] +fn groups_are_walked_and_their_locked_and_hidden_members_left_out() { + let mut s = session("cmyk"); + let (a, b, c) = (rect(&mut s, 20.0), rect(&mut s, 100.0), rect(&mut s, 180.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0, c.0]})).unwrap(); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.edit("lock", |d, _| { + d.node_mut(b).unwrap().locked = true; + d.node_mut(c).unwrap().visible = false; + Ok(()) + }) + .unwrap(); + let r = set_role(&mut s, json!({"role": "crease", "ids": [g.0]})); + assert_eq!(r["ids"], json!([a.0])); + assert_eq!(r["skipped"].as_u64(), Some(2), "the locked and the hidden member"); + assert_eq!(counts(&mut s, json!({"ids": [g.0]})), [0, 1, 0, 0]); + // Named directly, a locked or hidden path is left out too. + let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, b.0, c.0]})); + assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([a.0]), Some(2))); + let before = steps(&s); + assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [b.0]})).contains("locked")); + assert_eq!(steps(&s), before); + assert_eq!(counts(&mut s, json!({"ids": [b.0, c.0]})), [0, 0, 0, 0]); +} + +#[test] +fn a_clip_group_s_clipping_path_is_skipped_and_counted() { + let mut s = session("cmyk"); + let (art, mask) = (rect(&mut s, 20.0), rect(&mut s, 30.0)); + s.execute("select.set", &json!({"ids": [art.0, mask.0]})).unwrap(); + let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap()); + let r = set_role(&mut s, json!({"role": "cut", "ids": [g.0]})); + assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([art.0]), Some(1)), "the clipping path is left out and counted"); +} + +#[test] +fn a_group_and_its_member_count_once_and_locked_lines_count_in_every_scope() { + let mut s = session("cmyk"); + let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0)); + set_role(&mut s, json!({"role": "cut", "ids": [b.0]})); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + let r = set_role(&mut s, json!({"role": "crease", "ids": [g.0, a.0]})); + assert_eq!(r["ids"], json!([a.0, b.0]), "each path once"); + assert_eq!(counts(&mut s, json!({"ids": [g.0, a.0]})), [0, 2, 0, 0]); + set_role(&mut s, json!({"role": "cut", "ids": [b.0]})); + s.edit("lock", |d, _| { + d.node_mut(b).unwrap().locked = true; + Ok(()) + }) + .unwrap(); + // A locked line keeps its role and is counted, whether its group is selected or not. + assert_eq!(counts(&mut s, json!({"ids": [g.0]})), [1, 1, 0, 0]); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(counts(&mut s, json!({})), [1, 1, 0, 0]); +} + +#[test] +fn a_process_swatch_named_like_a_role_swatch_keeps_its_name() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + s.execute("swatch.new", &json!({"name": "Cut", "color": "#ff0000"})).unwrap(); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 2")); + assert!(d.swatch("Cut 2").is_some_and(|w| w.spot), "the role swatch is made beside it"); + assert!(d.swatch("Cut").is_some_and(|w| !w.global), "the process swatch is left as it was"); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]); +} + +#[test] +fn the_free_role_swatch_name_is_searched_past_ten_thousand() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + let taken = std::iter::once("Cut".to_string()).chain((2..10_000).map(|i| format!("Cut {i}"))).chain(["Cut 10004".to_string()]); + let process = |name: String| vectorcraft_color::Swatch { name, paint: Paint::solid(Color::rgb(1.0, 0.0, 0.0)), global: false, spot: false }; + Arc::make_mut(&mut s.doc_mut().unwrap().doc).swatches.extend(taken.map(process)); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 10000")); + assert!(d.swatch("Cut 10000").is_some_and(|w| w.spot), "the role swatch is made under the first free name"); + assert!(d.swatch("Cut 10004").is_some_and(|w| !w.global), "a taken name is left as it was"); +} + +#[test] +fn a_merged_role_swatch_hands_its_role_to_the_kept_swatch() { + let mut s = session("cmyk"); + let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0)); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + set_role(&mut s, json!({"role": "crease", "ids": [b.0]})); + s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap(); + s.execute("swatch.merge", &json!({"names": ["Die", "Cut"]})).unwrap(); + assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die")); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0], "the cut line is still a cut line"); + // A kept swatch that already carries a role keeps it; the merged role's lines take it. + s.execute("swatch.merge", &json!({"names": ["Crease", "Die"]})).unwrap(); + let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap(); + assert_eq!((&table["cut"], &table["crease"]), (&json!("Die"), &json!("Crease")), "{table}"); + assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [0, 2, 0, 0]); + // The next Make Cut Line makes the Cut role's swatch again. + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + assert!(s.doc().unwrap().doc.swatch("Die").is_some_and(|w| w.spot)); + assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [1, 1, 0, 0]); +} + +#[test] +fn a_global_process_swatch_can_carry_a_role() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "global": true})).unwrap(); + s.execute("addon.packaging.setRoleSwatch", &json!({"role": "partialCut", "swatch": "Die"})).unwrap(); + set_role(&mut s, json!({"role": "partialCut", "ids": [a.0]})); + assert!(matches!(&node(&s, a).appearance.stroke().unwrap().paint, Paint::Solid { swatch: Some(n), .. } if n == "Die")); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 1, 0]); +} + +#[test] +fn roles_counts_the_selection_or_the_whole_document() { + let mut s = session("cmyk"); + let (a, b, c) = (rect(&mut s, 20.0), rect(&mut s, 100.0), rect(&mut s, 180.0)); + set_role(&mut s, json!({"role": "cut", "ids": [a.0, b.0]})); + set_role(&mut s, json!({"role": "partialCut", "ids": [c.0]})); + s.execute("select.set", &json!({"ids": [a.0, c.0]})).unwrap(); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + assert_eq!((r["scope"].as_str(), r["selected"].as_u64()), (Some("selection"), Some(2))); + assert_eq!(counts(&mut s, json!({})), [1, 0, 1, 0]); + s.execute("select.none", &json!({})).unwrap(); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + assert_eq!((r["scope"].as_str(), r["selected"].as_u64()), (Some("document"), Some(0))); + assert_eq!(counts(&mut s, json!({})), [2, 0, 1, 0]); + let rows = r["roles"].as_array().unwrap(); + assert_eq!(rows[0], json!({"role": "cut", "name": "Cut", "swatch": "Cut", "exists": true, "count": 2})); + assert_eq!(rows[1]["exists"], json!(false), "no Crease swatch yet"); +} + +#[test] +fn role_swatches_maps_a_role_to_another_swatch() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap(); + let before = steps(&s); + let r = s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap(); + assert_eq!(r["changed"], json!(true)); + assert_eq!(steps(&s), before + 1); + assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die")); + // The old swatch's objects keep their color and lose the role. + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 0, 0]); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + assert!(matches!(&node(&s, a).appearance.stroke().unwrap().paint, Paint::Solid { swatch: Some(n), .. } if n == "Die")); + // The same mapping again changes nothing. + let steps_now = steps(&s); + let r = s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap(); + assert_eq!((r["changed"].clone(), steps(&s)), (json!(false), steps_now)); +} + +#[test] +fn a_renamed_role_swatch_keeps_its_role() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + set_role(&mut s, json!({"role": "crease", "ids": [a.0]})); + s.execute("swatch.edit", &json!({"name": "Crease", "newName": "Score"})).unwrap(); + assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["crease"], json!("Score")); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 1, 0, 0]); + // A swatch that carries no role leaves the table alone. + s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap(); + s.execute("swatch.edit", &json!({"name": "Ink", "newName": "Red Ink"})).unwrap(); + let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap(); + assert_eq!(table, json!({"cut": "Cut", "crease": "Score", "partialCut": "Partial Cut", "perforation": "Perforation"})); + // Undo puts the old name back in the table with the swatch. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.unknown.get("packagingRoles").is_none()); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 1, 0, 0]); +} + +#[test] +fn a_role_swatch_renamed_to_another_role_s_name_leaves_each_role_its_own_swatch() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + // No Crease swatch exists yet, so the name is free for the Cut swatch. + s.execute("swatch.edit", &json!({"name": "Cut", "newName": "Crease"})).unwrap(); + let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap(); + assert_eq!((&table["cut"], &table["crease"]), (&json!("Crease"), &json!("Crease 2")), "{table}"); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0], "the line is still a cut line"); +} + +#[test] +fn a_role_swatch_that_stops_being_global_hands_its_role_to_a_new_swatch() { + let mut s = session("cmyk"); + let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0)); + set_role(&mut s, json!({"role": "perforation", "ids": [a.0]})); + s.execute("swatch.edit", &json!({"name": "Perforation", "spot": false, "global": false})).unwrap(); + assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["perforation"], json!("Perforation 2")); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 0, 0], "the unlinked stroke has no role"); + set_role(&mut s, json!({"role": "perforation", "ids": [b.0]})); + assert!(s.doc().unwrap().doc.swatch("Perforation 2").is_some_and(|w| w.spot)); + assert_eq!(counts(&mut s, json!({"ids": [b.0]})), [0, 0, 0, 1]); +} + +#[test] +fn a_color_group_named_like_a_role_swatch_keeps_its_name() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + s.execute("swatch.newGroup", &json!({"name": "Cut", "colors": ["#ff0000"]})).unwrap(); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 2")); + assert!(d.swatch("Cut 2").is_some_and(|w| w.spot) && d.swatch("Cut").is_none()); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]); +} + +#[test] +fn set_role_makes_a_deleted_role_swatch_again_for_strokes_that_still_name_it() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + s.execute("swatch.delete", &json!({"name": "Cut", "unlink": false})).unwrap(); + assert!(s.doc().unwrap().doc.swatch("Cut").is_none()); + let before = steps(&s); + let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + assert_eq!(r["changed"].as_u64(), Some(0), "the stroke already names the swatch"); + assert!(s.doc().unwrap().doc.swatch("Cut").is_some_and(|w| w.spot), "the swatch is back"); + assert_eq!(steps(&s), before + 1, "as one undo step"); +} + +#[test] +fn a_hidden_stroke_is_shown_when_it_takes_a_role() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + s.edit("hide", |d, _| { + if let Some(AppearanceItem::Stroke(st)) = d.node_mut(a).unwrap().appearance.items.iter_mut().find(|i| !i.is_fill()) { + st.visible = false; + } + Ok(()) + }) + .unwrap(); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + assert!(node(&s, a).appearance.stroke().unwrap().visible); +} + +#[test] +fn role_swatches_refuses_swatches_that_cannot_carry_a_role() { + let mut s = session("cmyk"); + let ramp = json!({"type": "linear", "stops": [{"offset": 0, "color": "#000000"}, {"offset": 1, "color": "#ffffff"}]}); + s.execute("swatch.new", &json!({"name": "Ramp", "gradient": ramp})).unwrap(); + s.execute("swatch.new", &json!({"name": "Plain", "color": "#336699"})).unwrap(); + s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap(); + s.execute("swatch.new", &json!({"name": "Ink Tint", "swatch": "Ink", "tint": 0.5})).unwrap(); + s.execute("swatch.new", &json!({"name": "Crease", "color": {"model": "cmyk", "c": 1, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap(); + let before = steps(&s); + for (swatch, says) in [ + ("Nope", "no swatch"), + ("Ramp", "isn't a color swatch"), + ("Plain", "process color"), + ("Ink Tint", "tint swatch"), + ("[None]", "can't carry a role"), + ("[Registration]", "can't carry a role"), + ("Crease", "already carries the Crease role"), + ] { + let e = err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "cut", "swatch": swatch})); + assert!(e.contains(says), "{swatch}: {e}"); + } + assert!(err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "none", "swatch": "Ink"})).contains("unknown role")); + assert!(err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "cut"})).contains("swatch")); + assert_eq!(steps(&s), before, "no refusal records an undo step"); +} + +#[test] +fn a_damaged_role_table_reads_as_the_defaults() { + let mut s = session("cmyk"); + s.edit("damage", |d, _| { + d.unknown.insert("packagingRoles".into(), json!({"cut": 5, "crease": "", "partialCut": null, "extra": "x"})); + Ok(()) + }) + .unwrap(); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + let swatches: Vec<&str> = r["roles"].as_array().unwrap().iter().map(|r| r["swatch"].as_str().unwrap()).collect(); + assert_eq!(swatches, ["Cut", "Crease", "Partial Cut", "Perforation"]); + s.edit("not an object", |d, _| { + d.unknown.insert("packagingRoles".into(), json!("Cut")); + Ok(()) + }) + .unwrap(); + let a = rect(&mut s, 20.0); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]); + // One swatch named for two roles: the later role takes its own default. + s.edit("duplicate", |d, _| { + d.unknown.insert("packagingRoles".into(), json!({"cut": "Crease", "crease": "Crease", "partialCut": "Cut"})); + Ok(()) + }) + .unwrap(); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + let swatches: Vec<&str> = r["roles"].as_array().unwrap().iter().map(|r| r["swatch"].as_str().unwrap()).collect(); + assert_eq!(swatches, ["Crease", "Crease 2", "Cut", "Perforation"]); + let b = rect(&mut s, 100.0); + set_role(&mut s, json!({"role": "crease", "ids": [b.0]})); + assert_eq!(counts(&mut s, json!({"ids": [b.0]})), [0, 1, 0, 0], "the crease line is a crease line"); +} + +#[test] +fn native_save_and_open_keep_the_role_table_and_the_roles() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap(); + s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap(); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + let saved = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap(); + s.execute("document.open", &json!({"name": "box.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap(); + assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die")); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(counts(&mut s, json!({})), [1, 0, 0, 0]); +} + +/// A document with one rectangle of each of Cut and Crease. +fn two_roles() -> Session { + let mut s = session("cmyk"); + let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0)); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + set_role(&mut s, json!({"role": "crease", "ids": [b.0]})); + s +} + +fn export(s: &mut Session, format: &str) -> String { + String::from_utf8_lossy(&b64(&s.execute("document.export", &json!({"format": format})).unwrap())).into_owned() +} + +#[test] +fn pdf_prints_each_role_on_its_swatch_s_separation_and_overprints_it() { + let mut s = two_roles(); + let c = rect(&mut s, 180.0); + set_role(&mut s, json!({"role": "partialCut", "ids": [c.0]})); + let bytes = vectorcraft_pdf::export( + &s.doc().unwrap().doc, + &vectorcraft_pdf::PdfOptions { created: Some(0), ..vectorcraft_pdf::PdfOptions::uncompressed() }, + ) + .unwrap(); + let pdf = String::from_utf8_lossy(&bytes); + assert!(pdf.contains("/Separation/Cut"), "the Cut line prints on the Cut plate"); + assert!(pdf.contains("/Separation/Crease")); + assert!(pdf.contains("/Separation/Partial#20Cut"), "a name with a space"); + assert!(pdf.contains("/OP true"), "the role strokes overprint"); + // Without overprint, nothing in the file overprints. + let mut plain = session("cmyk"); + let (a, b) = (rect(&mut plain, 20.0), rect(&mut plain, 100.0)); + set_role(&mut plain, json!({"role": "cut", "ids": [a.0], "overprint": false})); + set_role(&mut plain, json!({"role": "crease", "ids": [b.0], "overprint": false})); + let bytes = vectorcraft_pdf::export( + &plain.doc().unwrap().doc, + &vectorcraft_pdf::PdfOptions { created: Some(0), ..vectorcraft_pdf::PdfOptions::uncompressed() }, + ) + .unwrap(); + assert!(!String::from_utf8_lossy(&bytes).contains("/OP true")); + assert!(!export(&mut s, "pdf").is_empty()); +} + +#[test] +fn svg_dxf_and_hpgl_keep_the_default_role_swatches_apart() { + let mut s = two_roles(); + let svg = export(&mut s, "svg"); + let strokes: BTreeSet<&str> = svg.split("stroke=\"").skip(1).filter_map(|t| t.split('"').next()).filter(|c| c.starts_with('#')).collect(); + let strokes = if strokes.is_empty() { + svg.split("stroke:").skip(1).filter_map(|t| t.split([';', '"', '}']).next()).filter(|c| c.starts_with('#')).collect() + } else { + strokes + }; + assert_eq!(strokes.len(), 2, "two stroke colors: {svg}"); + let dxf = export(&mut s, "dxf"); + let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); + // The rectangles' white fills come out as true colors too. + let colors: BTreeSet<&str> = lines.windows(2).filter(|w| w[0] == "420" && w[1] != "16777215").map(|w| w[1]).collect(); + assert_eq!(colors.len(), 2, "two stroke true colors: {colors:?}"); + let plot = s.execute("document.export", &json!({"format": "hpgl", "hpglVersion": "hpgl2"})).unwrap(); + let plot = String::from_utf8_lossy(&b64(&plot)).into_owned(); + assert!(plot.contains("SP1") && plot.contains("SP2"), "a pen per role swatch color: {plot}"); +} + +#[test] +fn compound_paths_carry_a_role() { + let mut s = session("cmyk"); + let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 30.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let c = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + assert!(matches!(node(&s, c).kind, NodeKind::Compound { .. })); + let r = set_role(&mut s, json!({"role": "cut", "ids": [c.0]})); + assert_eq!(r["ids"], json!([c.0])); + assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [1, 0, 0, 0]); + // A member named by id gives its compound the role. + let r = set_role(&mut s, json!({"role": "crease", "ids": [a.0, b.0]})); + assert_eq!((r["ids"].clone(), r["changed"].as_u64()), (json!([c.0]), Some(1))); + assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]); +} diff --git a/crates/engine/src/cmd/addons/pathtools.rs b/crates/engine/src/cmd/addons/pathtools.rs index 8a271557a9..f84fb20f57 100644 --- a/crates/engine/src/cmd/addons/pathtools.rs +++ b/crates/engine/src/cmd/addons/pathtools.rs @@ -3,7 +3,8 @@ //! anchor edits, Split / Add Points at Crossings, Slide Anchor Along Path, the Corner Tool's corners //! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's //! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes, Expand Dashes -//! into Paths and Trim at Crossings ([`trim`]). +//! into Paths, Trim at Crossings ([`trim`]), Common Tangents ([`tangents`]) and Tangent Circle +//! ([`tangent_circle`]). //! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's //! and the UI's. @@ -12,6 +13,8 @@ mod corners; mod effect_tests; mod shape; mod shared_edge; +mod tangent_circle; +mod tangents; #[cfg(test)] mod tests; mod trim; @@ -180,6 +183,8 @@ pub fn specs() -> Vec { v.extend(corners::specs()); v.extend(shared_edge::specs()); v.extend(trim::specs()); + v.extend(tangent_circle::specs()); + v.extend(tangents::specs()); v } diff --git a/crates/engine/src/cmd/addons/pathtools/tangent_circle.rs b/crates/engine/src/cmd/addons/pathtools/tangent_circle.rs new file mode 100644 index 0000000000..379f80905b --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/tangent_circle.rs @@ -0,0 +1,130 @@ +//! Tangent Circle: draw the circles that touch two paths or compound paths at a given radius, or +//! that touch three of them. The geometry is the pathops crate's +//! ([`tangent_circles`](vectorcraft_pathops::addons::pathtools::tangent_circles)). + +use std::collections::HashSet; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, LiveShape, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Affine, FillRule, PathData}; +use vectorcraft_pathops::addons::pathtools::{self as pt, TangentCircleError}; + +use super::super::super::{CommandSpec, bad, checked_ids_or_selection, checked_ids_param, cmd, has_selection, index_opt, number_or}; +use crate::{Result, Session}; + +#[cfg(test)] +mod tests; + +/// The command. +pub(crate) const COMMAND: &str = "addon.pathtools.tangentCircle"; +/// The undo step's name. +const LABEL: &str = "Tangent Circle"; +/// The radius the command takes with two shapes (pt). +const RADIUS: std::ops::RangeInclusive = 0.01..=1e6; + +pub(super) fn specs() -> Vec { + vec![cmd!( + "addon.pathtools.tangentCircle", + "Tangent Circle", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{ids?: [id…] (two or three paths or compound paths; default: the selection), radius?: pt 0.01..1000000 (needed with two shapes; three shapes set the radius themselves and take none), circle?: 0..64 (0: every circle found; n: only the nth, the circles listed by radius, then top to bottom, then left to right)} draw the circles that touch two shapes and have the radius, or that touch three shapes. A circle touches a shape when it meets the shape's outline without crossing it, the whole outline lying outside the circle or inside it: it is tangent to the outline at a smooth point and passes through a corner or an open end; the members of a compound path count as one outline. With three shapes, circles up to 64 times the diagonal of the box around the shapes' anchors and handles are found. Each circle is a new ellipse with the current paint on top of the current layer, or of the isolated group (inside an isolated compound path they join it); the circles are selected; one undo step. Locked and hidden shapes given by `ids` are read and left as they are. No circle is an error, and so are more than 64 (shapes touched along a whole curve, such as two concentric circles), an object named twice, shapes at one point or too small for the radius, and more than 2000 segments in all; the document is then unchanged → {ids, found (how many circles touch the shapes)}", + has_selection, + tangent_circle + )] +} + +/// The paths of path or compound path `id`: itself, or its members. +fn paths_of(d: &Document, id: NodeId) -> Result> { + let value = id.0; + let n = d.node(id).ok_or_else(|| bad(COMMAND, format!("no such object id {value}")))?; + match &n.kind { + NodeKind::Path { path, .. } => Ok(vec![path]), + NodeKind::Compound { children, .. } => Ok(children.iter().filter_map(|c| c.path_data()).collect()), + _ => Err(bad(COMMAND, format!("object {value} is not a path or compound path"))), + } +} + +/// The outlines of `ids`, each path's or compound path's subpaths together; counted before they +/// are copied. +fn outlines(d: &Document, ids: &[NodeId]) -> Result> { + let parts = ids.iter().map(|id| paths_of(d, *id)).collect::>>()?; + let segments: usize = parts.iter().flatten().map(|p| pt::tangent_circle_segments(p)).sum(); + if segments > pt::MAX_TANGENT_CIRCLE_SEGMENTS { + return Err(bad(COMMAND, TOO_COMPLEX)); + } + Ok(parts.iter().map(|paths| PathData::new(paths.iter().flat_map(|p| p.subpaths.iter().cloned()).collect())).collect()) +} + +const TOO_COMPLEX: &str = "the shapes are too complex: at most 2000 segments in all"; + +fn tangent_circle(s: &mut Session, p: &Value) -> Result { + // A repeated id is refused before the ids inside another given one are dropped. + if p.get("ids").is_some_and(|v| !v.is_null()) { + let mut seen = HashSet::new(); + if checked_ids_param(s, p, "ids", COMMAND)?.iter().any(|id| !seen.insert(*id)) { + return Err(bad(COMMAND, "`ids` names an object twice")); + } + } + let ids = checked_ids_or_selection(s, p, COMMAND)?; + let d = &s.doc()?.doc; + if !(2..=3).contains(&ids.len()) { + return Err(bad(COMMAND, "select two or three paths or compound paths")); + } + let outlines = outlines(d, &ids)?; + if outlines.iter().any(|o| o.subpaths.iter().all(|sp| sp.anchors.is_empty())) { + return Err(bad(COMMAND, "a shape has no outline")); + } + let given_radius = p.get("radius").is_some_and(|v| !v.is_null()); + let radius = number_or(p, "radius", 0.0, COMMAND)?; + let radius = match (ids.len(), given_radius) { + (2, true) if RADIUS.contains(&radius) => Some(radius), + (2, true) => return Err(bad(COMMAND, "`radius` must be from 0.01 to 1000000 pt")), + (2, false) => return Err(bad(COMMAND, "two shapes need a `radius`")), + (_, true) => return Err(bad(COMMAND, "three shapes set the radius themselves: leave `radius` out")), + (_, false) => None, + }; + let pick = index_opt(p, "circle", COMMAND)?.unwrap_or(0); + if pick > pt::MAX_TANGENT_CIRCLES { + return Err(bad(COMMAND, "`circle` must be from 0 to 64")); + } + let refs: Vec<&PathData> = outlines.iter().collect(); + let found = pt::tangent_circles(&refs, radius).map_err(|e| match e { + // Every outline has points (checked above): all at one place, or too small for the radius. + TangentCircleError::BadInput => bad(COMMAND, "these shapes are too small to measure"), + // The segments were counted above: the search itself went past its limits. + TangentCircleError::TooComplex => bad(COMMAND, "these shapes take too long to search"), + TangentCircleError::TooMany => bad(COMMAND, "more than 64 circles touch these shapes: they may touch along a whole curve"), + })?; + if found.is_empty() { + return Err(bad(COMMAND, "no circle touches these shapes")); + } + let chosen: Vec = match pick { + 0 => found.clone(), + n => match found.get(n - 1) { + Some(c) => vec![*c], + None => { + let found = found.len(); + return Err(bad(COMMAND, format!("`circle` is past the last circle found ({found})"))); + } + }, + }; + // Path art: inside an isolated compound path, the circles join it and take its appearance. + let parent = s.doc()?.target_parent_for_path()?; + let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); + let ids = s.edit(LABEL, |d, sel| { + let mut ids = vec![]; + for c in &chosen { + let (r, at) = (c.radius, c.center); + let live = LiveShape::Ellipse { w: 2.0 * r, h: 2.0 * r, pie: (0.0, 360.0), xf: Affine::translate((at.x - r, at.y - r)) }; + let kind = NodeKind::Path { path: live.to_path(), rule: FillRule::NonZero, live: Some(Box::new(live)), clipping: false, guide: false }; + let mut n = Node::new(d.alloc_id(), kind); + look.apply(d, &mut n); + ids.push(n.id); + d.insert(parent, usize::MAX, n)?; + } + sel.set(ids.iter().copied()); + Ok(ids) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "found": found.len() })) +} diff --git a/crates/engine/src/cmd/addons/pathtools/tangent_circle/tests.rs b/crates/engine/src/cmd/addons/pathtools/tangent_circle/tests.rs new file mode 100644 index 0000000000..9ffc08df52 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/tangent_circle/tests.rs @@ -0,0 +1,192 @@ +//! Tangent Circle: circles drawn for two shapes and a radius or three shapes, one undo step, the +//! current paint, compound paths, one circle picked, and the errors that leave the document as it was. + +use serde_json::{Value, json}; +use vectorcraft_doc::{LiveShape, NodeId, NodeKind}; +use vectorcraft_geom::Point; + +use super::COMMAND; +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn ellipse(s: &mut Session, x: f64, y: f64, w: f64, h: f64, rotation: f64) -> u64 { + let id = s.execute("shape.ellipse", &json!({"x": x, "y": y, "width": w, "height": h, "rotation": rotation})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.none", &json!({})).unwrap(); + id +} + +fn circle(s: &mut Session, cx: f64, cy: f64, r: f64) -> u64 { + ellipse(s, cx - r, cy - r, 2.0 * r, 2.0 * r, 0.0) +} + +fn undo_steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn count(s: &Session) -> usize { + s.doc().unwrap().doc.layers[0].children().unwrap().len() +} + +/// The circle path `id` is: (center, radius) from its live ellipse. +fn drawn(s: &Session, id: &Value) -> (Point, f64) { + let n = s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap(); + let NodeKind::Path { live: Some(live), .. } = &n.kind else { panic!("not a live shape") }; + let LiveShape::Ellipse { w, h, xf, .. } = live.as_ref() else { panic!("not an ellipse") }; + assert!((w - h).abs() < 1e-9); + (*xf * Point::new(w / 2.0, h / 2.0), w / 2.0) +} + +fn refused(s: &mut Session, p: Value) -> String { + let (steps, objects) = (undo_steps(s), count(s)); + let e = s.execute(COMMAND, &p).unwrap_err().to_string(); + assert_eq!((undo_steps(s), count(s)), (steps, objects), "{p} changed the document"); + e +} + +#[test] +fn two_circles_and_a_radius_draw_every_circle_as_one_step() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 10.0); + let b = circle(&mut s, 130.0, 100.0, 10.0); + s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap(); + let steps = undo_steps(&s); + let r = s.execute(COMMAND, &json!({"ids": [a, b], "radius": 20})).unwrap(); + assert_eq!(r["found"], 6); + let ids = r["ids"].as_array().unwrap().clone(); + assert_eq!(ids.len(), 6); + assert_eq!(undo_steps(&s), steps + 1); + assert_eq!(count(&s), 8); + let st = s.doc().unwrap(); + assert_eq!(st.selection.objects.len(), 6); + let fill = st.doc.node(NodeId(ids[0].as_u64().unwrap())).unwrap().appearance.fill_paint(); + assert_eq!(fill, s.paint.fill); + // Outside both: 30 from each center, at x = 115. + let h = (900.0f64 - 225.0).sqrt(); + let centers: Vec<(Point, f64)> = ids.iter().map(|id| drawn(&s, id)).collect(); + for want in [Point::new(115.0, 100.0 - h), Point::new(115.0, 100.0 + h)] { + // Within the Bézier circles' own error (0.0273% of the radius) of the ideal answer. + assert!(centers.iter().any(|(c, r)| (*c - want).hypot() < 0.02 && (r - 20.0).abs() < 1e-9), "{centers:?}"); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(count(&s), 2); +} + +#[test] +fn three_circles_and_one_picked() { + let mut s = session(); + let ids = [circle(&mut s, 100.0, 100.0, 10.0), circle(&mut s, 180.0, 100.0, 10.0), circle(&mut s, 100.0, 160.0, 10.0)]; + s.execute("select.set", &json!({"ids": ids})).unwrap(); + // The selection: all eight, smallest first; the first is the one outside all three, about the + // circumcenter (140, 130), 50 from each center. + let r = s.execute(COMMAND, &json!({"circle": 1})).unwrap(); + assert_eq!(r["found"], 8); + let one = r["ids"].as_array().unwrap(); + assert_eq!(one.len(), 1); + let (c, radius) = drawn(&s, &one[0]); + assert!((c - Point::new(140.0, 130.0)).hypot() < 0.05 && (radius - 40.0).abs() < 0.05, "{c:?} {radius}"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + assert_eq!(s.execute(COMMAND, &json!({})).unwrap()["ids"].as_array().unwrap().len(), 8); + assert!(refused(&mut s, json!({"ids": ids, "circle": 9})).contains("past the last circle found (8)")); +} + +#[test] +fn compound_rotated_and_locked_shapes() { + let mut s = session(); + // A ring as a compound path, and an ellipse turned 30° inside its hole. + let outer = circle(&mut s, 200.0, 150.0, 80.0); + let inner = circle(&mut s, 200.0, 150.0, 60.0); + s.execute("select.set", &json!({"ids": [outer, inner]})).unwrap(); + let ring = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + let oval = ellipse(&mut s, 180.0, 140.0, 40.0, 20.0, 30.0); + s.execute("select.set", &json!({"ids": [oval]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [ring]})).unwrap(); + s.execute("object.hide", &json!({})).unwrap(); + let r = s.execute(COMMAND, &json!({"ids": [ring, oval], "radius": 22})).unwrap(); + let ids = r["ids"].as_array().unwrap(); + // In the hole, 38 from the center, and 22 from the oval (reaching 42 along its long axis and + // 32 along its short one): two by each end of the oval. + assert_eq!(ids.len(), 4, "{r}"); + for id in ids { + let (c, radius) = drawn(&s, id); + assert!(((c - Point::new(200.0, 150.0)).hypot() - (60.0 - radius)).abs() < 0.05, "{c:?}"); + } + // The locked oval and the hidden ring were read and left as they were. + let d = &s.doc().unwrap().doc; + assert!(d.node(NodeId(oval)).unwrap().locked); + assert!(!d.node(NodeId(ring)).unwrap().visible); +} + +#[test] +fn circles_go_into_an_isolated_group() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 10.0); + let b = circle(&mut s, 130.0, 100.0, 10.0); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.isolate", &json!({"id": group})).unwrap(); + let r = s.execute(COMMAND, &json!({"ids": [a, b], "radius": 5})).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let d = &s.doc().unwrap().doc; + assert_eq!(d.parent_of(id), Some(NodeId(group))); + // On top of the group's art. + assert_eq!(d.node(NodeId(group)).unwrap().children().unwrap().last().map(|n| n.id), Some(id)); +} + +#[test] +fn circles_join_an_isolated_compound_path() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 10.0); + let b = circle(&mut s, 130.0, 100.0, 10.0); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.isolate", &json!({"id": compound})).unwrap(); + let members: Vec = s.doc().unwrap().doc.node(NodeId(compound)).unwrap().children().unwrap().iter().map(|c| c.id.0).collect(); + let r = s.execute(COMMAND, &json!({"ids": members, "radius": 5})).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(NodeId(compound))); + // A compound path and one of its own members are taken as the compound path alone: one shape. + let e = refused(&mut s, json!({"ids": [compound, members[0]], "radius": 5})); + assert!(e.contains("two or three"), "{e}"); + // A repeated member is refused even though the compound path holds it. + let other = circle(&mut s, 300.0, 100.0, 10.0); + let e = refused(&mut s, json!({"ids": [compound, members[0], members[0], other], "radius": 5})); + assert!(e.contains("twice"), "{e}"); +} + +#[test] +fn errors_leave_the_document_unchanged() { + let mut s = session(); + let a = circle(&mut s, 50.0, 50.0, 10.0); + let b = circle(&mut s, 250.0, 50.0, 10.0); + let c = circle(&mut s, 150.0, 200.0, 10.0); + assert!(refused(&mut s, json!({"ids": [a, b], "radius": 5})).contains("no circle touches")); + assert!(refused(&mut s, json!({"ids": [a, b]})).contains("need a `radius`")); + assert!(refused(&mut s, json!({"ids": [a, b, c], "radius": 5})).contains("leave `radius` out")); + assert!(refused(&mut s, json!({"ids": [a, b], "radius": 0})).contains("0.01")); + assert!(refused(&mut s, json!({"ids": [a, b], "radius": "5 mm"})).contains("must be a number")); + assert!(refused(&mut s, json!({"ids": [a], "radius": 5})).contains("two or three")); + assert!(refused(&mut s, json!({"ids": [a, a], "radius": 5})).contains("twice")); + let e = refused(&mut s, json!({"ids": [a, a as f64], "radius": 5})); + assert!(e.contains("not a non-negative integer"), "{e}"); + // Two lone anchors at one place. + let dot = |s: &mut Session| s.execute("path.create", &json!({"anchors": [{"x": 5, "y": 5}]})).unwrap()["id"].as_u64().unwrap(); + let (p, q) = (dot(&mut s), dot(&mut s)); + assert!(refused(&mut s, json!({"ids": [p, q], "radius": 5})).contains("too small to measure")); + assert!(refused(&mut s, json!({"ids": [a, b], "radius": 200, "circle": 65})).contains("from 0 to 64")); + assert!(refused(&mut s, json!({"ids": [a, b], "radius": 200, "circle": -1})).contains("whole number")); + let t = s.execute("text.create", &json!({"x": 10, "y": 280, "text": "Hi"})).unwrap()["id"].as_u64().unwrap(); + assert!(refused(&mut s, json!({"ids": [a, t], "radius": 5})).contains("not a path")); + let anchors: Vec = (0..2002).map(|i| json!({"x": i as f64 * 0.1, "y": 250.0 + (i % 2) as f64})).collect(); + let zigzag = s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap(); + assert!(refused(&mut s, json!({"ids": [a, zigzag], "radius": 5})).contains("at most 2000 segments")); + // Concentric circles touched all the way round. + let inner = circle(&mut s, 50.0, 50.0, 40.0); + assert!(refused(&mut s, json!({"ids": [a, inner], "radius": 15})).contains("whole curve")); +} diff --git a/crates/engine/src/cmd/addons/pathtools/tangents.rs b/crates/engine/src/cmd/addons/pathtools/tangents.rs new file mode 100644 index 0000000000..8102777687 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/tangents.rs @@ -0,0 +1,131 @@ +//! Common Tangents (`addon.pathtools.commonTangents`): the straight lines that touch two selected +//! convex closed paths (ellipses at any rotation and scale, and convex Bézier paths) without +//! crossing into either, added as separate open paths, with the line joining their centers if +//! asked. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`. + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{AppearanceItem, Document, LiveShape, Node, NodeId, NodeKind}; +use vectorcraft_geom::kurbo::Affine; +use vectorcraft_geom::{FillRule, PathData, Point, SubPath}; +use vectorcraft_pathops::addons::pathtools as pt; + +use super::super::super::object::choice; +use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_selection, switch_or}; +use crate::{EngineError, Result, Session}; + +/// The command's id. +pub const COMMON_TANGENTS: &str = "addon.pathtools.commonTangents"; +/// The undo step's name. +const LABEL: &str = "Common Tangents"; +/// The kinds of tangent `tangents` picks. +const KINDS: [&str; 3] = ["external", "internal", "all"]; + +pub(super) fn specs() -> Vec { + vec![cmd!( + "addon.pathtools.commonTangents", + "Common Tangents", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}", + has_selection, + common_tangents + )] +} + +/// The outline of path `id` as the geometry takes it: an exact ellipse for a whole live ellipse, +/// else the path's one closed convex subpath. +fn outline_of(d: &Document, id: NodeId) -> Result { + const C: &str = COMMON_TANGENTS; + let n = d.node(id).ok_or(EngineError::NoNode(id))?; + let NodeKind::Path { path, live, .. } = &n.kind else { return Err(bad(C, "select two closed paths")) }; + let [sp] = path.subpaths.as_slice() else { return Err(bad(C, "select two closed paths")) }; + if let Some(LiveShape::Ellipse { w, h, pie, xf }) = live.as_deref() { + let span = (pie.1 - pie.0).rem_euclid(360.0); + if span < 1e-9 || 360.0 - span < 1e-9 { + let unit = *xf * Affine::new([w / 2.0, 0.0, 0.0, h / 2.0, w / 2.0, h / 2.0]); + return pt::Outline::ellipse(unit).map_err(refusal); + } + } + pt::Outline::convex(sp).map_err(refusal) +} + +fn refusal(e: pt::OutlineError) -> EngineError { + bad( + COMMON_TANGENTS, + match e { + pt::OutlineError::Open => "a selected path is open", + pt::OutlineError::NotConvex => "a selected path is not convex", + pt::OutlineError::Empty => "a selected path has no area", + pt::OutlineError::TooComplex => "a selected path has more than 10000 segments", + }, + ) +} + +fn common_tangents(s: &mut Session, p: &Value) -> Result { + const C: &str = COMMON_TANGENTS; + let kinds = choice(p, C, "tangents", &KINDS)?.unwrap_or("all"); + let centerline = switch_or(p, "centerline", false, C)?; + let roots = checked_ids_or_selection(s, p, C)?; + let d = &s.doc()?.doc; + let ordered = d.paint_order(roots.iter().copied()); + let [first, second] = ordered.as_slice() else { return Err(bad(C, "select two closed paths")) }; + let (a, b) = (outline_of(d, *first)?, outline_of(d, *second)?); + let all = pt::common_tangents(&a, &b).map_err(|_| bad(C, "the two paths have the same outline"))?; + let external = all.iter().filter(|t| t.kind == pt::TangentKind::External).count(); + let keep = |t: &&pt::Tangent| match kinds { + "external" => t.kind == pt::TangentKind::External, + "internal" => t.kind == pt::TangentKind::Internal, + _ => true, + }; + let kept: Vec<&pt::Tangent> = all.iter().filter(keep).collect(); + let count = |kind: pt::TangentKind| kept.iter().filter(|t| t.kind == kind).count(); + let (external_kept, internal_kept) = (count(pt::TangentKind::External), count(pt::TangentKind::Internal)); + let lines: Vec<(Point, Point)> = kept.iter().map(|t| (t.from, t.to)).collect(); + if lines.is_empty() { + // Written as `EngineError::Other` so that the i18n message scan finds them. Exactly one + // external tangent means one path lies inside the other and touches it there; paths that + // overlap without one inside the other have at least two. + let warning = match external { + 0 => EngineError::Other("One path lies inside the other, so they have no common tangents".into()), + 1 => EngineError::Other("One path lies inside the other, so they have no internal tangents".into()), + _ => EngineError::Other("The paths overlap, so they have no internal tangents".into()), + }; + return Ok(json!({ "ids": [], "external": 0, "internal": 0, "centerline": null, "warning": warning.to_string() })); + } + // Centers closer than a billionth of the larger path's size count as one point: no line. + let center = (centerline && (a.center() - b.center()).hypot() > 1e-9 * a.size().max(b.size())).then(|| (a.center(), b.center())); + let fill = Paint::None; + let stroke = if s.paint.stroke.is_none() { Paint::solid(Color::BLACK) } else { s.paint.stroke.clone() }; + let mut look = s.new_art_look(fill, stroke, s.paint.stroke_width.max(0.1)); + // The new art's look may carry more fills than the top one: none of them is kept. + look.appearance.items.retain(|i| !matches!(i, AppearanceItem::Fill(_))); + let top = *second; + let (ids, center_id) = s.edit(LABEL, |d, sel| { + let (parent, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?; + let mut ids = vec![]; + let mut center_id = None; + for (k, (from, to)) in lines.iter().copied().chain(center).enumerate() { + let id = d.alloc_id(); + let path = PathData::single(SubPath::polyline(&[from, to], false)); + let mut n = Node::new(id, NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: false }); + look.apply(d, &mut n); + d.insert(parent, idx + 1 + k, n)?; + if k == lines.len() { + center_id = Some(id); + } + ids.push(id); + } + sel.set(ids.iter().copied()); + Ok((ids, center_id)) + })?; + Ok(json!({ + "ids": ids.iter().map(|i| i.0).collect::>(), + "external": external_kept, + "internal": internal_kept, + "centerline": center_id.map(|i| i.0), + })) +} diff --git a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs new file mode 100644 index 0000000000..aef694bbdd --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs @@ -0,0 +1,278 @@ +//! Common Tangents: the lines for circles, turned ellipses and convex paths, the centerline, +//! the paint, one undo step, the cases with no tangent, and refused selections and params. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{AppearanceItem, NodeId, NodeKind}; +use vectorcraft_geom::{Point, Vec2}; + +use crate::Session; + +const C: &str = super::COMMON_TANGENTS; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + s +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn circle(s: &mut Session, cx: f64, cy: f64, r: f64) -> NodeId { + id_of(&s.execute("shape.ellipse", &json!({"x": cx - r, "y": cy - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +/// The ends of each new line, as `ids` lists them. +fn lines(s: &Session, r: &Value) -> Vec<(Point, Point)> { + let d = &s.doc().unwrap().doc; + r["ids"] + .as_array() + .unwrap() + .iter() + .map(|v| { + let n = d.node(NodeId(v.as_u64().unwrap())).unwrap(); + let NodeKind::Path { path, .. } = &n.kind else { panic!("not a path") }; + assert_eq!(path.subpaths.len(), 1); + let sp = &path.subpaths[0]; + assert!(!sp.closed); + assert_eq!(sp.anchors.len(), 2); + (sp.anchors[0].p, sp.anchors[1].p) + }) + .collect() +} + +fn near(p: Point, q: Point) -> bool { + p.distance(q) < 1e-6 +} + +fn has_line(found: &[(Point, Point)], p: Point, q: Point) -> bool { + found.iter().any(|(a, b)| (near(*a, p) && near(*b, q)) || (near(*a, q) && near(*b, p))) +} + +#[test] +fn two_circles_get_four_tangents_at_the_exact_points_as_one_undo_step() { + let mut s = session(); + let a = circle(&mut s, 100.0, 200.0, 20.0); + let b = circle(&mut s, 300.0, 200.0, 40.0); + select(&mut s, &[a, b]); + let before = steps(&s); + let r = s.execute(C, &json!({})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64(), r["centerline"].is_null()), (Some(2), Some(2), true), "{r}"); + assert_eq!(steps(&s), before + 1); + let found = lines(&s, &r); + assert_eq!(found.len(), 4); + let (c1, c2) = (Point::new(100.0, 200.0), Point::new(300.0, 200.0)); + // External: (c1 - c2) · n = r2 - r1, n.x = -0.1; internal: (c1 - c2) · n = -(r1 + r2), n.x = 0.3. + for (nx, external) in [(-0.1f64, true), (0.3, false)] { + for sy in [1.0, -1.0] { + let n = Vec2::new(nx, sy * (1.0 - nx * nx).sqrt()); + let far = if external { c2 + n * 40.0 } else { c2 - n * 40.0 }; + assert!(has_line(&found, c1 + n * 20.0, far), "{n:?} in {found:?}"); + } + } + // The lines are the selection, above the two circles. + let st = s.doc().unwrap(); + assert_eq!(st.selection.objects.len(), 4); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect(); + let order = st.doc.paint_order([a, b].into_iter().chain(ids.iter().copied())); + assert_eq!(&order[..2], &[a, b]); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(ids.iter().all(|id| s.doc().unwrap().doc.node(*id).is_none()), "one undo step removes them all"); +} + +#[test] +fn turned_ellipses_are_measured_exactly() { + let mut s = session(); + let a = id_of(&s.execute("shape.ellipse", &json!({"x": 60, "y": 170, "width": 80, "height": 30})).unwrap()); + select(&mut s, &[a]); + s.execute("object.rotate", &json!({"angle": 30, "origin": [100, 185]})).unwrap(); + let b = id_of(&s.execute("shape.ellipse", &json!({"x": 330, "y": 120, "width": 50, "height": 120})).unwrap()); + select(&mut s, &[b]); + s.execute("object.rotate", &json!({"angle": -70, "origin": [355, 180]})).unwrap(); + select(&mut s, &[a, b]); + let r = s.execute(C, &json!({"tangents": "all"})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(2)), "{r}"); + // Each end lies on its ellipse, where the ellipse runs along the line: turned back about the + // center, (x/rx)² + (y/ry)² = 1 and the gradient is square to the line. + let on = |p: Point, center: Point, rx: f64, ry: f64, deg: f64, dir: Vec2| { + let turn = vectorcraft_geom::kurbo::Affine::rotate(-deg.to_radians()); + // `object.rotate` turns counter-clockwise on the page (y down): undo it in page terms. + let page = |v: Vec2| Vec2::new(v.x, -v.y); + let q = page((turn * page(p - center).to_point()).to_vec2()); + let d = page((turn * page(dir).to_point()).to_vec2()); + let value = (q.x / rx).powi(2) + (q.y / ry).powi(2); + let grad = Vec2::new(q.x / (rx * rx), q.y / (ry * ry)); + (value - 1.0).abs() < 1e-9 && (grad.dot(d) / (grad.hypot() * d.hypot())).abs() < 1e-7 + }; + for (p, q) in lines(&s, &r) { + let dir = q - p; + assert!(on(p, Point::new(100.0, 185.0), 40.0, 15.0, 30.0, dir), "{p:?} on the first ellipse"); + assert!(on(q, Point::new(355.0, 180.0), 25.0, 60.0, -70.0, dir), "{q:?} on the second ellipse"); + } +} + +#[test] +fn a_convex_bezier_path_and_the_centerline() { + let mut s = session(); + let anchors = json!([ + {"x": 0, "y": 40, "in": [0, 70], "out": [0, 10]}, + {"x": 50, "y": 0, "in": [20, 0], "out": [90, 0]}, + {"x": 110, "y": 50, "in": [110, 20], "out": [110, 90]}, + {"x": 40, "y": 100, "in": [80, 100], "out": [10, 100]} + ]); + let blob = id_of(&s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap()); + let round = circle(&mut s, 300.0, 200.0, 30.0); + let r = s.execute(C, &json!({"ids": [blob.0, round.0], "centerline": true})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(2)), "{r}"); + let found = lines(&s, &r); + assert_eq!(found.len(), 5, "four tangents and the centerline"); + // The centerline is the last line and its id is given: from the blob's center of area to the + // circle's center. + assert_eq!(r["centerline"], r["ids"][4]); + let (from, to) = found[4]; + assert!(near(to, Point::new(300.0, 200.0)), "{to:?}"); + assert!(from.x > 30.0 && from.x < 80.0 && from.y > 30.0 && from.y < 70.0, "{from:?}"); + // A tangent touches without crossing: every point of both paths is on one side of it. + let d = &s.doc().unwrap().doc; + let points = |id: NodeId| { + let sp = d.node(id).unwrap().path_data().unwrap().subpaths[0].clone(); + let segments: Vec<_> = (0..sp.segment_count()).map(|k| sp.segment(k)).collect(); + segments.iter().flat_map(|seg| (0..200).map(|j| vectorcraft_geom::kurbo::ParamCurve::eval(seg, j as f64 / 200.0))).collect::>() + }; + let (pa, pb) = (points(blob), points(round)); + for (p, q) in &found[..4] { + let n = Vec2::new(-(q.y - p.y), q.x - p.x).normalize(); + for pts in [&pa, &pb] { + let side: Vec = pts.iter().map(|x| (*x - *p).dot(n)).collect(); + let (lo, hi) = side.iter().fold((f64::MAX, f64::MIN), |(lo, hi), v| (lo.min(*v), hi.max(*v))); + // The circle is measured as an exact circle, which its four curves follow to within + // about 0.03% of the radius. + assert!(lo > -1e-2 || hi < 1e-2, "crosses: {lo} .. {hi}"); + } + } +} + +#[test] +fn tiny_paths_close_together_still_get_the_centerline() { + // Two circles a ten-billionth of a point wide, half a billionth apart: separate, with all four + // tangents, and centers apart by far more than their sizes' rounding. + let mut s = session(); + let a = circle(&mut s, 1.0, 1.0, 1e-10); + let b = circle(&mut s, 1.0 + 5e-10, 1.0, 1e-10); + let r = s.execute(C, &json!({"ids": [a.0, b.0], "centerline": true})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(2)), "{r}"); + assert_eq!(r["ids"].as_array().map(Vec::len), Some(5), "{r}"); + assert_eq!(r["centerline"], r["ids"][4]); +} + +#[test] +fn the_lines_take_the_current_stroke_and_no_fill() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 300.0, 100.0, 20.0); + s.execute("select.none", &json!({})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + let r = s.execute(C, &json!({"ids": [a.0, b.0], "tangents": "external"})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}"); + let d = &s.doc().unwrap().doc; + for v in r["ids"].as_array().unwrap() { + let n = d.node(NodeId(v.as_u64().unwrap())).unwrap(); + assert!(n.appearance.fill().is_none_or(|f| f.paint.is_none()), "no fill"); + let st = n.appearance.stroke().expect("stroked"); + assert!(!st.paint.is_none(), "black when the stroke is None"); + } + // A new-art appearance with two fills and a stroke: the lines keep the stroke and neither fill. + let mut look = vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 2.0); + let fill = look.items.iter().find(|i| matches!(i, AppearanceItem::Fill(_))).cloned().unwrap(); + look.items.push(fill); + s.paint.appearance = Some(look); + s.paint.inherited = false; + let r2 = s.execute(C, &json!({"ids": [a.0, b.0], "tangents": "external"})).unwrap(); + let d2 = &s.doc().unwrap().doc; + for v in r2["ids"].as_array().unwrap() { + let n = d2.node(NodeId(v.as_u64().unwrap())).unwrap(); + assert!(!n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(_))), "no fill at all"); + assert!(n.appearance.stroke().is_some()); + } + // Two equal circles: the external tangents run along their tops and bottoms. + assert!(has_line(&lines(&s, &r), Point::new(100.0, 80.0), Point::new(300.0, 80.0))); + assert!(has_line(&lines(&s, &r), Point::new(100.0, 120.0), Point::new(300.0, 120.0))); +} + +#[test] +fn nested_and_overlapping_paths_change_nothing_and_say_why() { + let mut s = session(); + let big = circle(&mut s, 200.0, 200.0, 100.0); + let small = circle(&mut s, 220.0, 200.0, 20.0); + let before = (steps(&s), s.doc().unwrap().doc.node_count()); + let r = s.execute(C, &json!({"ids": [big.0, small.0]})).unwrap(); + assert_eq!(r["ids"], json!([])); + assert!(r["warning"].as_str().unwrap().contains("inside the other"), "{r}"); + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes"); + // Overlapping circles have external tangents only. + let a = circle(&mut s, 100.0, 100.0, 30.0); + let b = circle(&mut s, 140.0, 100.0, 30.0); + let before = (steps(&s), s.doc().unwrap().doc.node_count()); + let r = s.execute(C, &json!({"ids": [a.0, b.0], "tangents": "internal"})).unwrap(); + assert!(r["warning"].as_str().unwrap().contains("overlap"), "{r}"); + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before); + let r = s.execute(C, &json!({"ids": [a.0, b.0]})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}"); + // Circles that touch share the tangent where they touch. + let c = circle(&mut s, 100.0, 300.0, 10.0); + let e = circle(&mut s, 130.0, 300.0, 20.0); + let r = s.execute(C, &json!({"ids": [c.0, e.0], "tangents": "internal"})).unwrap(); + assert_eq!(r["internal"].as_u64(), Some(1), "{r}"); + let (p, q) = lines(&s, &r)[0]; + assert!((p.x - 110.0).abs() < 1e-5 && (q.x - 110.0).abs() < 1e-5 && (p.distance(q) - 20.0).abs() < 1e-5, "{p:?} {q:?}"); + // A circle touching the inside of a larger one: no internal tangent, and the message says the + // one lies inside the other rather than that they overlap. + let outer = circle(&mut s, 400.0, 200.0, 50.0); + let inner = circle(&mut s, 430.0, 200.0, 20.0); + let before = (steps(&s), s.doc().unwrap().doc.node_count()); + let r = s.execute(C, &json!({"ids": [outer.0, inner.0], "tangents": "internal"})).unwrap(); + assert_eq!(r["ids"], json!([])); + assert!(r["warning"].as_str().unwrap().contains("inside the other, so they have no internal"), "{r}"); + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before); + let r = s.execute(C, &json!({"ids": [outer.0, inner.0]})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(1), Some(0)), "{r}"); +} + +#[test] +fn bad_selections_and_params_are_refused() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 300.0, 100.0, 20.0); + let star = id_of(&s.execute("shape.star", &json!({"cx": 200, "cy": 300, "radius1": 40, "radius2": 15, "points": 5})).unwrap()); + let open = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 50, "y": 0}, {"x": 50, "y": 50}]})).unwrap()); + let group_of = |s: &mut Session, ids: &[NodeId]| { + select(s, ids); + id_of(&s.execute("object.group", &json!({})).unwrap()) + }; + let before = (steps(&s), s.doc().unwrap().doc.node_count()); + let err = |s: &mut Session, p: Value| s.execute(C, &p).unwrap_err().to_string(); + assert!(err(&mut s, json!({"ids": [a.0, b.0], "tangents": "both"})).contains("tangents")); + assert!(err(&mut s, json!({"ids": [a.0, b.0], "tangents": 3})).contains("tangents")); + assert!(err(&mut s, json!({"ids": [a.0, b.0], "centerline": "yes"})).contains("centerline")); + assert!(err(&mut s, json!({"ids": [a.0, b.0], "which": "all"})).contains("which"), "unknown keys are refused"); + assert!(err(&mut s, json!({"ids": [a.0]})).contains("select two closed paths")); + assert!(err(&mut s, json!({"ids": [a.0, b.0, star.0]})).contains("select two closed paths")); + assert!(err(&mut s, json!({"ids": [a.0, star.0]})).contains("not convex")); + assert!(err(&mut s, json!({"ids": [a.0, open.0]})).contains("open")); + assert!(s.execute(C, &json!({"ids": [a.0, a.0]})).is_err(), "the same path twice"); + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes"); + let copy = id_of(&s.execute("shape.ellipse", &json!({"x": 80, "y": 80, "width": 40, "height": 40})).unwrap()); + assert!(err(&mut s, json!({"ids": [a.0, copy.0]})).contains("same outline")); + let g = group_of(&mut s, &[b]); + assert!(err(&mut s, json!({"ids": [a.0, g.0]})).contains("select two closed paths")); +} diff --git a/crates/engine/src/cmd/addons/pathtools/trim.rs b/crates/engine/src/cmd/addons/pathtools/trim.rs index 134edc6607..f1ffab9ba0 100644 --- a/crates/engine/src/cmd/addons/pathtools/trim.rs +++ b/crates/engine/src/cmd/addons/pathtools/trim.rs @@ -1,15 +1,13 @@ //! Trim at Crossings: remove the stretch of a path between the places where other paths, or the //! path itself, cross it. The command takes the stretch at a point, every stretch a rectangle //! touches, or every stretch a line through some points crosses. It works on every path that can -//! be edited, selected or not. - -use std::collections::HashSet; +//! be edited, selected or not. What it removes is worked out by +//! [`vectorcraft_tools::addons::trim::plan`], which the tool also uses to show it beforehand. use serde_json::{Value, json}; -use vectorcraft_doc::{Document, NodeId, NodeKind}; -use vectorcraft_geom::kurbo::{Line, PathSeg}; -use vectorcraft_geom::{PathData, Point, Rect, SubPath, hit}; -use vectorcraft_pathops::addons::pathtools as pt; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_geom::{Point, Rect}; +use vectorcraft_tools::addons::trim::plan::{self, Limits, Pick, Stretches}; use super::super::super::draw2::replace_with_pieces; use super::super::super::pathops::Beside; @@ -41,16 +39,6 @@ pub(super) fn specs() -> Vec { )] } -/// What picks the stretches to remove. -enum Pick { - /// The stretch of the nearest path within the tolerance of the point. - At(Point, f64), - /// Every stretch the rectangle touches. - Rect(Rect), - /// Every stretch the line through the points crosses. - Line(Vec, Rect), -} - fn pick(p: &Value) -> Result { const C: &str = "addon.pathtools.trim"; let given = |key: &str| p.get(key).filter(|v| !v.is_null()); @@ -89,194 +77,15 @@ fn pick(p: &Value) -> Result { } } -/// A path that takes part: its id, geometry and control-point box. -type Part<'a> = (NodeId, &'a PathData, Rect); - -/// The paths that take part, bottom to top: the ones that can be edited, without guides and -/// clipping paths. The clipping path of a clip group or a clipped layer is left out whole, the -/// members of a compound clipping path included. -fn parts(d: &Document) -> Vec> { - let editable = d.editable(); - let mut masks = HashSet::new(); - d.walk(|n| { - if n.clips() - && let Some(first) = n.children().and_then(|c| c.first()) - { - first.walk(&mut |m| { - masks.insert(m.id); - }); - } - }); - let mut out = vec![]; - d.walk(|n| { - if let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind - && !masks.contains(&n.id) - && let Some(b) = path.control_bounds() - && editable(n.id) - { - out.push((n.id, path, b)); - } - }); - out -} - -/// Most box tests one command makes between a line's pieces and the paths' segments. -const MAX_LINE_TESTS: usize = 60_000_000; -/// Most tests one command makes between the boxes of the paths to trim and of the other paths. -const MAX_BOX_TESTS: usize = 50_000_000; - -/// Does the line through `pts` cross `sp`? Each piece of the line compared costs one of `budget`; -/// `None` once it is spent. -fn crossed_by_line(sp: &SubPath, pts: &[Point], budget: &mut usize) -> Option { - let segs: Vec<_> = (0..sp.segment_count()) - .map(|i| { - let c = sp.segment(i); - (c, Rect::from_points(c.p0, c.p1).union_pt(c.p2).union_pt(c.p3).inflate(1e-9, 1e-9)) - }) - .collect(); - let Some(reach) = segs.iter().map(|s| s.1).reduce(|a, b| a.union(b)) else { return Some(false) }; - for w in pts.windows(2) { - let [a, b] = w else { continue }; - let piece = Rect::from_points(*a, *b); - *budget = budget.checked_sub(1)?; - if !reach.overlaps(piece) { - continue; - } - for (c, r) in &segs { - *budget = budget.checked_sub(1)?; - if r.overlaps(piece) && !PathSeg::Cubic(*c).intersect_line(Line::new(*a, *b)).is_empty() { - return Some(true); - } - } - } - Some(false) -} - -/// Does the rectangle or line of `pick` touch the outline of `piece`? Never for `Pick::At`. -fn touches(piece: &SubPath, pick: &Pick, budget: &mut usize) -> Result { - match pick { - Pick::At(..) => Ok(false), - Pick::Rect(r) => Ok(hit::intersects_rect(&PathData::single(piece.clone()), *r)), - Pick::Line(pts, _) => crossed_by_line(piece, pts, budget) - .ok_or_else(|| bad("addon.pathtools.trim", "the line is too long, or the paths it passes too many, to check")), - } -} - -/// `path` without the stretches `pick` takes (`on`: the place of `Pick::At` on it): its subpaths -/// then, and how many stretches went. `None` when none does. A rectangle or a line that touches no -/// part of `path` leaves it out before its crossings are looked for. -fn trimmed( - path: &PathData, - others: &[&PathData], - pick: &Pick, - on: Option, - budget: &mut usize, - work: &mut pt::Work, -) -> Result, usize)>> { - const C: &str = "addon.pathtools.trim"; - let reached = match pick { - Pick::At(..) => true, - Pick::Rect(r) => hit::intersects_rect(path, *r), - Pick::Line(..) => { - let mut any = false; - for sp in &path.subpaths { - if touches(sp, pick, budget)? { - any = true; - break; - } - } - any - } - }; - if !reached { - return Ok(None); - } - let places = - pt::crossings_on_within(path, others, work).ok_or_else(|| bad(C, "the paths are too many or too tangled to find where they cross"))?; - let mut subs = vec![]; - let mut removed = 0; - for (si, sp) in path.subpaths.iter().enumerate() { - // The places come in subpath order: this subpath's are one run of them. - let run = places.partition_point(|p| p.0 < si)..places.partition_point(|p| p.0 <= si); - let here: Vec<(usize, f64)> = places.get(run).unwrap_or_default().iter().map(|&(_, seg, t)| (seg, t)).collect(); - let spans = pt::spans(sp, &here); - let marks: Vec = match pick { - Pick::At(..) => { - let at = on.filter(|(s, ..)| *s == si).and_then(|(_, seg, t)| pt::span_at(sp, &spans, seg, t)); - (0..spans.len()).map(|i| Some(i) == at).collect() - } - _ => spans.iter().map(|s| touches(&pt::slice(sp, *s), pick, budget)).collect::>()?, - }; - match pt::without_spans(sp, &spans, &marks) { - Some(pieces) => { - removed += marks.iter().filter(|m| **m).count(); - subs.extend(pieces); - } - None => subs.push(sp.clone()), - } - } - Ok((removed > 0).then_some((subs, removed))) -} - fn trim(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.pathtools.trim"; let pick = pick(p)?; let st = s.doc()?; - let d = &st.doc; - let parts = parts(d); // In isolation mode only the isolated object's paths are trimmed; paths outside it still cross them. let root = crate::cmd::ordinary_isolation(st); - let in_scope = |id: NodeId| root.is_none_or(|r| id == r || crate::cmd::inside_isolation(d, r, id)); - // The paths to trim, each with the place `at` falls on. - let targets: Vec<(usize, Option)> = match &pick { - Pick::At(at, tolerance) => { - let mut best: Option<(usize, pt::Place, f64)> = None; - for (i, (id, path, b)) in parts.iter().enumerate() { - if !in_scope(*id) { - continue; - } - let b = b.inflate(*tolerance, *tolerance); - if !(b.x0 <= at.x && at.x <= b.x1 && b.y0 <= at.y && at.y <= b.y1) { - continue; - } - // Of paths equally near, the one on top. - if let Some((si, seg, t, _, dist)) = path.nearest(*at) - && dist <= *tolerance - && best.is_none_or(|b| dist <= b.2) - { - best = Some((i, (si, seg, t), dist)); - } - } - best.map(|(i, on, _)| (i, Some(on))).into_iter().collect() - } - Pick::Rect(r) | Pick::Line(_, r) => { - parts.iter().enumerate().filter(|(_, (id, _, b))| in_scope(*id) && b.overlaps(*r)).map(|(i, _)| (i, None)).collect() - } - }; - // Each path to trim has its box tested against every other path's. - if targets.len().saturating_mul(parts.len()) > MAX_BOX_TESTS { - return Err(bad(C, "the rectangle or line reaches too many paths to check")); - } - let mut plan: Vec<(NodeId, Vec)> = vec![]; - let mut removed = 0; - let mut budget = MAX_LINE_TESTS; - // One budget of crossing work for every path the command trims. - let mut work = pt::Work::default(); - for (i, on) in targets { - let Some((id, path, b)) = parts.get(i) else { continue }; - let reach = b.inflate(1e-3, 1e-3); - let others: Vec<&PathData> = - parts.iter().enumerate().filter(|(j, (_, _, ob))| *j != i && reach.overlaps(*ob)).map(|(_, (_, o, _))| *o).collect(); - let Some((subs, n)) = trimmed(path, &others, &pick, on, &mut budget, &mut work)? else { continue }; - removed += n; - // A path of one subpath becomes a path per piece; the pieces of one with more stay its subpaths. - let pieces = match (path.subpaths.len(), subs.is_empty()) { - (_, true) => vec![], - (1, false) => subs.into_iter().map(PathData::single).collect(), - _ => vec![PathData::new(subs)], - }; - plan.push((*id, pieces)); - } + let trimmed = plan::plan(&st.doc, root, &pick, Limits::COMMAND, &mut Stretches::default()).map_err(|e| bad(C, e.message()))?; + let removed: usize = trimmed.iter().map(|t| t.count).sum(); + let plan: Vec<(NodeId, Vec<_>)> = trimmed.into_iter().map(|t| (t.id, t.pieces)).collect(); if plan.is_empty() { return Ok(json!({ "ids": [], "removed": 0 })); } diff --git a/crates/engine/src/cmd/addons/pathtools/trim/tests.rs b/crates/engine/src/cmd/addons/pathtools/trim/tests.rs index 42adb70ab9..a36c705e4f 100644 --- a/crates/engine/src/cmd/addons/pathtools/trim/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/trim/tests.rs @@ -480,6 +480,129 @@ fn the_tool_trims_on_release_as_one_step_and_escape_drops_a_drag() { assert_eq!(steps(&s), n + 2); } +/// The ends of each red path the tool shows. +fn highlighted(s: &mut Session, view: crate::ViewInfo) -> Vec<(Point, Point)> { + use vectorcraft_geom::kurbo::ParamCurve; + s.overlays(view) + .into_iter() + .filter_map(|o| match o { + vectorcraft_tools::Overlay::Path { path, color, .. } if color == vectorcraft_tools::builder::HIGHLIGHT_RED => { + let segs: Vec<_> = path.segments().collect(); + Some((segs.first()?.start(), segs.last()?.end())) + } + _ => None, + }) + .collect() +} + +#[test] +fn hovering_with_the_tool_shows_the_stretch_its_click_removes() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let mut s = session(); + let (h, _, _) = across_and_uprights(&mut s); + let hidden = line(&mut s, &[(0.0, 200.0), (300.0, 200.0)], false); + set_flags(&mut s, hidden, false, false); + let view = crate::ViewInfo { smart_guides: false, ..crate::ViewInfo::default() }; + s.select_tool("trimAtCrossings", view).unwrap(); + let n = steps(&s); + // Over the middle of the line across: the stretch between the uprights, and nothing changes. + s.pointer(&PointerEvent::new(PointerKind::Move, 150.0, 101.0), view).unwrap(); + let shown = highlighted(&mut s, view); + assert!(matches!(shown.as_slice(), [(a, b)] if near(*a, 100.0, 100.0) && near(*b, 200.0, 100.0)), "{shown:?}"); + assert_eq!(steps(&s), n); + // Over the hidden path and over empty canvas: nothing. + s.pointer(&PointerEvent::new(PointerKind::Move, 150.0, 200.0), view).unwrap(); + assert!(highlighted(&mut s, view).is_empty()); + s.pointer(&PointerEvent::new(PointerKind::Move, 150.0, 250.0), view).unwrap(); + assert!(highlighted(&mut s, view).is_empty()); + // A click where the stretch was shown removes exactly it: the line keeps 0 to 100 and 200 to 300. + s.pointer(&PointerEvent::new(PointerKind::Move, 150.0, 101.0), view).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 101.0), view).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 101.0), view).unwrap(); + assert_eq!(steps(&s), n + 1); + assert!(near(ends(&s, h).0, 0.0, 100.0) && near(ends(&s, h).1, 100.0, 100.0)); + let rest = stack(&s).into_iter().find(|id| *id != h && path(&s, *id).subpaths.len() == 1 && near(ends(&s, *id).0, 200.0, 100.0)); + assert!(rest.is_some_and(|id| near(ends(&s, id).1, 300.0, 100.0))); + assert!(highlighted(&mut s, view).is_empty(), "the edit drops the highlight"); +} + +/// The red paths the tool shows. +fn red(s: &mut Session, view: crate::ViewInfo) -> Vec { + s.overlays(view) + .into_iter() + .filter_map(|o| match o { + vectorcraft_tools::Overlay::Path { path, color, .. } if color == vectorcraft_tools::builder::HIGHLIGHT_RED => Some(path), + _ => None, + }) + .collect() +} + +/// The length of every path in the first layer. +fn total_length(s: &Session) -> f64 { + use vectorcraft_geom::kurbo::ParamCurveArclen; + stack(s).into_iter().flat_map(|id| path(s, id).to_bezpath().segments().collect::>()).map(|seg| seg.arclen(1e-9)).sum() +} + +/// `act` removes exactly the red paths shown before it: the paths lose their length, and nothing +/// is left on the middle of any of them. +fn removes_what_was_shown(s: &mut Session, view: crate::ViewInfo, act: &dyn Fn(&mut Session)) { + use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen}; + let shown = red(s, view); + assert!(!shown.is_empty()); + let shown_length: f64 = shown.iter().flat_map(|p| p.segments().collect::>()).map(|seg| seg.arclen(1e-9)).sum(); + let before = total_length(s); + act(s); + assert!((before - total_length(s) - shown_length).abs() < 1e-3, "{before} - {} != {shown_length}", total_length(s)); + for p in &shown { + let segs: Vec<_> = p.segments().collect(); + let mid = segs[segs.len() / 2].eval(if segs.len() % 2 == 1 { 0.5 } else { 0.0 }); + let left = stack(s).into_iter().filter_map(|id| path(s, id).nearest(mid)).map(|n| n.4).fold(f64::INFINITY, f64::min); + assert!(left > 0.5, "a path is left at {mid:?}"); + } +} + +#[test] +fn what_the_tool_shows_before_a_click_or_a_release_is_what_the_command_removes() { + use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; + let view = crate::ViewInfo { smart_guides: false, ..crate::ViewInfo::default() }; + let ev = |kind, x, y| PointerEvent::new(kind, x, y); + let alt = Mods { alt: true, ..Mods::default() }; + let setup = || { + let mut s = session(); + s.execute("shape.ellipse", &json!({"x": 100, "y": 50, "width": 200, "height": 100})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + line(&mut s, &[(50.0, 100.0), (350.0, 100.0)], false); + // A Z whose first and last sides cross. + line(&mut s, &[(0.0, 160.0), (100.0, 260.0), (100.0, 160.0), (0.0, 260.0)], false); + s.select_tool("trimAtCrossings", view).unwrap(); + s + }; + // A click on the ellipse's top, on the line inside it and on the Z's loop. + for (x, y) in [(200.0, 51.0), (200.0, 101.0), (101.0, 210.0)] { + let mut s = setup(); + s.pointer(&ev(PointerKind::Move, x, y), view).unwrap(); + removes_what_was_shown(&mut s, view, &|s| { + s.pointer(&ev(PointerKind::Down, x, y), view).unwrap(); + s.pointer(&ev(PointerKind::Up, x, y), view).unwrap(); + }); + } + // A rectangle over the ellipse's left side and the line. + let mut s = setup(); + s.pointer(&ev(PointerKind::Down, 90.0, 90.0), view).unwrap(); + s.pointer(&ev(PointerKind::Drag, 120.0, 110.0), view).unwrap(); + removes_what_was_shown(&mut s, view, &|s| { + s.pointer(&ev(PointerKind::Up, 120.0, 110.0), view).unwrap(); + }); + // An Alt line through the ellipse's bottom and the Z's tail. + let mut s = setup(); + s.pointer(&ev(PointerKind::Down, 200.0, 140.0).with_mods(alt), view).unwrap(); + s.pointer(&ev(PointerKind::Drag, 200.0, 170.0).with_mods(alt), view).unwrap(); + s.pointer(&ev(PointerKind::Drag, 10.0, 250.0).with_mods(alt), view).unwrap(); + removes_what_was_shown(&mut s, view, &|s| { + s.pointer(&ev(PointerKind::Up, 10.0, 250.0).with_mods(alt), view).unwrap(); + }); +} + #[test] fn a_line_too_long_to_check_against_the_paths_is_refused() { let mut s = session(); diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 256e585923..84596eb53c 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Add New Fill", ["Window", "Appearance"], Some("Cmd+/"), - "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind", + "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)", has_doc, |s, p| add_item(s, p, true) ), @@ -57,7 +57,7 @@ pub fn specs() -> Vec { "Add New Stroke", ["Window", "Appearance"], Some("Cmd+Alt+/"), - "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind", + "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)", has_doc, |s, p| add_item(s, p, false) ), @@ -66,7 +66,7 @@ pub fn specs() -> Vec { "Clear Appearance", ["Window", "Appearance"], None, - "{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind", + "{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", has_doc, clear_appearance ), @@ -75,7 +75,7 @@ pub fn specs() -> Vec { "Reduce to Basic Appearance", ["Window", "Appearance"], None, - "{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind", + "{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)", has_doc, reduce_basic ), @@ -84,7 +84,7 @@ pub fn specs() -> Vec { "Appearance Item", [], None, - "{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind", + "{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; when their rows differ, `index` needs `aligned` and is a row of the backmost one), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the paint, weight, opacity and blend mode it writes to the line's topmost visible row)", has_doc, set_item ), @@ -93,7 +93,7 @@ pub fn specs() -> Vec { "Remove Item", [], None, - "{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind", + "{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; when their rows differ, the indices need `aligned` and are rows of the backmost one), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)", has_doc, remove_item ), @@ -111,7 +111,7 @@ pub fn specs() -> Vec { "Duplicate Item", ["Window", "Appearance"], None, - "{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind", + "{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; when their rows differ, the indices need `aligned` and are rows of the backmost one), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)", has_doc, duplicate_item ), @@ -120,7 +120,7 @@ pub fn specs() -> Vec { "Reorder Appearance Item", [], None, - "{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ, or differ from that of a graph design's art given first)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series (a series group's id stands for those paths, except with from \"contents\", which moves the group's own row), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {index: where the item landed | contents: the row's slot}", + "{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ, or differ from that of a graph design's art given first)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series (a series group's id stands for those paths, except with from \"contents\", which moves the group's own row), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; moving rows of such a group whose members' rows differ is an error), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes) → {index: where the item landed | contents: the row's slot}", has_doc, move_item ), @@ -129,7 +129,7 @@ pub fn specs() -> Vec { "Eyedropper", [], None, - "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode, and with `append` its topmost visible fill and stroke rows → {ids}", + "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode when transparency is applied, and with `append` its topmost visible fill and stroke rows of the kinds it adds; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows, and when transparency is applied its object opacity and blend mode, for every line of its kind (a pick of some attributes without `append`: what it changes, and the paint, stroke weight and row transparency it applies to the topmost visible rows; with `append`: only the kinds of row it adds) → {ids}", has_doc, copy_from ), @@ -147,7 +147,7 @@ pub fn specs() -> Vec { "Show All Hidden Attributes", ["Window", "Appearance"], None, - "{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {ids}", + "{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes) → {ids}", has_doc, show_all_hidden ), @@ -165,7 +165,7 @@ pub fn specs() -> Vec { "Move Appearance", [], None, - "{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series (a series group's id stands for those paths; as `source`, when the group has no effect, opacity, blend mode, isolation, knockout or style link of its own, the topmost one is read and a move clears them all; as `target` each takes the appearance and the group is cleared, a `source` among them keeps its look, and a `source` that is the group's only path is an error), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {source, target}", + "{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series (a series group's id stands for those paths; as `source`, when the group has no effect, opacity, blend mode, isolation, knockout or style link of its own, the topmost one is read and a move clears them all; as `target` each takes the appearance and the group is cleared, a `source` among them keeps its look, and a `source` that is the group's only path is an error), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {source, target}", has_doc, transfer ), @@ -446,7 +446,7 @@ pub(crate) fn rows_per_target(d: &Document, of: Option, ids: &[NodeId], } /// Whether the `target` param asks for the contents of groups and layers (see the module docs). -fn targets_contents(p: &Value) -> Result { +pub(crate) fn targets_contents(p: &Value) -> Result { match p.get("target") { None | Some(Value::Null) => Ok(false), Some(v) => match v.as_str() { @@ -508,6 +508,20 @@ pub(crate) fn drop_design_art(d: &Document, mut ids: Vec) -> Vec ids } +/// [`drop_design_art`] for an edit of the `item` rows of `ids` (`fill`: fill rows): an explicit `item` that a design's +/// art has no row of that kind for is still an error of `cmd`, as on any other object. +pub(crate) fn drop_design_art_rows(s: &Session, ids: Vec, item: ItemTarget, fill: bool, cmd: &str) -> Result> { + let d = &s.doc()?.doc; + for (id, it) in ids.iter().zip(item.per_target(s, &ids)) { + if let (Some(it), Some(n)) = (it, d.node(*id)) + && super::graph::is_design_art(d, *id) + { + it.resolve(&n.appearance, fill, cmd)?; + } + } + Ok(drop_design_art(d, ids)) +} + /// The outermost art of graph designs drawn in graph series inside `roots`: the objects directly in a series group that /// [`super::graph::is_design_art`] accepts. pub(crate) fn design_art_in(d: &Document, roots: &[NodeId]) -> Vec { @@ -524,7 +538,8 @@ pub(crate) fn design_art_in(d: &Document, roots: &[NodeId]) -> Vec { } /// `ids` with each graph series group that has no fill or stroke row of its own replaced by the paths directly inside -/// it ([`super::graph::series_group_marks`]). A series group with rows, as a document saved earlier can hold, stays: +/// it, and each such Axes or Legend group of a graph by the lines and labels directly inside it +/// ([`super::graph::series_group_marks`]). A series group with rows, as a document saved earlier can hold, stays: /// the Appearance panel lists those rows and edits them by index. pub(crate) fn rowless_series_marks(d: &Document, ids: &[NodeId]) -> Vec { super::graph::series_group_marks_where(d, ids, |group| group.appearance.items.is_empty()) @@ -545,8 +560,9 @@ fn holds_no_look(group: &Node) -> bool { } /// The objects whose appearance a command reads for `id`: a graph series group that holds nothing of its own -/// ([`holds_no_look`]) gives the paths directly inside it, backmost first. A series group with an effect, an opacity or -/// another attribute of its own is read itself, with that attribute. +/// ([`holds_no_look`]) gives the paths directly inside it, backmost first, and such an Axes or Legend group of a graph +/// the lines and labels directly inside it. A series group with an effect, an opacity or another attribute of its own is +/// read itself, with that attribute. fn look_holders(d: &Document, id: NodeId) -> Vec { super::graph::series_group_marks_where(d, &[id], holds_no_look) } @@ -612,11 +628,48 @@ fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result> { Ok(ids) } +/// Refuse a row index given a graph's Axes or Legend group that stands for lines and labels whose stacks differ +/// ([`rowless_series_marks`]), unless the index is `aligned`, a row of the backmost one's stack: the same index names a +/// different row in each of them. +pub(crate) fn check_part_rows(s: &Session, p: &Value, aligned: bool, cmd: &str) -> Result<()> { + if aligned { + return Ok(()); + } + let d = &s.doc()?.doc; + for id in appearance_targets(s, p)? { + let Some(n) = d.node(id).filter(|n| n.appearance.items.is_empty()) else { continue }; + if let Some(members) = super::graph::graph_part_members(d, n) + && appearances_differ(d, &members) + { + return Err(bad( + cmd, + format!("the lines and labels in graph group {} have different appearance rows: pass `aligned: true` or their ids", id.0), + )); + } + } + Ok(()) +} + +/// Whether row `index` of `n` is the topmost visible row of its kind, the row a graph keeps for a label or line. +fn is_top_shown(n: &Node, index: usize) -> bool { + let items = &n.appearance.items; + items.get(index).is_some_and(|it| items.iter().rposition(|o| o.is_fill() == it.is_fill() && o.visible()) == Some(index)) +} + +/// `ids` without the objects whose topmost visible fill and stroke rows ([`super::graph::label_rows`]) an edit left as +/// they were (`before`: the document before it), unless `wrote` says the edit wrote one of those rows. An edit of a +/// hidden row of a graph label or line then leaves what the graph keeps for its kind as it is. +fn shown_rows_edited(before: &Document, d: &Document, ids: Vec, wrote: impl Fn(NodeId) -> bool) -> Vec { + let shown = |doc: &Document, id: NodeId| doc.node(id).map(super::graph::label_rows); + ids.into_iter().filter(|id| wrote(*id) || shown(before, *id) != shown(d, *id)).collect() +} + /// One undo step (`label`) running `f` on each of `ids` with the item a fill (`fill`) or stroke /// edit aimed at `item` changes there (`None`: the topmost one; text then edits its characters). /// What the edit changes on the topmost visible fill and stroke of graph series marks, and on the /// rows and characters of graph labels, is stored on their graphs in the same step -/// ([`capture_series_changes`], [`super::graph::capture_label_changes`]). Nothing targeted is not +/// ([`capture_series_changes`], [`super::graph::capture_label_changes`]), and so are the rows of +/// the graph lines it reaches ([`super::graph::capture_line_changes`]). Nothing targeted is not /// an edit, and when `f` leaves every target as it was, the document and its undo history stay as /// they are. /// @@ -638,7 +691,7 @@ pub(crate) fn edit_items( edit_items_then(s, ids, item, of, cmd, label, fill, f, |before, d, edited| { let series = capture_series_changes(before, d, edited); // The rows `f` edited are kept by `edit_items_then`. - let labels = super::graph::capture_label_changes(before, d, edited, false); + let labels = super::graph::capture_label_changes(before, d, edited, false, None); Ok(series || labels) }) } @@ -656,6 +709,45 @@ pub(crate) fn edit_items_then( cmd: &str, label: &str, fill: bool, + f: impl FnMut(&mut Node, Option) -> Result<()>, + after: impl FnMut(&vectorcraft_doc::Document, &mut vectorcraft_doc::Document, &[NodeId]) -> Result, +) -> Result> { + edit_items_writing_then(s, ids, item, of, cmd, label, fill, super::graph::RowWrites::NONE, f, after) +} + +/// [`edit_items`] for an edit that writes the attributes `writes` says to the row of each target it edits: a graph line +/// keeps them for its kind when that row is its topmost visible one, also when the line already showed them +/// ([`super::graph::capture_line_row_writes`]). +#[allow(clippy::too_many_arguments)] +pub(crate) fn edit_items_writing( + s: &mut Session, + ids: &[NodeId], + item: ItemTarget, + of: Option, + cmd: &str, + label: &str, + fill: bool, + writes: super::graph::RowWrites, + f: impl FnMut(&mut Node, Option) -> Result<()>, +) -> Result> { + edit_items_writing_then(s, ids, item, of, cmd, label, fill, writes, f, |before, d, edited| { + let series = capture_series_changes(before, d, edited); + let labels = super::graph::capture_label_changes(before, d, edited, false, None); + Ok(series || labels) + }) +} + +/// [`edit_items_then`] with the attributes `writes` says, as [`edit_items_writing`] keeps them. +#[allow(clippy::too_many_arguments)] +fn edit_items_writing_then( + s: &mut Session, + ids: &[NodeId], + item: ItemTarget, + of: Option, + cmd: &str, + label: &str, + fill: bool, + writes: super::graph::RowWrites, mut f: impl FnMut(&mut Node, Option) -> Result<()>, mut after: impl FnMut(&vectorcraft_doc::Document, &mut vectorcraft_doc::Document, &[NodeId]) -> Result, ) -> Result> { @@ -679,6 +771,10 @@ pub(crate) fn edit_items_then( let mut edited = Vec::new(); // The objects whose rows `f` edited: on type, no row means its characters. let mut rows = Vec::new(); + // The objects where `f` wrote the topmost visible row of its kind. + let mut wrote = Vec::new(); + // The row of each object `f` wrote: its index, else the topmost row of the kind. + let mut written = Vec::new(); for (id, item) in ids.iter().zip(&per) { let Some(item) = item else { continue }; let Some(n) = d.node_mut(*id) else { continue }; @@ -688,10 +784,22 @@ pub(crate) fn edit_items_then( if index.is_some() { rows.push(*id); } + if index.is_none_or(|i| is_top_shown(n, i)) { + wrote.push(*id); + } + written.extend(index.or_else(|| n.appearance.items.iter().rposition(|it| it.is_fill() == fill)).map(|at| (*id, at))); } let more = after(&before, d, &edited)?; - let labels = super::graph::capture_label_rows(d, &rows); - Ok(count_changed(d, &before, &edited) + usize::from(more || labels)) + // A graph line keeps only the attributes of its rows that the edit changed, and those it wrote (`writes`): the + // others stay as its kind keeps them, which the line may not show yet. + rows.retain(|id| !super::graph::is_graph_line(d, *id)); + let labels = super::graph::capture_label_rows(d, &shown_rows_edited(&before, d, rows, |id| wrote.contains(&id))); + let mut lines = super::graph::capture_line_changes(&before, d, &edited); + if writes != super::graph::RowWrites::NONE { + let (on_fill, on_stroke) = if fill { (writes, super::graph::RowWrites::NONE) } else { (super::graph::RowWrites::NONE, writes) }; + lines |= super::graph::capture_line_row_writes(d, &written, on_fill, on_stroke); + } + Ok(count_changed(d, &before, &edited) + usize::from(more || labels || lines)) })?; Ok(aimed) } @@ -702,6 +810,17 @@ pub(crate) fn first_edited(s: &Session, item: ItemTarget, of: Option, id ids.iter().zip(item.per_target_of(s, of, ids)).find_map(|(id, it)| Some((*id, it?))) } +/// Keep the object rows of the graph labels among `ids` for every label of their kind +/// ([`super::graph::capture_label_rows`]), and of the graph lines among them only the attributes the edit changed +/// ([`super::graph::capture_line_changes`]): a line's other attributes stay as its kind keeps them, which the line may +/// not show yet. Returns whether what a graph keeps changed. +fn capture_row_edits(before: &vectorcraft_doc::Document, d: &mut vectorcraft_doc::Document, ids: &[NodeId]) -> bool { + let labels: Vec = ids.iter().copied().filter(|id| !super::graph::is_graph_line(d, *id)).collect(); + let labels = super::graph::capture_label_rows(d, &labels); + let lines = super::graph::capture_line_changes(before, d, ids); + labels || lines +} + /// How many of `ids` differ in `d` from `before`. pub(crate) fn count_changed(d: &vectorcraft_doc::Document, before: &vectorcraft_doc::Document, ids: &[NodeId]) -> usize { ids.iter().filter(|id| d.node(**id) != before.node(**id)).count() @@ -720,7 +839,10 @@ pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bo let holder = match reference_of(s, p, item, cmd)? { Some(of) => Some(of), None => { - let ids = drop_design_art(d, appearance_targets(s, p)?); + let all = appearance_targets(s, p)?; + // The art of a graph design is left out, unless it is all there is: the item is then a row of that art. + let kept = drop_design_art(d, all.clone()); + let ids = if kept.is_empty() { all } else { kept }; ids.get(item.anchor(s, &ids)).copied() } }; @@ -837,10 +959,13 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result { } } super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids)); + let lines: Vec = added.iter().map(|(id, _)| *id).collect(); let mut rows = top_paint_changed(&before, d, &ids); rows.extend(painted_rows(d, added)); super::graph::capture_series_top_paints(d, &rows); - super::graph::capture_label_rows(d, &ids); + capture_row_edits(&before, d, &ids); + // A graph line keeps the row it got for its kind, also when it showed that row's paint, weight and transparency. + super::graph::capture_line_kind_rows(d, &lines, (fill, !fill), false); Ok(()) })?; // A fill added above the active row becomes the active row; otherwise the rows above the new @@ -1029,7 +1154,7 @@ fn transfer(s: &mut Session, p: &Value) -> Result { let mut targets: Vec = marks.iter().copied().filter(|id| !within.contains(id)).collect(); if targets.is_empty() { if stands { - return Err(bad(C, "`source` is the only path in series group `target`")); + return Err(bad(C, "`source` is the only path, line or label that graph group `target` stands for")); } targets.push(target); } @@ -1074,8 +1199,9 @@ fn transfer(s: &mut Session, p: &Value) -> Result { rows.extend(painted_rows(d, both_kinds(&targets))); let painted = super::graph::capture_series_top_paints(d, &rows); let object = super::graph::capture_series_object_opacity(d, &changed); - // The targets last: on two labels of one kind, the target's rows are the ones the kind keeps. - let labels = super::graph::capture_label_rows(d, &changed); + // The targets last: on two labels of one kind, the target's rows are the ones the kind keeps. Graph lines are + // taken in paint order, so the targets are captured again on their own, after a cleared source in front of them. + let labels = super::graph::capture_label_rows(d, &changed) | super::graph::capture_label_rows(d, &targets); let all: Vec = from.iter().chain(&targets).chain(&group).copied().collect(); Ok(count_changed(d, &before, &all) + usize::from(kept || painted || object || labels || forgot)) })?; @@ -1133,7 +1259,7 @@ fn reduce_basic(s: &mut Session, p: &Value) -> Result { } let kept = super::graph::capture_series_opacity(d, &both_kinds(&ids)); let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids)); - let labels = super::graph::capture_label_rows(d, &ids); + let labels = capture_row_edits(&before, d, &ids); Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels)) })?; s.active_appearance_item = None; @@ -1150,6 +1276,7 @@ fn set_item(s: &mut Session, p: &Value) -> Result { if ids.is_empty() { return Err(bad("appearance.setItem", "select objects or give ids")); } + check_part_rows(s, p, aligned(p, "appearance.setItem")?, "appearance.setItem")?; let blend = str_param(p, "blend").and_then(BlendMode::parse); // When every object comes out as it was (for example, when none has item `index`), the document // and its undo history stay as they are. @@ -1158,6 +1285,9 @@ fn set_item(s: &mut Session, p: &Value) -> Result { let per = rows_per_target(&before, of, &ids, &[idx], aligned(p, "appearance.setItem")?); super::overprint::edit_counted(s, "Appearance", |d| { let mut edited = Vec::new(); + // The targets that have the row: an aligned row leaves out the members of a graph's Axes or Legend group that + // lack it, and the graph keeps the rows of the labels and lines it reached only. + let mut reached = Vec::new(); for (id, at) in ids.iter().zip(&per) { let Some(&idx) = at.first() else { continue }; let Some(n) = d.node_mut(*id) else { continue }; @@ -1168,6 +1298,7 @@ fn set_item(s: &mut Session, p: &Value) -> Result { } let bounds = n.geometric_bounds(); let Some(item) = n.appearance.items.get_mut(idx) else { continue }; + reached.push(*id); let (pp, op, bl, vis, bounds) = match item { AppearanceItem::Fill(f) => (&mut f.paint, &mut f.opacity, &mut f.blend, &mut f.visible, bounds), AppearanceItem::Stroke(st) => { @@ -1210,8 +1341,19 @@ fn set_item(s: &mut Session, p: &Value) -> Result { let mut rows = top_paint_changed(&before, d, &ids); rows.extend(painted_rows(d, written)); let painted = super::graph::capture_series_top_paints(d, &rows); - let labels = super::graph::capture_label_rows(d, &ids); - Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels)) + let reached = shown_rows_edited(&before, d, reached, |id| edited.iter().any(|(e, _)| *e == id)); + let labels = capture_row_edits(&before, d, &reached); + // A graph line keeps what was written to its topmost visible row, also when it already showed it. + let tops: Vec<(NodeId, usize)> = ids.iter().zip(&per).filter_map(|(id, at)| Some((*id, *at.first()?))).collect(); + // Only the values the edit applied: a null weight or opacity leaves the row as it is. + let writes = super::graph::RowWrites { + paint: paint.is_some(), + weight: p.get("weight").and_then(Value::as_f64).is_some(), + opacity: p.get("opacity").and_then(Value::as_f64).is_some(), + blend: blend.is_some(), + }; + let lines = super::graph::capture_line_row_writes(d, &tops, super::graph::RowWrites { weight: false, ..writes }, writes); + Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels || lines)) })?; if let Some(pa) = &paint { s.remember_paint(pa); @@ -1239,14 +1381,20 @@ pub(super) fn item_indices(p: &Value, cmd: &str) -> Result> { fn remove_item(s: &mut Session, p: &Value) -> Result { let idx = item_indices(p, "appearance.removeItem")?; let ids = require_targets(s, p, "appearance.removeItem")?; + check_part_rows(s, p, aligned(p, "appearance.removeItem")?, "appearance.removeItem")?; // When no object has an item at any of the indices, the document and its undo history stay as // they are. let before = s.doc()?.doc.clone(); let of = design_reference(s, p, "appearance.removeItem")?; let per = rows_per_target(&before, of, &ids, &idx, aligned(p, "appearance.removeItem")?); super::overprint::edit_counted(s, "Remove Item", |d| { + // The targets that had a row to remove, as in `set_item`. + let mut reached = Vec::new(); for (id, idx) in ids.iter().zip(&per) { if let Some(n) = d.node_mut(*id) { + if idx.iter().any(|i| *i < n.appearance.items.len()) { + reached.push(*id); + } let mut idx = idx.clone(); idx.sort_unstable(); // From the top down, so the lower indices stay valid. @@ -1258,7 +1406,7 @@ fn remove_item(s: &mut Session, p: &Value) -> Result { } let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids)); let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids)); - let labels = super::graph::capture_label_rows(d, &ids); + let labels = capture_row_edits(&before, d, &shown_rows_edited(&before, d, reached, |_| false)); Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels)) })?; // The rows removed from the active row's object, which need not come first in `ids`. @@ -1278,6 +1426,7 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "`contents` goes with `to`")); } let ids = require_targets(s, p, C)?; + check_part_rows(s, p, aligned(p, C)?, C)?; // Where the first target's copy landed, and where it landed on the active row's object (the // first selected one, not always the first target): copies placed at `to` land at a different // index on stacks of other lengths. @@ -1302,6 +1451,8 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result { // Copies that became the topmost visible row of their kind: the series stores their paint even when the object // showed it. let mut added = Vec::new(); + // The targets that took a copy, as in `set_item`. + let mut reached = Vec::new(); for (id, idx) in ids.iter().zip(&per) { let Some(n) = d.node_mut(*id) else { continue }; let has_contents = n.contents_label().is_some(); @@ -1326,6 +1477,7 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result { ap.set_contents_at(c); } any = true; + reached.push(*id); continue; } let mut idx = idx.clone(); @@ -1340,6 +1492,9 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result { added.push((*id, kind)); } any = true; + if reached.last() != Some(id) { + reached.push(*id); + } } } } @@ -1348,9 +1503,10 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result { } super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids)); let mut rows = top_paint_changed(&before, d, &ids); + let top_copies: Vec = added.iter().map(|(id, _)| *id).collect(); rows.extend(painted_rows(d, added)); super::graph::capture_series_top_paints(d, &rows); - super::graph::capture_label_rows(d, &ids); + capture_row_edits(&before, d, &shown_rows_edited(&before, d, reached, |id| top_copies.contains(&id))); Ok(()) })?; // Rows at or above each copy move up by one (by the block, for copies placed at `to`). @@ -1390,7 +1546,7 @@ fn show_all_hidden(s: &mut Session, p: &Value) -> Result { } super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &shown)); super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &shown)); - super::graph::capture_label_rows(d, &shown); + capture_row_edits(&before, d, &shown); Ok(shown) })?; Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>() })) @@ -1414,6 +1570,7 @@ fn move_item(s: &mut Session, p: &Value) -> Result { return move_contents(s, &ids, to); } let ids = require_targets(s, p, C)?; + check_part_rows(s, p, aligned, C)?; // Where an aligned row would go in each of several different stacks isn't one place. if aligned && appearances_differ(&s.doc()?.doc, &with_reference(design_reference(s, p, C)?, &ids)) { return Err(bad(C, "rows of objects whose appearances differ can't be reordered together")); @@ -1440,7 +1597,7 @@ fn move_item(s: &mut Session, p: &Value) -> Result { } let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids)); let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids)); - let labels = super::graph::capture_label_rows(d, &ids); + let labels = super::graph::capture_label_changes(&before, d, &ids, true, None); Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels)) })?; // The moved row stays the active one; the rows it passed shift by one. @@ -1486,7 +1643,7 @@ fn move_items(s: &mut Session, p: &Value, ids: &[NodeId], to: usize) -> Result Result { slot.get_or_insert(n.appearance.contents_at()); } slot.ok_or_else(|| bad("appearance.moveItem", "only groups, layers, type and images have a Contents (Characters) row"))?; - // A graph label's kind keeps where its rows paint relative to the characters. - let labels = super::graph::capture_label_rows(d, ids); + // A graph label's kind keeps where its rows paint relative to the characters, from the labels the move changed. + let labels = capture_row_edits(&before, d, &shown_rows_edited(&before, d, ids.to_vec(), |_| false)); Ok(count_changed(d, &before, ids) + usize::from(labels)) })?; Ok(json!({ "contents": slot })) @@ -1787,15 +1944,45 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { let object = super::graph::capture_series_object_opacity(d, &objects); // Graph labels keep their new rows, characters and paragraphs per kind of label. // On type, only `append` adds rows and a transparency pick changes the object's opacity and blend mode; the other - // attributes go to the characters. + // attributes go to the characters. Without a transparency pick, the object opacity and blend mode a kind keeps stay, + // also when the label or line picked onto still shows other ones until the graph is drawn again. `append` keeps + // only the kinds of row it added; a row of the other kind stays as the kind keeps it. + let transparency = attrs.appearance.transparency; let rows = if append { - super::graph::capture_label_rows(d, &targets) + super::graph::capture_label_kind_rows(d, &targets, paints, transparency) } else { - attrs.appearance.transparency && super::graph::capture_label_object_opacity(d, &targets) + transparency && super::graph::capture_label_object_opacity(d, &targets) }; // `append` adds rows and leaves the characters as they were. let text = !append && super::graph::capture_label_text(d, &targets, kept_text, kept_para)?; - Ok(count_changed(d, &before, &targets) + usize::from(kept || painted || object || rows || text)) + // A graph line is a path: a whole pick and `append` write its rows. A pick of some attributes keeps those it + // changed, and the rest stay as its kind keeps them, which the line may not show yet. Row attributes the graph + // does not keep (overprint, caps, joins, miter limit, dashes) leave what its kind keeps as it is. + let lines = match (rows_written, transparency) { + _ if append => super::graph::capture_line_kind_rows(d, &targets, paints, transparency), + (true, true) => super::graph::capture_line_rows(d, &targets), + (true, false) => super::graph::capture_line_fill_stroke_rows(d, &targets), + (false, _) => { + // The topmost row of each kind, which the pick wrote: what it wrote is kept also when the line showed it. + let tops: Vec<(NodeId, usize)> = targets + .iter() + .filter_map(|id| d.node(*id).map(|n| (*id, &n.appearance.items))) + .flat_map(|(id, items)| { + [true, false].into_iter().filter_map(move |kind| items.iter().rposition(|it| it.is_fill() == kind).map(|at| (id, at))) + }) + .collect(); + // A transparency pick applies the row's opacity and blend mode together. + let on_fill = super::graph::RowWrites { paint: fill.color, weight: false, opacity: opacities.0, blend: opacities.0 }; + let on_stroke = super::graph::RowWrites { + paint: stroke.color, + weight: stroke.weight && source_has(false), + opacity: opacities.1, + blend: opacities.1, + }; + super::graph::capture_line_changes(&before, d, &targets) | super::graph::capture_line_row_writes(d, &tops, on_fill, on_stroke) + } + }; + Ok(count_changed(d, &before, &targets) + usize::from(kept || painted || object || rows || text || lines)) })?; Ok(finish(s, &targets)) } diff --git a/crates/engine/src/cmd/assets.rs b/crates/engine/src/cmd/assets.rs index cb990e4857..fcb251347d 100644 --- a/crates/engine/src/cmd/assets.rs +++ b/crates/engine/src/cmd/assets.rs @@ -8,7 +8,7 @@ use std::collections::HashSet; use serde_json::{Map, Value, json}; use vectorcraft_doc::{ExportAsset, NodeId}; -use super::edit::{roots_of, selected_roots}; +use super::edit::{refuse_symbol_part, roots_of, selected_roots}; use super::fileio::{ DEFAULT_FORMAT_3D, FORMATS_3D, SCREEN_SETTINGS_KEYS, check_screen_settings, create_dir, export_crop, export_screens, mesh_file_names, mesh_files, safe_file_name, store_screen_settings, with_screen_export_preset, write_file, @@ -62,7 +62,7 @@ pub fn specs() -> Vec { "Export 3D Object", [], None, - "{ids?: [id…] (default: the selected objects), format?: usda|usdz|gltf|obj (default usda)} collect each object with an Extrude & Bevel, Revolve, Inflate or Rotate effect as a 3D asset of Window › Asset Export, named after the object (else Asset 1, Asset 2…): assets.export3D writes it as a mesh file. An object already collected as a 3D asset keeps it; an object without such an effect is refused → {assets: [asset id…] (in order), added: n}", + "{ids?: [id…] (default: the selected objects), format?: usda|usdz|gltf|obj (default usda)} collect each object with an Extrude & Bevel, Revolve, Inflate or Rotate effect as a 3D asset of Window › Asset Export, named after the object (else Asset 1, Asset 2…): assets.export3D writes it as a mesh file. An object already collected as a 3D asset keeps it; an object in ids without such an effect is refused. Without ids, the selected objects without one (on a group or layer, one on its fill or stroke draws nothing and does not count), and a selected object inside another selected object that has one, are left out; refused when none is left → {assets: [asset id…] (in order), added: n}", has_doc, add_3d ), @@ -203,10 +203,36 @@ fn three_d_asset_ids(d: &vectorcraft_doc::Document, p: &Value, key: &str, cmd: & Ok(ids) } +/// The selected objects `assets.add3D` collects without `ids`: those with a 3D effect it exports +/// ([`vectorcraft_render::effects::exports_three_d`]; a path of a compound path counts as the +/// compound path), layers included, in tree order, dropping +/// each one inside another of them (that one's asset holds it). Refused while an object of a +/// dynamic symbol instance's art is selected, as [`selected_roots`] is. +fn selected_3d_roots(s: &Session) -> Result> { + refuse_symbol_part(s)?; + let st = s.doc()?; + // A path of a compound path stands for the compound path, which holds the paint and effects. + let found = st + .selection + .objects + .iter() + .map(|id| super::path::compound_or_self(&st.doc, *id)) + .filter(|id| st.doc.node(*id).is_some_and(vectorcraft_render::effects::exports_three_d)); + let mut paths: Vec<(Vec, NodeId)> = st.doc.index_paths(found).into_iter().map(|(id, path)| (path, id)).collect(); + paths.sort_by(|a, b| a.0.cmp(&b.0)); + let mut kept: Vec<(Vec, NodeId)> = Vec::with_capacity(paths.len()); + for (path, id) in paths { + if !kept.last().is_some_and(|(outer, _)| path.starts_with(outer)) { + kept.push((path, id)); + } + } + Ok(kept.into_iter().map(|(_, id)| id).collect()) +} + fn add_3d(s: &mut Session, p: &Value) -> Result { const C: &str = "assets.add3D"; let format = format_3d_param(p, C, Some(DEFAULT_FORMAT_3D))?; - let ids = if p.get("ids").is_some_and(|v| !v.is_null()) { checked_ids_param(s, p, "ids", C)? } else { selected_roots(s)? }; + let ids = if p.get("ids").is_some_and(|v| !v.is_null()) { checked_ids_param(s, p, "ids", C)? } else { selected_3d_roots(s)? }; if ids.is_empty() { return Err(bad(C, "select an object with a 3D effect (or give its ids)")); } diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index db6e4e28a1..c4f35dfc3f 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -27,6 +27,9 @@ use crate::EngineError; /// Whether Reset Transformation changes a symbol instance. pub use symbols::reset_transformation_changes; +/// The Symbols panel's current symbol, as `symbol.list` answers it. +pub use symbols::current_symbol; + mod brushes; mod dynamic; mod symbols; @@ -190,7 +193,7 @@ pub fn specs() -> Vec { "Symbols", [], None, - "{} → {symbols: [{name, instances, size: [w,h], registration: 0..8, exportType: movieClip|graphic, nineSlice, type: static|dynamic}], current}", + "{} → {symbols: [{name, instances, size: [w,h], registration: 0..8, exportType: movieClip|graphic, nineSlice, type: static|dynamic, alignToPixelGrid: bool}], current}", has_doc, symbol_list ), @@ -199,7 +202,7 @@ pub fn specs() -> Vec { "New Symbol…", [], None, - "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions → {name, id, registration, exportType, nineSlice, type}", + "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}", has_selection, symbol_new ), @@ -208,7 +211,7 @@ pub fn specs() -> Vec { "Symbol Options…", [], None, - "{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}", + "{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic, alignToPixelGrid?: bool} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1), Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes) and Align to Pixel Grid (on: the horizontal and vertical straight segments of the paths in the symbol's art snap to whole points, or half points for an odd centered stroke, at the symbol's natural size, its stroke weights become whole points, and every instance placed at that size, reflected across one axis or not, moves to whole points and goes back to them after each move; a scaled, rotated (a half turn included) or sheared instance, and an instance in another symbol's art, is left where it is; the art snaps again after it is edited); alignToPixelGrid alone with the value the symbol already has changes nothing and adds no undo step; default name: current → {name, registration, exportType, nineSlice, type, alignToPixelGrid}", has_doc, symbol_options ), diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 1bfb8edea7..cecd314858 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -69,6 +69,15 @@ fn nine_slice_param(p: &Value, cmd: &str, current: Option) -> R }) } +/// `alignToPixelGrid` (Symbol Options › Align to Pixel Grid): `None` when it is not given; any +/// value other than true or false, null included, is an error. +fn pixel_grid_param(p: &Value, cmd: &str) -> Result> { + match p.get("alignToPixelGrid") { + None => Ok(None), + Some(v) => v.as_bool().map(Some).ok_or_else(|| bad(cmd, "alignToPixelGrid must be true or false")), + } +} + fn nine_slice_json(d: &Document, name: &str) -> Value { d.symbol_nine_slice(name).map_or(Value::Null, SymbolNineSlice::to_value) } @@ -153,7 +162,7 @@ pub(super) fn symbol_sort(s: &mut Session, _: &Value) -> Result { if d.symbols.is_sorted_by_key(key) { return ok(); } - let current = current_symbol(d).or_else(|| symbol_names(d).into_iter().next()); + let current = current_symbol(d); s.edit("Sort by Name", |d, _| { if let Some(name) = current { d.unknown.insert(CURRENT_SYMBOL.into(), json!(name)); @@ -164,12 +173,15 @@ pub(super) fn symbol_sort(s: &mut Session, _: &Value) -> Result { ok() } -fn symbol_names(d: &Document) -> Vec { - d.symbols.iter().map(|s| s.name.clone()).collect() -} - -fn current_symbol(d: &Document) -> Option { - d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str).filter(|n| d.symbols.iter().any(|s| s.name == *n)).map(str::to_string) +/// The Symbols panel's current symbol, as `symbol.list` answers it: the stored current symbol +/// while `d` has a symbol of that name, else the first symbol; `None` when `d` has no symbols. +pub fn current_symbol(d: &Document) -> Option { + d.unknown + .get(CURRENT_SYMBOL) + .and_then(Value::as_str) + .filter(|n| d.symbols.iter().any(|s| s.name == *n)) + .or_else(|| d.symbols.first().map(|s| s.name.as_str())) + .map(str::to_string) } pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result { @@ -187,10 +199,11 @@ pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result { "exportType": d.symbol_export_type(&sym.name).id(), "nineSlice": nine_slice_json(d, &sym.name), "type": type_id(sym.dynamic), + "alignToPixelGrid": d.symbol_pixel_aligned(&sym.name), }) }) .collect(); - Ok(json!({ "symbols": list, "current": current_symbol(d).or_else(|| symbol_names(d).into_iter().next()) })) + Ok(json!({ "symbols": list, "current": current_symbol(d) })) } /// Store `art` ([`normalize`]d, of natural size `size`) as symbol `name`, which becomes the @@ -239,6 +252,7 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result { let export = export_type_param(p, C)?.unwrap_or_default(); let nine = nine_slice_param(p, C, None)?.flatten(); let dynamic = type_param(p, C)?.unwrap_or(false); + let pixel = pixel_grid_param(p, C)?.unwrap_or(false); // Keep the art where it was: the geometric centre stays at `c`, whatever the registration is. let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg); let id = s.edit("New Symbol", |d, sel| { @@ -249,6 +263,7 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result { d.set_symbol_registration(&name, reg); d.set_symbol_export_type(&name, export); d.set_symbol_nine_slice(&name, nine); + d.set_symbol_pixel_aligned(&name, pixel); let id = instance_in_place(d, &ids, &name, place)?; sel.set([id]); Ok(id) @@ -260,6 +275,7 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result { "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value), "type": type_id(dynamic), + "alignToPixelGrid": pixel, })) } @@ -270,9 +286,15 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result { let reg = registration_param(p, C)?; let nine = nine_slice_param(p, C, s.doc()?.doc.symbol_nine_slice(&name))?; let dynamic = type_param(p, C)?; + let pixel = pixel_grid_param(p, C)?; let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string); if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() && dynamic.is_none() { - return Err(bad(C, "pass newName, registration, exportType, nineSlice and/or type")); + match pixel { + None => return Err(bad(C, "pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid")), + // Align to Pixel Grid alone, already as asked: nothing changes and no undo step is added. + Some(on) if on == s.doc()?.doc.symbol_pixel_aligned(&name) => return Ok(options_json(&s.doc()?.doc, &name)), + Some(_) => {} + } } if let Some(ref n) = new_name && n != &name @@ -324,6 +346,7 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result { d.rename_symbol_registration(&name, n); d.rename_symbol_export_type(&name, n); d.rename_symbol_nine_slice(&name, n); + d.rename_symbol_pixel_aligned(&name, n); if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) { d.unknown.insert(CURRENT_SYMBOL.into(), json!(n)); } @@ -352,25 +375,33 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result { sym.dynamic = dynamic; fit_overrides(d, &instances_of(d, Some(&final_name))); } + // Turning it on snaps the art and the instances at actual size when the edit ends + // (`object::refresh_pixel_aligned`). + if let Some(on) = pixel { + d.set_symbol_pixel_aligned(&final_name, on); + } Ok(()) })?; - let d = &s.doc()?.doc; - Ok(json!({ - "name": final_name, - "registration": d.symbol_registration(&final_name).0, - "exportType": d.symbol_export_type(&final_name).id(), - "nineSlice": nine_slice_json(d, &final_name), - "type": type_id(d.symbols.iter().any(|x| x.name == final_name && x.dynamic)), - })) + Ok(options_json(&s.doc()?.doc, &final_name)) +} + +/// What `symbol.options` answers for symbol `name`. +fn options_json(d: &Document, name: &str) -> Value { + json!({ + "name": name, + "registration": d.symbol_registration(name).0, + "exportType": d.symbol_export_type(name).id(), + "nineSlice": nine_slice_json(d, name), + "type": type_id(d.symbols.iter().any(|x| x.name == name && x.dynamic)), + "alignToPixelGrid": d.symbol_pixel_aligned(name), + }) } fn resolve_symbol(d: &Document, p: &Value, cmd: &str) -> Result { match str_param(p, "name") { Some(n) if d.symbols.iter().any(|s| s.name == n) => Ok(n.to_string()), Some(n) => Err(bad(cmd, format!("no symbol named `{n}`"))), - None => { - current_symbol(d).or_else(|| symbol_names(d).into_iter().next()).ok_or_else(|| EngineError::Other("the document has no symbols".into())) - } + None => current_symbol(d).ok_or_else(|| EngineError::Other("the document has no symbols".into())), } } @@ -702,6 +733,7 @@ pub(super) fn symbol_delete(s: &mut Session, p: &Value) -> Result { d.set_symbol_registration(name, SymbolRegistration::CENTER); d.clear_symbol_export_type(name); d.set_symbol_nine_slice(name, None); + d.set_symbol_pixel_aligned(name, false); if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) { d.unknown.remove(CURRENT_SYMBOL); } @@ -725,6 +757,7 @@ pub(super) fn symbol_duplicate(s: &mut Session, p: &Value) -> Result { let reg = d.symbol_registration(&name); let export = d.symbol_export_type(&name); let nine = d.symbol_nine_slice(&name); + let pixel = d.symbol_pixel_aligned(&name); s.edit("Duplicate Symbol", |d, _| { let art = d.reid(&sym.art); d.symbols.push(Symbol { dynamic: sym.dynamic, name: new.clone(), art: Arc::new(art) }); @@ -732,6 +765,7 @@ pub(super) fn symbol_duplicate(s: &mut Session, p: &Value) -> Result { d.set_symbol_registration(&new, reg); d.set_symbol_export_type(&new, export); d.set_symbol_nine_slice(&new, nine); + d.set_symbol_pixel_aligned(&new, pixel); Ok(()) })?; Ok(json!({ "name": new, "registration": reg.0, "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value) })) diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 95c04e39c7..98aa9ae490 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -126,7 +126,7 @@ pub fn specs() -> Vec { "Live Paint Bucket (Stroke)", [], None, - "{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), through?: [id…] (scope connected only; at most 4096 edges counted as drawing with stroke paint match whatever they draw with, such as the edge a double-click's first click painted), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}", + "{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), through?: [id…] (scope connected only; at most 4096 of the group's edges, each given once, counted as drawing with stroke paint match whatever they draw with, such as another edge a double-click's clicks painted; any other id is an error), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}", has_doc, lp_stroke_edge ), @@ -144,7 +144,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Image Trace"], None, - "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" group under the paths holds 1.5 px strokes along the edges two filled paths share, in the color of the lower path, so that no light hairline shows along those edges; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", + "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", has_selection_or_ids, |s, p| trace_make(s, p, false) ), diff --git a/crates/engine/src/cmd/buildcmds/live_paint.rs b/crates/engine/src/cmd/buildcmds/live_paint.rs index 46a2d37555..a030f5bd8f 100644 --- a/crates/engine/src/cmd/buildcmds/live_paint.rs +++ b/crates/engine/src/cmd/buildcmds/live_paint.rs @@ -580,6 +580,12 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result { let (eid, count, changed) = { let d = &s.doc()?.doc; let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad(C, format!("{g} is not a Live Paint group")))?; + // Each id in `through` is an edge of the group, given once. + let group_edges: std::collections::HashSet = b::edges(n).iter().map(|e| e.id).collect(); + let mut seen = std::collections::HashSet::new(); + if let Some(id) = through.iter().find(|id| !group_edges.contains(id) || !seen.insert(**id)) { + return Err(bad(C, format!("through: {id} is not an edge of {g}, or is given twice"))); + } let start = b::visible_edge_near(n, pt, tol).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?; let eid = start.id; let like = like.unwrap_or_else(|| b::lp_stroke_paint(start)); diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 2eb81eaef5..203fd62338 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -23,20 +23,30 @@ fn is_trace_group(n: &Node) -> bool { && n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_)))) } -/// The name of the group that holds an Abutting trace's seam fills (see [`tr::TraceResult::seams`]). +/// The name of the clip group that holds an Abutting trace's seam fills (see [`tr::seam_fills`]). const SEAM_FILLS_NAME: &str = "Seam Fills"; -/// Whether `n` can be a trace's seam fills group: a group named as one, or a group of stroked paths -/// without fills, so that it is still found after it is renamed or its strokes are edited. (Auto -/// Grouping groups hold filled paths.) +/// Whether `n` can be a trace's seam fills group: a clip group named as one, or a clip group whose +/// members after the clipping path are all stroked paths without fills, or all filled paths +/// without strokes (the strokes' outlines, on a stretched image), so that it is still found after +/// it is renamed or its strokes are edited. (Auto Grouping groups are not clip groups.) Traces made +/// before the seam fills were clipped hold a group without a clip: one named as seam fills, or one +/// of stroked paths without fills. (Auto Grouping groups hold filled paths.) fn is_seam_fills(n: &Node) -> bool { - let stroke_only = |m: &Arc| { - matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) - && m.appearance.fill_paint() == Paint::None - && m.appearance.stroke_paint() != Paint::None - }; - matches!(n.kind, NodeKind::Group { clip: false, .. }) - && (n.name.as_deref() == Some(SEAM_FILLS_NAME) || n.children().is_some_and(|c| !c.is_empty() && c.iter().all(stroke_only))) + let path = |m: &Arc| matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }); + let stroke_only = |m: &Arc| path(m) && m.appearance.fill_paint() == Paint::None && m.appearance.stroke_paint() != Paint::None; + let fill_only = |m: &Arc| path(m) && m.appearance.fill_paint() != Paint::None && m.appearance.stroke_paint() == Paint::None; + let named = n.name.as_deref() == Some(SEAM_FILLS_NAME); + match &n.kind { + NodeKind::Group { clip: true, children } => { + named + || children + .split_first() + .is_some_and(|(_, members)| !members.is_empty() && (members.iter().all(stroke_only) || members.iter().all(fill_only))) + } + NodeKind::Group { clip: false, children } => named || (!children.is_empty() && children.iter().all(stroke_only)), + _ => false, + } } const LIVE_PATHFINDER_BY_COLOR: &str = "byColor can't regroup a trace with a live Pathfinder effect: expand without byColor"; @@ -411,7 +421,8 @@ fn by_color_param(cmd: &str, p: &Value) -> Result { /// starts another group of that paint, which keeps the stacking order of those items. Items /// farther apart can still share antialiased pixels at small view or raster-export scales, so /// their edge pixels may change. The seam fills' group, when it is the lowest item, stays as it is, -/// under every other group. Any other group among `items` (Auto Grouping) is refused. +/// under every other group; above another item it is refused. Any other group among `items` (Auto +/// Grouping) is refused. fn color_groups(cmd: &str, d: &mut Document, items: Vec>) -> Result>> { use std::collections::{BTreeMap, HashMap}; use std::ops::Bound::{Excluded, Unbounded}; @@ -465,6 +476,9 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec>) -> Result> = BTreeMap::new(); let mut all_boxes: BTreeMap> = BTreeMap::new(); for (item, bounds) in items { + if is_seam_fills(&item) { + return Err(bad(cmd, "byColor needs the seam fills' group under every path: move it to the bottom or delete it")); + } if matches!(item.kind, NodeKind::Group { .. }) { return Err(bad(cmd, "byColor can't split Auto Grouping groups: trace without Auto Grouping")); } @@ -637,12 +651,12 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result { } /// What a trace made of an image: the size in pixels it was decoded at, the paths, and their seam -/// fills ([`seams_within`]). +/// fills, if any ([`seams_within`]). pub struct Traced { inputs: TraceInputs, raster: (u32, u32), res: tr::TraceResult, - seams: Vec, + seams: Option, } impl Traced { @@ -669,18 +683,127 @@ fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64 tr::TraceError::Cancelled => EngineError::Cancelled, e => EngineError::Other(e.to_string()), })?; - let seams = seams_within(&res, params, MAX_TRACE_ANCHORS); - Ok(Traced { inputs: inputs.clone(), raster: (raster.width, raster.height), res, seams }) + if !steps(0, 0) { + return Err(EngineError::Cancelled); + } + let size = (raster.width, raster.height); + let outlined = seam_unit(inputs.image.xf, raster_xf(&inputs.image, size)).is_none(); + let seams = seams_within(&res, params, size, MAX_TRACE_ANCHORS, outlined, steps)?; + Ok(Traced { inputs: inputs.clone(), raster: size, res, seams }) } -/// The seam fills of `res`, traced with `params` ([`tr::seam_fills`]), while the paths and the seam -/// fills together stay within `max` anchors: the seam fills have at most as many anchors as the -/// paths, so a trace whose paths have more than half of `max` gets none. -fn seams_within(res: &tr::TraceResult, params: &tr::TraceParams, max: usize) -> Vec { - if res.anchor_count() > max / 2 { - return vec![]; +/// Pixel space of a `size` raster decoded from `img` → the image object's pixel space → document. +fn raster_xf(img: &ImageObject, size: (u32, u32)) -> vectorcraft_geom::Affine { + let sx = img.width.max(1) as f64 / size.0.max(1) as f64; + let sy = img.height.max(1) as f64 / size.1.max(1) as f64; + img.xf * vectorcraft_geom::Affine::scale_non_uniform(sx, sy) +} + +/// Whether `xf` scales every direction alike (turning and mirroring allowed): its axes keep equal +/// lengths and stay at right angles. +fn scales_alike(xf: vectorcraft_geom::Affine) -> bool { + let [a, b, c, d, _, _] = xf.as_coeffs(); + let (across, down) = (a * a + b * b, c * c + d * d); + let t = across + down; + t.is_finite() && t > 0.0 && (across - down).abs() <= 1e-9 * t && (a * c + b * d).abs() <= 1e-9 * t +} + +/// The smallest length that `xf` scales a unit vector to (its smaller singular value): the +/// difference of the lengths of its turning part and its stretching part. +fn least_scale(xf: vectorcraft_geom::Affine) -> f64 { + let [a, b, c, d, _, _] = xf.as_coeffs(); + let turning = ((a + d) / 2.0).hypot((b - c) / 2.0); + let stretching = ((a - d) / 2.0).hypot((b + c) / 2.0); + (turning - stretching).abs() +} + +/// Document units per raster pixel for the seam fills' strokes when the image object's transform +/// `img_xf` scales every direction alike: the smaller scale of the raster-to-document transform +/// `xf`, so that a stroke 1.5 pixels wide covers at most 0.75 pixels on each side of its edge at +/// any angle. (A raster decoded scaled down to fit can be scaled a little differently across and +/// down, as each side is rounded.) `None` when `img_xf` stretches one direction more than another +/// or is degenerate, where a stroke of any one width would cover more pixels across some edges +/// than across others. +fn seam_unit(img_xf: vectorcraft_geom::Affine, xf: vectorcraft_geom::Affine) -> Option { + let least = least_scale(xf); + (scales_alike(img_xf) && least.is_finite() && least > 0.0).then_some(least) +} + +/// The seam fills of `res`, traced with `params` from a `size` raster ([`tr::seam_fills`]), while +/// the paths, the seam fills and their clip together stay within `max` anchors. With `outlined`, +/// each stroke is replaced by a filled path, its outline in raster pixels ([`outline_seams`]), +/// for an image stretched more one way than another ([`seam_unit`]). The strokes have at most as +/// many anchors as the paths and the clip at most [`SEAM_CLIP_ANCHORS`], so a trace whose paths +/// have more than half of `max` less four gets none. Outlines, which have more anchors, are +/// counted as each is made, and none is made when [`SEAM_OUTLINE_ANCHORS`] times the strokes' +/// anchors would not fit, or once those made so far no longer fit. [`EngineError::Cancelled`] +/// once `steps` answers `false`. +fn seams_within( + res: &tr::TraceResult, + params: &tr::TraceParams, + size: (u32, u32), + max: usize, + outlined: bool, + steps: &(dyn Fn(u64, u64) -> bool + Sync), +) -> Result> { + if res.anchor_count().saturating_mul(2).saturating_add(SEAM_CLIP_ANCHORS) > max { + return Ok(None); + } + let Some(mut seams) = tr::seam_fills(&res.paths, params, size) else { return Ok(None) }; + if outlined { + let strokes = seams.strokes.iter().map(|tp| tp.path.anchor_count()).sum::(); + let estimate = strokes.saturating_mul(SEAM_OUTLINE_ANCHORS).saturating_add(SEAM_CLIP_ANCHORS); + if res.anchor_count().saturating_add(estimate) > max { + return Ok(None); + } + let budget = max.saturating_sub(res.anchor_count()).saturating_sub(SEAM_CLIP_ANCHORS); + if !outline_seams(&mut seams.strokes, budget, steps)? { + return Ok(None); + } + seams.strokes.retain(|tp| !tp.path.is_empty()); + if seams.strokes.is_empty() { + return Ok(None); + } + } + Ok(Some(seams)) +} + +/// The most anchors the seam fills' clip has: the image's box cut to the box of the traced paths +/// ([`within_box`]), four corners and at most four more where the image is turned. +const SEAM_CLIP_ANCHORS: usize = 8; + +/// How many seam strokes [`outline_seams`] outlines between asking whether to go on. +const SEAM_OUTLINE_STEP: usize = 64; + +/// Outline each of `strokes` ([`outlined_seam`]) while the outlines' anchors stay within `budget`, +/// asking `steps` every [`SEAM_OUTLINE_STEP`] strokes whether to go on → whether every outline +/// fits (it stops at the first that does not), or [`EngineError::Cancelled`] once `steps` +/// answers `false`. +fn outline_seams(strokes: &mut [tr::TracedPath], budget: usize, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result { + let mut total = 0usize; + for (i, tp) in strokes.iter_mut().enumerate() { + if i % SEAM_OUTLINE_STEP == 0 && !steps(0, 0) { + return Err(EngineError::Cancelled); + } + outlined_seam(tp); + total = total.saturating_add(tp.path.anchor_count()); + if total > budget { + return Ok(false); + } + } + Ok(true) +} + +/// About how many anchors a seam stroke's outline ([`outlined_seam`]) has for each anchor of the +/// stroke: both sides of each segment and a round join at each anchor. Curves can take more. +const SEAM_OUTLINE_ANCHORS: usize = 6; + +/// Replace a seam stroke `tp` by the area it covers, as a filled path in the same raster pixels: +/// butt caps and round joins, as the strokes have. +fn outlined_seam(tp: &mut tr::TracedPath) { + if let Some(width) = tp.stroke.take() { + tp.path = vectorcraft_pathops::outline_stroke(&tp.path, width, vectorcraft_pathops::Cap::Butt, vectorcraft_pathops::Join::Round, 4.0); } - tr::seam_fills(&res.paths, params) } /// An Image Trace made away from its command, off the UI thread (#3098). [`TraceRun::prepare`] @@ -780,19 +903,12 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result Result> = seam_fills + // Abutting: the seam fills, in a clip group of their own under every path, clipped to the + // image's box within the traced paths' box: strokes, or on an image stretched more one + // way, their outlines filled. + let strokes: Vec> = seam_fills .iter() + .flat_map(|f| &f.strokes) .filter_map(|tp| { - let width = tp.stroke?; - let mut n = shape_node(d, tp.path.transformed(xf), None); - n.appearance = Appearance { - items: vec![AppearanceItem::Stroke(StrokeLayer { - cap: LineCap::Butt, - join: LineJoin::Round, - ..StrokeLayer::new(paint_of(tp), width * seam_unit) - })], - ..Default::default() + let outline = match (tp.stroke, seam_unit) { + (Some(width), Some(u)) => { + let mut n = shape_node(d, tp.path.transformed(xf), None); + n.appearance = Appearance { + items: vec![AppearanceItem::Stroke(StrokeLayer { + cap: LineCap::Butt, + join: LineJoin::Round, + ..StrokeLayer::new(paint_of(tp), width * u) + })], + ..Default::default() + } + .into(); + return Some(Arc::new(n)); + } + // The trace leaves strokes only for an image scaled alike in every direction, + // with these same inputs; a stroke is left out here rather than outlined + // outside the anchor limit. + (Some(_), None) => return None, + (None, _) => tp.path.clone(), + }; + if outline.is_empty() { + return None; } - .into(); + let mut n = shape_node(d, outline.transformed(xf), None); + n.appearance = fill_only(paint_of(tp)).into(); Some(Arc::new(n)) }) .collect(); - if !seams.is_empty() { - let mut g = Node::group(d.alloc_id(), seams); - g.name = Some(SEAM_FILLS_NAME.into()); - children.push(Arc::new(g)); - } let mut traced = Vec::with_capacity(res.paths.len()); for tp in res.paths { let paint = paint_of(&tp); @@ -873,6 +1001,23 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result = f.clip.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| xf * a.p)).collect(); + let inside = within_box(&corners, art); + if inside.len() >= 3 { + let mut clip = shape_node(d, vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&inside, true)), None); + if let NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + let members = std::iter::once(Arc::new(clip)).chain(strokes).collect(); + let mut g = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true }); + g.name = Some(SEAM_FILLS_NAME.into()); + children.push(Arc::new(g)); + } + } children.extend(grouped(d, traced, &res.parents)); if group_by_color { children = color_groups(c, d, children)?; @@ -894,6 +1039,28 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result Vec { + let sides: [&dyn Fn(Point) -> f64; 4] = [&|p| p.x - r.x0, &|p| r.x1 - p.x, &|p| p.y - r.y0, &|p| r.y1 - p.y]; + let mut out = poly.to_vec(); + for side in sides { + let corners = std::mem::take(&mut out); + for (k, &p) in corners.iter().enumerate() { + let Some(&q) = corners.get((k + 1) % corners.len()) else { continue }; + let (dp, dq) = (side(p), side(q)); + if dp >= 0.0 { + out.push(p); + } + if (dp > 0.0 && dq < 0.0) || (dp < 0.0 && dq > 0.0) { + out.push(p + (q - p) * (dp / (dp - dq))); + } + } + } + out +} + /// Images larger than this on a side are traced, but more slowly: the trace says so. pub const LARGE_TRACE_SIDE: u32 = 1500; @@ -1193,7 +1360,7 @@ mod color_group_tests { #[cfg(test)] mod trace_limit_tests { - use super::{MAX_TRACE_ANCHORS, keep_warnings, seams_within, trace_warnings}; + use super::{MAX_TRACE_ANCHORS, SEAM_CLIP_ANCHORS, SEAM_OUTLINE_ANCHORS, keep_warnings, outline_seams, seams_within, trace_warnings}; use vectorcraft_trace as tr; #[test] @@ -1206,13 +1373,89 @@ mod trace_limit_tests { }); let params = tr::TraceParams { mode: tr::Mode::Color, colors: 2, method: tr::Method::Abutting, ..tr::TraceParams::default() }; let res = tr::trace(&img, ¶ms); - let all = tr::seam_fills(&res.paths, ¶ms); - assert!(!all.is_empty(), "{res:?}"); + let all = tr::seam_fills(&res.paths, ¶ms, (24, 16)); + assert!(all.is_some(), "{res:?}"); let anchors = res.anchor_count(); - // Twice the paths' anchors leaves room for any seam fills. - assert_eq!(seams_within(&res, ¶ms, 2 * anchors), all); + assert!(anchors + all.as_ref().map_or(0, tr::SeamFills::anchor_count) <= 2 * anchors + SEAM_CLIP_ANCHORS); + let go = |_: u64, _: u64| true; + // Twice the paths' anchors and the clip's eight at most leave room for any seam fills. + assert_eq!(seams_within(&res, ¶ms, (24, 16), 2 * anchors + SEAM_CLIP_ANCHORS, false, &go).unwrap(), all); // One anchor short of that: none. - assert_eq!(seams_within(&res, ¶ms, 2 * anchors - 1), []); + assert_eq!(seams_within(&res, ¶ms, (24, 16), 2 * anchors + SEAM_CLIP_ANCHORS - 1, false, &go).unwrap(), None); + // Outlined, the seam fills are filled paths, within SEAM_OUTLINE_ANCHORS of the strokes' + // anchors each. + let strokes = |f: &tr::SeamFills| f.strokes.iter().map(|tp| tp.path.anchor_count()).sum::(); + let outlined = seams_within(&res, ¶ms, (24, 16), MAX_TRACE_ANCHORS, true, &go).unwrap().unwrap(); + assert!(outlined.strokes.iter().all(|tp| tp.stroke.is_none() && !tp.path.is_empty()), "{outlined:?}"); + let n = strokes(all.as_ref().unwrap()); + assert!(strokes(&outlined) <= SEAM_OUTLINE_ANCHORS * n, "{} outline anchors, {n} stroke anchors", strokes(&outlined)); + // A staircase edge: the outline's round joins give it more anchors than the paths have. The + // outlines are made only when SEAM_OUTLINE_ANCHORS times the strokes' anchors fit. + let img = tr::Raster::from_fn(32, 32, |x, y| if x < y / 4 * 4 + 4 { [200, 40, 50, 255] } else { [30, 90, 200, 255] }); + let params = tr::TraceParams { corners: 100.0, ..params }; + let res = tr::trace(&img, ¶ms); + let anchors = res.anchor_count(); + let all = tr::seam_fills(&res.paths, ¶ms, (32, 32)).unwrap(); + let n = strokes(&all); + let outlined = seams_within(&res, ¶ms, (32, 32), MAX_TRACE_ANCHORS, true, &go).unwrap().unwrap(); + assert!(strokes(&outlined) > anchors, "{} outline anchors, {anchors} in the paths", strokes(&outlined)); + assert!(strokes(&outlined) <= SEAM_OUTLINE_ANCHORS * n, "{} outline anchors, {n} stroke anchors", strokes(&outlined)); + let fits = anchors + SEAM_OUTLINE_ANCHORS * n + SEAM_CLIP_ANCHORS; + assert!(fits > 2 * anchors + SEAM_CLIP_ANCHORS, "{fits}, {anchors} in the paths"); + assert_eq!(seams_within(&res, ¶ms, (32, 32), fits, true, &go).unwrap(), Some(outlined.clone())); + assert_eq!(seams_within(&res, ¶ms, (32, 32), fits - 1, true, &go).unwrap(), None); + assert_eq!(seams_within(&res, ¶ms, (32, 32), fits - 1, false, &go).unwrap(), Some(all.clone())); + // The outlines are counted as each is made: they stop at the first one past the budget, so + // outlines with more anchors than the estimate allows are refused too. + let need = strokes(&outlined); + assert!(outline_seams(&mut all.strokes.clone(), need, &go).unwrap()); + assert!(!outline_seams(&mut all.strokes.clone(), need - 1, &go).unwrap()); + // Canceled while outlining: the run stops. + let stop = |_: u64, _: u64| false; + assert!(matches!(seams_within(&res, ¶ms, (32, 32), MAX_TRACE_ANCHORS, true, &stop), Err(super::EngineError::Cancelled))); + assert!(matches!(outline_seams(&mut all.strokes.clone(), need, &stop), Err(super::EngineError::Cancelled))); + } + + #[test] + fn within_box_cuts_a_turned_box_to_a_box() { + use vectorcraft_geom::{Point, Rect}; + // A square turned by 45° in a smaller box: each side cuts a corner off, 8 corners. + let diamond = [Point::new(0.0, -10.0), Point::new(10.0, 0.0), Point::new(0.0, 10.0), Point::new(-10.0, 0.0)]; + let cut = super::within_box(&diamond, Rect::new(-6.0, -6.0, 6.0, 6.0)); + assert_eq!(cut.len(), 8, "{cut:?}"); + assert!(cut.iter().all(|p| p.x.abs() <= 6.0 + 1e-12 && p.y.abs() <= 6.0 + 1e-12 && p.x.abs() + p.y.abs() <= 10.0 + 1e-12), "{cut:?}"); + // A corner on a side is kept once. + let square = [Point::new(0.0, 0.0), Point::new(4.0, 0.0), Point::new(4.0, 4.0), Point::new(0.0, 4.0)]; + assert_eq!(super::within_box(&square, Rect::new(0.0, 0.0, 4.0, 4.0)), square.to_vec()); + assert_eq!(super::within_box(&square, Rect::new(1.0, 0.0, 4.0, 4.0)).len(), 4); + assert!(super::within_box(&square, Rect::new(5.0, 5.0, 6.0, 6.0)).is_empty()); + } + + #[test] + fn seams_are_strokes_only_where_the_image_is_scaled_alike_every_way() { + use super::seam_unit; + use vectorcraft_geom::Affine; + assert_eq!(seam_unit(Affine::scale(2.0), Affine::scale(2.0)), Some(2.0)); + assert_eq!(seam_unit(Affine::new([-2.0, 0.0, 0.0, 2.0, 5.0, 7.0]), Affine::new([-2.0, 0.0, 0.0, 2.0, 5.0, 7.0])), Some(2.0)); + // Turned and scaled alike at any angle, rounding included. + for k in [0.5, 1.0, 3.0, 17.0] { + for i in 0..2000 { + let xf = Affine::rotate(f64::from(i) * std::f64::consts::TAU / 2000.0) * Affine::scale(k); + let unit = seam_unit(xf, xf); + assert!(unit.is_some_and(|u| (u - k).abs() < 1e-9 * k), "{unit:?} at step {i}, scale {k}"); + } + } + let xf = Affine::rotate(0.0496) * Affine::scale(0.5); + assert!(seam_unit(xf, xf).is_some()); + // A raster decoded scaled down to fit (10000 × 7000 pixels as 9791 × 6853) of an image placed + // at 2×: strokes, at the smaller scale. + let (sx, sy) = (10000.0 / 9791.0, 7000.0 / 6853.0); + let unit = seam_unit(Affine::scale(2.0), Affine::scale(2.0) * Affine::scale_non_uniform(sx, sy)).unwrap(); + assert!((unit - 2.0 * f64::min(sx, sy)).abs() < 1e-12, "{unit}"); + assert_eq!(seam_unit(Affine::scale_non_uniform(20.0, 1.0), Affine::scale_non_uniform(20.0, 1.0)), None); + assert_eq!(seam_unit(Affine::skew(0.5, 0.0), Affine::skew(0.5, 0.0)), None); + assert_eq!(seam_unit(Affine::scale_non_uniform(1.0, 0.0), Affine::scale_non_uniform(1.0, 0.0)), None); + assert_eq!(seam_unit(Affine::scale(0.0), Affine::scale(0.0)), None); } #[test] diff --git a/crates/engine/src/cmd/clipboard/flavours.rs b/crates/engine/src/cmd/clipboard/flavours.rs index e98dbd5619..c17d6a4428 100644 --- a/crates/engine/src/cmd/clipboard/flavours.rs +++ b/crates/engine/src/cmd/clipboard/flavours.rs @@ -173,7 +173,7 @@ pub fn specs() -> Vec { "Clipboard Formats", [], None, - "{} → {flavours: [mime…]} what Copy offers other apps for the current clipboard, best first, by the Clipboard Handling preferences: text/plain (a type-only copy's text, else the SVG markup with copyAsSvg when the images it embeds total at most 1 MiB), image/svg+xml (copyAsSvg), application/pdf (copyAsPdf), image/png (always; PDF and PNG only for objects with an area); the app publishes them on Copy and Cut", + "{} → {flavours: [mime…]} what Copy offers other apps for the current clipboard, best first, by the Clipboard Handling preferences: text/plain (a type-only copy's text, else the SVG markup with copyAsSvg when the images it embeds total at most 1 MiB), image/svg+xml (copyAsSvg), application/pdf (copyAsPdf), image/png (always; PDF and PNG only for objects with an area); under read roots, SVG and its markup as text are left out when clipboard.exportSvg would refuse; the app publishes them on Copy and Cut", always, flavours ), @@ -369,13 +369,20 @@ impl Session { /// The MIME types of [`Self::clipboard_flavours`], without making them. pub fn clipboard_flavour_types(&self) -> Vec<&'static str> { - self.clipboard.flavour_types(self.prefs.copy_as_svg, self.prefs.copy_as_pdf) + self.clipboard.flavour_types(self.clipboard_svg_offered(), self.prefs.copy_as_pdf) } /// What Copy offers other apps, best first (see `clipboard.flavours`): [`Clipboard::flavours`] - /// by the Clipboard Handling preferences. + /// by the Clipboard Handling preferences, without the SVG (and the SVG markup as text) that + /// [`Self::clipboard_svg_refused`] withholds from the caller asking now. pub fn clipboard_flavours(&self) -> Vec { - self.clipboard.flavours(self.prefs.copy_as_svg, self.prefs.copy_as_pdf) + self.clipboard.flavours(self.clipboard_svg_offered(), self.prefs.copy_as_pdf) + } + + /// Does Copy offer the SVG: Include SVG Code is on and the SVG is not withheld from the caller + /// asking now. + fn clipboard_svg_offered(&self) -> bool { + self.prefs.copy_as_svg && !self.clipboard_svg_refused() } /// Replace the clipboard with `clip`, centred on `p`'s `center` (default: the first diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index f457712415..f912fce7ae 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -595,6 +595,8 @@ struct Relink { styles: BTreeMap, /// Swatch (its name in the document) → the colour linked colours show at 100 %. colors: BTreeMap, + /// Leave graphic style links as they are ([`Clipboard::show_merged_colors`]). + keep_styles: bool, } impl Relink { @@ -674,7 +676,9 @@ impl Relink { /// Relink a node tree (the mirror of [`node_refs`]). fn node(&self, n: &mut Node) { self.appearance(&mut n.appearance); - n.extras_mut().graphic_style = n.extras().graphic_style.and_then(|id| self.styles.get(&id).copied()); + if !self.keep_styles { + n.extras_mut().graphic_style = n.extras().graphic_style.and_then(|id| self.styles.get(&id).copied()); + } if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) { self.node(Arc::make_mut(&mut m.art)); } @@ -699,7 +703,7 @@ impl Relink { self.name(Res::ParaStyle, s); } } - for r in [&mut l.values_rows, &mut l.categories_rows, &mut l.legend_rows].into_iter().flatten() { + for r in [&mut l.values_rows, &mut l.categories_rows, &mut l.legend_rows, &mut l.axis_rows, &mut l.ring_rows].into_iter().flatten() { r.paint.fill.iter_mut().chain(r.paint.stroke.iter_mut()).for_each(|p| self.paint(p)); } } @@ -762,6 +766,8 @@ pub struct SymbolOptions { pub export_type: SymbolExportType, /// 9-slice guides (`None`: 9-slice scaling off). pub nine_slice: Option, + /// Align to Pixel Grid. + pub pixel_aligned: bool, } impl SymbolOptions { @@ -772,6 +778,7 @@ impl SymbolOptions { registration: d.symbol_registration(name), export_type: d.symbol_export_type(name), nine_slice: d.symbol_nine_slice(name), + pixel_aligned: d.symbol_pixel_aligned(name), } } @@ -781,6 +788,7 @@ impl SymbolOptions { d.set_symbol_registration(name, self.registration); d.set_symbol_export_type(name, self.export_type); d.set_symbol_nine_slice(name, self.nine_slice); + d.set_symbol_pixel_aligned(name, self.pixel_aligned); } } @@ -1031,10 +1039,13 @@ impl Imported { self.relink.renames.entry(r).or_default().insert(from.to_string(), to.clone()); } } - /// Point a pasted copy at the document's resources. + /// Point a pasted copy at the document's resources. A pie's legend labels in wedges that now show a color of the + /// other darkness take the contrast a redraw sets there. pub(crate) fn apply(&self, n: &mut Node) { if self.relinks { + let shades = super::super::graph::wedge_shades(n); self.relink.node(n); + super::super::graph::follow_wedge_shades(n, &shades); } } } @@ -1109,6 +1120,30 @@ impl Clipboard { self.import_used(d, &self.used(), choices, same_doc) } + /// Give the objects' colors linked to a global or spot swatch whose conflict with `d` + /// `choices` merge the color that swatch has in `d`, as pasting into `d` gives them (Paste + /// without Formatting sets its pie legend labels' contrast from the wedge colors before it + /// pastes). Nothing changes for the document the objects came from (`same_doc`). + pub(crate) fn show_merged_colors(&mut self, d: &Document, choices: &SwatchChoices, same_doc: bool) { + if same_doc { + return; + } + let used = self.used(); + let colors: BTreeMap = self + .conflicts(d, &used) + .into_iter() + .filter(|(w, _)| choices.of(&w.name) == SwatchChoice::Merge) + .filter_map(|(w, _)| d.global_color(&w.name).map(|c| (w.name.clone(), c))) + .collect(); + if colors.is_empty() { + return; + } + let relink = Relink { colors, keep_styles: true, ..Default::default() }; + for n in &mut self.nodes { + relink.node(n); + } + } + /// [`Self::import_into`] for the resources `used` names. Each style, symbol, pattern and brush /// comes after the styles, symbols, patterns and brushes it uses ([`use_order`]), so that it is /// compared and relinked with their names here, and each loop of definitions that use each diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 8377822094..a9dee00af3 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Invert Colors", ["Edit", "Edit Colors"], None, - "{fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?} replace each colour by its RGB inverse (keeps the colour model) in fills, strokes, text, gradient meshes (with fills), colorized image fills (their pixels stay unchanged), other embedded images (a recoloured copy) and pattern tiles (a new pattern swatch; the original stays), as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed, notChanged: {locked, hidden} (when the selection is everything select.all takes: the locked and hidden objects it left out whose colors would have changed; an object both hidden and locked counts as hidden), warning?: set when notChanged counts any object}", + "{fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?} replace each colour by its RGB inverse (keeps the colour model) in fills, strokes, text, gradient meshes (with fills), colorized image fills (their pixels stay unchanged), other embedded images (a recoloured copy) and pattern tiles (a new pattern swatch; the original stays), as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, notChanged: {locked, hidden} (when the selection is everything select.all takes: the locked and hidden objects it left out whose colors would have changed; an object both hidden and locked counts as hidden), warning?: set when notChanged counts any object}", has_selection, |s, p| recolor(s, p, "edit.colors.invert", "Invert Colors", &invert) ), @@ -221,6 +221,8 @@ pub(crate) struct Recolor<'a> { patterns: HashMap>, new_images: Vec<(String, ImageBlob)>, new_patterns: Vec, + /// Objects inside the recolored ones that keep their colors, with everything inside them. + skip: HashSet, changed: usize, } @@ -236,6 +238,7 @@ impl<'a> Recolor<'a> { patterns: HashMap::new(), new_images: vec![], new_patterns: vec![], + skip: HashSet::new(), changed: 0, } } @@ -254,7 +257,7 @@ impl<'a> Recolor<'a> { /// A pass that maps colors as this one does, with nothing recolored yet. fn again(&self) -> Self { - Self { links: self.links, gray_images: self.gray_images, remake: self.remake, ..Self::new(self.scope, self.f) } + Self { links: self.links, gray_images: self.gray_images, remake: self.remake, skip: self.skip.clone(), ..Self::new(self.scope, self.f) } } /// The entries of `objects` (ids, each with a flag) whose object this pass would change, other @@ -440,12 +443,20 @@ impl ColorVisitor for Visit<'_, '_> { fn image(&mut self, key: &str) -> Option { self.pass.image(self.d, key) } + fn enters(&mut self, n: &Node) -> bool { + !self.pass.skip.contains(&n.id) + } } pub(crate) fn recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result { run_pass(s, p, cmd, label, Recolor::new(Scope::of(p, cmd)?, f)) } +/// [`recolor`] that leaves the objects `skip` inside the recolored ones, and everything inside them, as they are. +pub(crate) fn recolor_except(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color, skip: HashSet) -> Result { + run_pass(s, p, cmd, label, Recolor { skip, ..Recolor::new(Scope::of(p, cmd)?, f) }) +} + /// [`recolor`] where `f` gives gray colors, so embedded images are stored with one gray channel. fn recolor_gray(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result { run_pass(s, p, cmd, label, Recolor { gray_images: true, ..Recolor::new(Scope::of(p, cmd)?, f) }) @@ -522,7 +533,7 @@ pub(crate) fn keeping_series_paint(d: &mut Document, roots: &[NodeId], recolor: let n = recolor(d)?; if let Some(before) = before.filter(|_| n > 0) { super::appearance::capture_series_changes(&before, d, &marks); - super::graph::capture_label_changes(&before, d, &labels, true); + super::graph::capture_label_changes(&before, d, &labels, true, Some(roots)); } Ok(n) } diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index d863edb96d..a529a3bea9 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -803,8 +803,8 @@ fn map_effect_colors(a: &mut vectorcraft_doc::Appearance, f: &mut dyn FnMut(&Col } } -/// `f` applied to the series paints and the label styles that graph `g` keeps, which its marks and -/// labels take each time it is drawn again. +/// `f` applied to the series paints, the label styles and the line rows that graph `g` keeps, which +/// its marks, labels and lines take each time it is drawn again. fn map_graph_colors(g: &mut vectorcraft_doc::GraphSpec, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { for p in g.series_paints.iter_mut() { for paint in [&mut p.fill, &mut p.stroke].into_iter().flatten() { @@ -823,7 +823,10 @@ fn map_graph_colors(g: &mut vectorcraft_doc::GraphSpec, f: &mut dyn FnMut(&Color } map_paint_colors(&mut st.stroke, f); } - for r in [&mut styles.values_rows, &mut styles.categories_rows, &mut styles.legend_rows].into_iter().flatten() { + for r in [&mut styles.values_rows, &mut styles.categories_rows, &mut styles.legend_rows, &mut styles.axis_rows, &mut styles.ring_rows] + .into_iter() + .flatten() + { for paint in [&mut r.paint.fill, &mut r.paint.stroke].into_iter().flatten() { map_paint_colors(paint, f); } diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 9c6e042e9e..e94858b966 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -26,7 +26,7 @@ pub fn specs() -> Vec { "Ellipse", [], None, - "{x, y, width, height, rotation?: deg clockwise about the centre (0: upright)} → {id}", + "{x, y, width, height, rotation?: deg clockwise about the centre (0: upright), anchors=4 (2–1000: smooth anchors spaced evenly by angle; any count but 4 draws a plain path, not a live ellipse)} → {id}", has_doc, ellipse ), @@ -383,10 +383,28 @@ fn rectangle(s: &mut Session, p: &Value) -> Result { add_art_turned(s, label, path_kind(live.to_path(), Some(live)), f64_or(p, "rotation", 0.0)) } +/// The most anchors `shape.ellipse` draws, as many as a polygon's sides. +const MAX_ELLIPSE_ANCHORS: u64 = 1000; + fn ellipse(s: &mut Session, p: &Value) -> Result { let r = rect_of(p, "shape.ellipse")?; - let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: rect_transform(r, p, "shape.ellipse")? }; - add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), f64_or(p, "rotation", 0.0)) + // One message for every number that is not a whole count in range (a fraction, a negative, + // 0, 1, too many); a value that is not a number gets `number_or`'s. + let (key, min, max) = ("anchors", 2, MAX_ELLIPSE_ANCHORS); + let n = number_or(p, key, 4.0, "shape.ellipse")?; + if n.fract() != 0.0 || !(min as f64..=max as f64).contains(&n) { + return Err(bad("shape.ellipse", format!("`{key}` must be a whole number between {min} and {max} (got {n})"))); + } + let x = n as u64; + let xf = rect_transform(r, p, "shape.ellipse")?; + let rotation = f64_or(p, "rotation", 0.0); + if x != 4 { + // Another count is a plain path: a live ellipse always has 4 anchors. + let path = shapes::ellipse_with_anchors(Rect::new(0.0, 0.0, r.width(), r.height()), x as u32).transformed(xf); + return add_art_turned(s, "Ellipse", path_kind(path, None), rotation); + } + let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf }; + add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), rotation) } /// A live ellipse whose edge passes through three points: `points`, or the three selected anchor @@ -950,7 +968,8 @@ pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str, t: &mut TextObject) /// The character style new type gets: `size`, `font`, `style` and `color` from `p` (an RGB /// `color` in a CMYK document as [`super::paint::new_color`] stores it), else the defaults, -/// filled with the current fill unless that is None or white (black then), in the document's +/// filled as `[Normal Character Style]` is (black unless redefined; never the current fill, +/// #7975), in the document's /// language. A `size` outside [`super::typecmd::TYPE_SIZES`] is an error. pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result { let mut style = CharStyle::default(); @@ -968,8 +987,7 @@ pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result vectorcraft_color::Paint::solid(super::paint::new_color(s, p, c)), - None if !s.paint.fill.is_none() && s.paint.fill != vectorcraft_color::Paint::solid(vectorcraft_color::Color::WHITE) => s.paint.fill.clone(), - None => vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), + None => s.doc().map_or_else(|_| CharStyle::default().fill, |d| super::textstyles::normal_char_fill(&d.doc)), }; // In the language Document Setup chose, else Preferences › Hyphenation › Default Language; none // for the default. Type already in a document keeps its own. diff --git a/crates/engine/src/cmd/distortcmds.rs b/crates/engine/src/cmd/distortcmds.rs index 8f1b5b97e6..1e78f210e6 100644 --- a/crates/engine/src/cmd/distortcmds.rs +++ b/crates/engine/src/cmd/distortcmds.rs @@ -631,13 +631,12 @@ impl LiquifyStroke { } let msg = (!ids.is_empty()).then(|| { let n = ids.len(); - format!( - "{} left {n} object{} under the brush as {} ({}): it reshapes paths only", - self.prm.kind.label(), - if n == 1 { "" } else { "s" }, - if n == 1 { "it was" } else { "they were" }, - kinds.join(", ") - ) + let (tool, kinds) = (self.prm.kind.label(), kinds.join(", ")); + if n == 1 { + format!("{tool} left {n} object under the brush as it was ({kinds}): it reshapes paths only") + } else { + format!("{tool} left {n} objects under the brush as they were ({kinds}): it reshapes paths only") + } }); (ids, msg) } diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index b5ac1c13e5..c7421ac391 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -857,14 +857,12 @@ mod tests { let mut s = Session::new(); s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); let r = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); - s.execute( - "paint.setFill", - &json!({"gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}}), - ) - .unwrap(); + let gradient = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}); + s.execute("paint.setFill", &json!({"gradient": gradient})).unwrap(); let t = s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi"})).unwrap()["id"].clone(); + // New type starts black (#7975); filled with the gradient, its characters make it a gradient object too. + s.execute("paint.setFill", &json!({"gradient": gradient, "ids": [t]})).unwrap(); let i = s.execute("document.info", &json!({})).unwrap(); - // The type's characters take the current gradient fill, so it is a gradient object too. assert_eq!( (i["objects"]["paths"].as_u64(), i["objects"]["textObjects"].as_u64(), i["objects"]["gradients"].as_u64()), (Some(1), Some(1), Some(2)) @@ -1500,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)); @@ -1657,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/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index 3b1e8a7666..9404dcc0c7 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -270,6 +270,33 @@ pub fn specs() -> Vec { has_doc, super::fileinfo::file_info ), + cmd!( + "file.info.saveTemplate", + "Save Metadata Template…", + [], + None, + "{name?: save into the metadata templates folder as .xmp (a name with characters file systems reject, a dot at either end, or a device name is an error (spaces at either end are dropped); the same name replaces that template), path?: save to this file instead (not both), fields?: {File Info fields as file.info takes them} save these instead of the document's (default: the document's File Info)} write the File Info as an XMP metadata template: title (only one of its own, not Untitled-N), author, authorTitle, description, keywords, rating (1–5), copyrightStatus, copyrightNotice and copyrightUrl, each where it has a value; the dates are left out → {name, path} (with name), {path} (with path), or {data: the XMP text} with neither", + has_doc, + super::fileinfo::save_template + ), + cmd!( + "file.info.applyTemplate", + "Import Metadata Template…", + [], + None, + "{path?: an XMP file, name?: a template of the metadata templates folder by the name or file file.info.templates lists, data?: XMP text (exactly one of the three; at most 8 MB), mode: \"replace\" (clear the author, authorTitle, description, keywords, rating, copyright status, notice and URL, then take the template's; the title stays unless the template has one) | \"keep\" (keep the File Info, and take each field the template has) | \"append\" (keep the File Info, add the template's keywords, and take its other fields only where the File Info has none: a title only over an Untitled-N one, a rating only over 0, a copyright status only over unknown), apply?: true (false: change nothing and return the merged File Info), base?: {File Info fields as file.info takes them} merged into instead of the document's} merge a metadata template into the File Info in one undo step, none when nothing changes; a template value file.info would refuse is left out; a missing file, a file larger than 8 MB or one that is not XMP is an error → the File Info as file.info reports it, with changed: true|false (with apply: false, the merged File Info without changed)", + has_doc, + super::fileinfo::apply_template + ), + cmd!( + query "file.info.templates", + "Metadata Templates", + [], + None, + "{create?: false (true: make the folder when it is missing)} the metadata templates in the metadata templates folder next to the preferences, sorted by name, at most 1,000 → {templates: [{name, file: the file name, path}], folder?: the folder (left out for a request that may not read it, in runs without preferences and on the web, where the list is empty)}", + super::always, + super::fileinfo::templates + ), ] } diff --git a/crates/engine/src/cmd/draw2.rs b/crates/engine/src/cmd/draw2.rs index 9055e83844..63ae0a3e4c 100644 --- a/crates/engine/src/cmd/draw2.rs +++ b/crates/engine/src/cmd/draw2.rs @@ -31,6 +31,6 @@ mod freehand; mod smooth; pub use commands::specs; -pub(super) use common::{ids_json, replace_with_pieces, usize_opt}; +pub(super) use common::{center_strokes, ids_json, replace_with_pieces, usize_opt}; pub(super) use cut::{components, erase_outline}; pub(super) use freehand::freehand_brushed; diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 49e277e5a0..b9015a4cc7 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -11,7 +11,7 @@ pub fn specs() -> Vec { "Pencil", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it", has_doc, freehand ), @@ -74,7 +74,7 @@ pub fn specs() -> Vec { "Split Path", [], None, - "{id, subpath?, segment, t} or {id, subpath?, anchor}: closed paths open there, open paths become two; one of the two new end points is left selected → {ids}", + "{id, subpath?, segment, t: 0–1 (0.5)} or {id, subpath?, anchor}: closed paths open there, open paths become two; one of the two new end points is left selected; the paths keep the source's fill and stroke settings except that every stroke's alignment becomes Center (in a path of several subpaths, the other subpaths' strokes too) → {ids}. A t outside 0–1 is refused with an error, and nothing changes", has_doc, split ), @@ -83,7 +83,7 @@ pub fn specs() -> Vec { "Knife", [], None, - "{points: [[x,y]…]} cut closed shapes (selected, or all when nothing is selected) along the polyline → {ids}", + "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the cut)} cut closed shapes (selected, or all when nothing is selected) along the polyline → {ids}", has_doc, knife ), @@ -92,7 +92,7 @@ pub fn specs() -> Vec { "Eraser", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation ° clockwise, as path.freehand), size?: pt (10), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0 or more, default 0)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from level), roundness?: % (100, 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An angle or roundness outside its range, an unknown mode, or a variation below 0 or past its range is refused with an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths lose its area, and open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added", has_doc, erase_region ), @@ -101,7 +101,7 @@ pub fn specs() -> Vec { "Path Eraser", [], None, - "{points: [[x,y]…], width?: pt (8)} erase the parts of selected paths under the drag → {ids}", + "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change what is erased), width?: pt (8)} erase the parts of selected paths under the drag → {ids}", has_selection, erase_segments ), @@ -110,7 +110,7 @@ pub fn specs() -> Vec { "Smooth", [], None, - "{points: [[x,y]…], radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}", + "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}", has_selection, smooth_region ), @@ -119,7 +119,7 @@ pub fn specs() -> Vec { "Join", [], None, - "{points: [[x,y]…], tolerance?: pt (12)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}", + "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the join), tolerance?: pt (12)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}", has_doc, join_scrub ), @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "Blob Brush", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1), size?: pt (10), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0), angle?: ° (0, kept within −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, kept within 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}", + "{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0; from 0 to 1000, checked with Fixed too), angle?: ° (0, kept within −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, kept within 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}", has_doc, blob ), diff --git a/crates/engine/src/cmd/draw2/common.rs b/crates/engine/src/cmd/draw2/common.rs index fd8967f3fa..bf52f580e7 100644 --- a/crates/engine/src/cmd/draw2/common.rs +++ b/crates/engine/src/cmd/draw2/common.rs @@ -28,6 +28,27 @@ pub(super) struct Sample { /// x and y. const PEN_KEYS: [&str; 4] = ["pressure", "tiltX", "tiltY", "rotation"]; +/// The range each of [`PEN_KEYS`] takes: pressure 0..1, each tilt −90..90 degrees and rotation +/// 0..360 degrees (360 is the same direction as 0). +const PEN_RANGES: [(f64, f64); PEN_KEYS.len()] = [(0.0, 1.0), (-90.0, 90.0), (-90.0, 90.0), (0.0, 360.0)]; + +/// Blob Brush and Eraser Tool Options' Size, in points. +pub(super) const SIZES: (f64, f64) = (0.1, 1000.0); + +/// Blob Brush and Eraser Tool Options' Size Variation, in points. +pub(super) const SIZE_VARIATIONS: (f64, f64) = (0.0, 1000.0); + +/// `v`, or an error naming `key` when it is outside `lo..=hi` (or not a number at all, NaN). +fn within(v: f64, key: &str, (lo, hi): (f64, f64), cmd: &str) -> Result { + if (lo..=hi).contains(&v) { Ok(v) } else { Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))) } +} + +/// The number `p` gives for `key`, `default` when it leaves it out or gives null, as [`number_or`] +/// reads it, or an error naming `key` when the number is outside `range`. +pub(super) fn ranged(p: &Value, key: &str, default: f64, range: (f64, f64), cmd: &str) -> Result { + within(number_or(p, key, default, cmd)?, key, range, cmd) +} + /// The point `[x, y, …]` or `{x, y, …}` that `v` holds, or an error when its x or y is not a finite /// number. pub(super) fn point_entry(v: &Value, cmd: &str) -> Result { @@ -42,27 +63,36 @@ pub(super) fn point_entry(v: &Value, cmd: &str) -> Result { /// [`points_param`] with what a pen read at each point, as far as it is given: /// `[[x,y,pressure,tiltX,tiltY,rotation]…]` or `[{x,y,pressure,tiltX,tiltY,rotation}…]`. Pressure /// is 0..1; tilt in degrees, each −90..90 (one of the two without the other is 0); rotation in -/// degrees clockwise. A point whose x or y is not a number, or whose pressure, tilt or rotation is -/// neither a number nor null, is an error. +/// degrees clockwise, 0..360. A point whose x or y is not a number, whose pressure, tilt or +/// rotation is neither a number nor null or is outside its range, or an array of more than six +/// numbers, is an error. pub(super) fn samples_param(p: &Value, key: &str, cmd: &str) -> Result> { let a = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("missing array `{key}`")))?; let pts: Vec = a .iter() - .map(|v| { + .enumerate() + .map(|(at, v)| { + const MAX_ITEMS: usize = 2 + PEN_KEYS.len(); + if let Value::Array(xy) = v + && xy.len() > MAX_ITEMS + { + let key = format!("{key}[{at}]"); + return Err(bad(cmd, format!("`{key}` must be an array of at most {MAX_ITEMS} entries"))); + } let mut pen = [None; 4]; - for (i, (key, slot)) in PEN_KEYS.iter().zip(&mut pen).enumerate() { + for (i, ((key, range), slot)) in PEN_KEYS.iter().zip(PEN_RANGES).zip(&mut pen).enumerate() { let given = match v { Value::Array(xy) => xy.get(i + 2), _ => v.get(*key), }; *slot = match given { None | Some(Value::Null) => None, - Some(n @ Value::Number(_)) => n.as_f64(), + Some(n @ Value::Number(_)) => n.as_f64().map(|x| within(x, key, range, cmd)).transpose()?, Some(v) => return Err(bad(cmd, format!("`{key}` must be a number, not {v}"))), }; } let [pressure, tx, ty, rotation] = pen; - let tilt = (tx.is_some() || ty.is_some()).then(|| [tx, ty].map(|t| t.unwrap_or(0.0).clamp(-90.0, 90.0))); + let tilt = (tx.is_some() || ty.is_some()).then(|| [tx, ty].map(|t| t.unwrap_or(0.0))); Ok(Sample { pt: point_entry(v, cmd)?, pressure, tilt, rotation }) }) .collect::>()?; @@ -186,18 +216,14 @@ impl PenRecord { } /// Blob Brush and Eraser Tool Options' Size set to Pressure (`sizeMode: "pressure"`, with -/// `sizeVariation` in points): the stroke's pen pressure along it and the variation, `None` for -/// Fixed (the default), no variation or a stroke without pressure (a mouse), which keeps the size. +/// `sizeVariation` in points, 0..1000): the stroke's pen pressure along it and the variation, `None` +/// for Fixed (the default), no variation or a stroke without pressure (a mouse), which keeps the +/// size. A `sizeVariation` outside its range is an error with Fixed too. pub(super) fn size_pressure(p: &Value, samples: &[Sample], cmd: &str) -> Result> { + let variation = ranged(p, "sizeVariation", 0.0, SIZE_VARIATIONS, cmd)?; match p.get("sizeMode").filter(|v| !v.is_null()).map(|v| v.as_str().ok_or(v)) { None | Some(Ok("fixed")) => Ok(None), - Some(Ok("pressure")) => { - let variation = number_or(p, "sizeVariation", 0.0, cmd)?; - if !(variation.is_finite() && variation >= 0.0) { - return Err(bad(cmd, "sizeVariation must be 0 or more")); - } - Ok(stroke_pressure(samples).filter(|_| variation > 0.0).map(|prof| (prof, variation))) - } + Some(Ok("pressure")) => Ok(stroke_pressure(samples).filter(|_| variation > 0.0).map(|prof| (prof, variation))), Some(Ok(other)) => Err(bad(cmd, format!("sizeMode is \"fixed\" or \"pressure\", not `{other}`"))), Some(Err(other)) => Err(bad(cmd, format!("sizeMode is \"fixed\" or \"pressure\", not {other}"))), } @@ -380,6 +406,26 @@ pub(super) fn sibling_with(d: &mut Document, id: NodeId, pd: PathData) -> Result Ok(n) } +/// Set every stroke of node `id`, and every stroke of the compound path it is a member of (whose +/// strokes its members show), to Center alignment. Every other stroke and fill setting stays as it +/// is, and an appearance whose strokes are all centered stays shared with its other copies. +pub(in super::super) fn center_strokes(d: &mut Document, id: NodeId) { + use vectorcraft_doc::{AppearanceItem, StrokeAlign}; + let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); + for n in [Some(id), parent].into_iter().flatten() { + let Some(n) = d.node_mut(n) else { continue }; + let off = |it: &AppearanceItem| matches!(it, AppearanceItem::Stroke(st) if st.align != StrokeAlign::Center); + if !n.appearance.items.iter().any(off) { + continue; + } + for it in &mut n.appearance.items { + if let AppearanceItem::Stroke(st) = it { + st.align = StrokeAlign::Center; + } + } + } +} + /// Replace path or compound path `id` with `pieces` (first keeps the id, the rest go right above /// it; none removes it). `cut` removes the path or puts the other pieces above it. Returns ids. pub(in super::super) fn replace_with_pieces(d: &mut Document, cut: &mut Beside, id: NodeId, pieces: Vec) -> Result> { diff --git a/crates/engine/src/cmd/draw2/cut.rs b/crates/engine/src/cmd/draw2/cut.rs index 64b8bdee16..40a4c74d79 100644 --- a/crates/engine/src/cmd/draw2/cut.rs +++ b/crates/engine/src/cmd/draw2/cut.rs @@ -1,11 +1,12 @@ use super::common::{ - PenRecord, Sample, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds, pressure_region, replace_with_pieces, - samples_param, sibling_with, size_pressure, target_paths, usize_opt, + PenRecord, SIZE_VARIATIONS, SIZES, Sample, center_strokes, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, + poly_bounds, pressure_region, ranged, replace_with_pieces, samples_param, sibling_with, size_pressure, target_paths, usize_opt, }; use super::{ - Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Result, Session, + Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Rect, Result, Session, SubPath, Value, Vec2, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po, }; +use kurbo::{CubicBez, Line, PathSeg}; use vectorcraft_brush::{Brush, BrushKind, Calligraphic, Variation}; use vectorcraft_doc::StrokeLayer; use vectorcraft_tools::draw2::MIN_BRUSH_SIZE; @@ -46,8 +47,8 @@ pub(in super::super) fn components(pd: &PathData) -> Vec { /// The pieces of `sp` where `remove(point)` is false. `None` when nothing is removed. Each segment /// is sampled at least every `step` pt (and at least 24 times), so a removed stretch at least -/// `step` long is found. -fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Option> { +/// `step` long is found, and also at the parameters `extra` gives for it. +fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool, extra: &dyn Fn(CubicBez) -> Vec) -> Option> { let nseg = sp.segment_count(); if nseg == 0 { return sp.anchors.first().filter(|a| remove(a.p)).map(|_| vec![]); @@ -64,6 +65,13 @@ fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Optio let edge = (c.p1 - c.p0).hypot().max((c.p2 - c.p1).hypot()).max((c.p3 - c.p2).hypot()); let wanted = (3.0 * edge / step).ceil(); let samples = if wanted.is_finite() && wanted > K as f64 { (wanted as usize).min(MAX_SAMPLES) } else { K }; + let mut ts: Vec = (1..=samples).map(|k| k as f64 / samples as f64).collect(); + let more = extra(c); + if !more.is_empty() { + ts.extend(more.into_iter().filter(|t| t.is_finite() && *t > 0.0 && *t < 1.0)); + ts.sort_by(f64::total_cmp); + ts.dedup(); + } let mut prev_t = 0.0; let mut prev_rm = remove(c.eval(0.0)); let mut start = if prev_rm { None } else { Some(0.0) }; @@ -73,8 +81,7 @@ fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Optio runs.push(std::mem::take(&mut cur)); } } - for k in 1..=samples { - let t = k as f64 / samples as f64; + for t in ts { let rm = remove(c.eval(t)); if rm != prev_rm { let (mut lo, mut hi) = (prev_t, t); @@ -146,10 +153,15 @@ fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Optio /// every `step` pt (`f64::INFINITY` for the fixed sampling). Returns the new geometry per output /// object (one object per piece when the path had a single subpath), or None if unchanged. pub(in super::super) fn erase_outline(pd: &PathData, step: f64, remove: &dyn Fn(Point) -> bool) -> Option> { + erase_outline_at(pd, step, remove, &|_| vec![]) +} + +/// [`erase_outline`], also sampling each segment at the parameters `extra` gives for it. +fn erase_outline_at(pd: &PathData, step: f64, remove: &dyn Fn(Point) -> bool, extra: &dyn Fn(CubicBez) -> Vec) -> Option> { let mut changed = false; let mut subs = vec![]; for sp in &pd.subpaths { - match cut_subpath(sp, step, remove) { + match cut_subpath(sp, step, remove, extra) { Some(pieces) => { changed = true; subs.extend(pieces); @@ -184,6 +196,9 @@ pub(super) fn split(s: &mut Session, p: &Value) -> Result { if !t.is_finite() || p.get("t").is_some_and(|v| !v.is_f64() && !v.is_i64() && !v.is_u64()) { return Err(bad(C, "invalid t")); } + if !(0.0..=1.0).contains(&t) { + return Err(bad(C, "`t` must be from 0 to 1")); + } let ids = s.edit("Split Path", |d, sel| { let path = path_mut(d, id)?; let mut sp = path.subpaths.get(si).cloned().ok_or_else(|| EngineError::Other("no such subpath".into()))?; @@ -210,14 +225,17 @@ pub(super) fn split(s: &mut Session, p: &Value) -> Result { sel.add(id); sel.anchors.entry(id).or_default().insert((si, 0)); }; + // The paths a cut makes keep the source's appearance with every stroke centered. if sp.closed { path.subpaths[si] = pieces.pop().ok_or_else(|| EngineError::Other("no such anchor".into()))?; + center_strokes(d, id); pick(sel, id, si); return Ok(vec![id]); } let [left, right] = <[SubPath; 2]>::try_from(pieces).map_err(|_| EngineError::Other("cannot split an open path at its end point".into()))?; if path.subpaths.len() == 1 { path.subpaths[0] = left; + center_strokes(d, id); let node = sibling_with(d, id, PathData::single(right))?; let (parent, idx, _) = d.position(id).ok_or(EngineError::NoNode(id))?; let nid = d.insert(parent, idx + 1, node)?; @@ -226,6 +244,7 @@ pub(super) fn split(s: &mut Session, p: &Value) -> Result { } else { path.subpaths[si] = left; path.subpaths.insert(si + 1, right); + center_strokes(d, id); pick(sel, id, si + 1); Ok(vec![id]) } @@ -274,13 +293,22 @@ pub(super) fn knife(s: &mut Session, p: &Value) -> Result { pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result { const C: &str = "path.eraseRegion"; - let samples = samples_param(p, "points", C)?; - let size = number_or(p, "size", 10.0, C)?; - if !(size.is_finite() && size > 0.0) { - return Err(bad(C, "size must be positive")); + if let Some(rect) = p.get("rect").filter(|v| !v.is_null()) { + if p.get("points").is_some_and(|v| !v.is_null()) { + return Err(bad(C, "give `points` or `rect`, not both")); + } + return erase_rect(s, marquee_param(rect, C)?); } + let samples = samples_param(p, "points", C)?; + let size = ranged(p, "size", 10.0, SIZES, C)?; let angle = number_or(p, "angle", 0.0, C)?; + if !(-180.0..=180.0).contains(&angle) { + return Err(bad(C, "`angle` must be from -180 to 180 degrees")); + } let roundness = number_or(p, "roundness", 100.0, C)?; + if !(1.0..=100.0).contains(&roundness) { + return Err(bad(C, "`roundness` must be from 1 to 100%")); + } let vary = eraser_variations(p, C)?; if varies_beyond_size_pressure(&vary) { return erase_varied(s, &samples, [angle, roundness, size], vary); @@ -290,7 +318,7 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result { let r = size / 2.0; // The tip's short axis (its narrowest with Pressure): an open path is sampled at least every half of it. let narrowest = pressure.as_ref().map_or(size, |(_, v)| vectorcraft_tools::draw2::pressure_size(size, *v, 0.0)); - let short = narrowest * roundness.clamp(1.0, 100.0) / 100.0; + let short = narrowest * roundness / 100.0; let st = s.doc()?; // A point is under the tip when, with the tip squashed back into a circle, it is within the // circle's radius of the squashed drag. @@ -325,18 +353,71 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result { apply_plan(s, "Eraser", plan) } +/// `path.eraseRegion`'s `rect: [x, y, width, height]`: four finite numbers, with a width and a +/// height above 0. +fn marquee_param(v: &Value, cmd: &str) -> Result { + const SHAPE: &str = "rect is [x, y, width, height] in points, with a width and a height above 0"; + let n: Vec = match v.as_array() { + Some(a) if a.len() == 4 => a.iter().map(Value::as_f64).collect::>().ok_or_else(|| bad(cmd, SHAPE))?, + _ => return Err(bad(cmd, SHAPE)), + }; + let [x, y, w, h] = [n[0], n[1], n[2], n[3]]; + if !(n.iter().all(|v| v.is_finite()) && w > 0.0 && h > 0.0 && (x + w).is_finite() && (y + h).is_finite()) { + return Err(bad(cmd, SHAPE)); + } + Ok(Rect::new(x, y, x + w, y + h)) +} + +/// `path.eraseRegion` with a marquee: everything inside `r` is erased from the paths (selected, or +/// all). Closed paths lose the rectangle's area, and open paths are cut where they cross its edges. +fn erase_rect(s: &mut Session, r: Rect) -> Result { + let region = + PathData::single(SubPath::polyline(&[Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)], true)); + let inside = |q: Point| q.x >= r.x0 && q.x <= r.x1 && q.y >= r.y0 && q.y <= r.y1; + // An open path is sampled at least every half of the rectangle's shorter side, and also where + // each segment crosses the rectangle's edges and halfway between those crossings, so a stretch + // inside the rectangle is found however long the segment is. + let step = r.width().min(r.height()) / 2.0; + let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]; + let crossings = |c: CubicBez| { + let mut ts: Vec = (0..4) + .flat_map(|k| PathSeg::Cubic(c).intersect_line(Line::new(corners[k], corners[(k + 1) % 4]))) + .map(|x| x.segment_t) + .filter(|t| t.is_finite() && *t > 0.0 && *t < 1.0) + .collect(); + ts.sort_by(f64::total_cmp); + let mids: Vec = [0.0].iter().chain(&ts).zip(ts.iter().chain(&[1.0])).map(|(a, b)| 0.5 * (a + b)).collect(); + ts.extend(mids); + ts + }; + let st = s.doc()?; + let mut plan: Vec<(NodeId, Vec)> = vec![]; + for (id, pd, rule) in fill_targets(&st.doc, &st.selection, r)? { + if pd.is_closed() { + if po::area(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 { + continue; + } + plan.push((id, components(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Difference)))); + } else if let Some(pieces) = erase_outline_at(&pd, step, &inside, &crossings) { + plan.push((id, pieces)); + } + } + apply_plan(s, "Eraser", plan) +} + /// The variation modes `path.eraseRegion` takes for each of `angleMode`, `roundnessMode` and /// `sizeMode`. const ERASER_MODES: &str = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\" or \"rotation\""; /// Eraser Tool Options' Angle, Roundness and Size variations: for each of angle (`angleMode` with /// `angleVariation` in degrees, at most 180), roundness (`roundnessMode` with `roundnessVariation` -/// in percent, at most 100) and size (`sizeMode` with `sizeVariation` in points), its mode and how -/// far it varies either way. A mode left out or null is Fixed, and a variation left out or null -/// is 0; any other mode, or a variation that is negative or past its most, is refused. +/// in percent, at most 100) and size (`sizeMode` with `sizeVariation` in points, at most 1000), its +/// mode and how far it varies either way. A mode left out or null is Fixed, and a variation left +/// out or null is 0; any other mode, or a variation that is negative or past its most, is refused, +/// in every mode. fn eraser_variations(p: &Value, cmd: &str) -> Result<[(Variation, f64); 3]> { const KEYS: [(&str, &str, f64); 3] = - [("angleMode", "angleVariation", 180.0), ("roundnessMode", "roundnessVariation", 100.0), ("sizeMode", "sizeVariation", f64::INFINITY)]; + [("angleMode", "angleVariation", 180.0), ("roundnessMode", "roundnessVariation", 100.0), ("sizeMode", "sizeVariation", SIZE_VARIATIONS.1)]; let mut out = [(Variation::Fixed, 0.0); 3]; for (slot, (mode_key, var_key, most)) in out.iter_mut().zip(KEYS) { let mode = match p.get(mode_key).filter(|v| !v.is_null()) { @@ -349,7 +430,11 @@ fn eraser_variations(p: &Value, cmd: &str) -> Result<[(Variation, f64); 3]> { return Err(bad(cmd, format!("{var_key} must be 0 or more"))); } if variation > most { - return Err(bad(cmd, format!("{var_key} must be at most {most}"))); + // Size Variation is refused as path.blob refuses it. + return Err(match var_key { + "sizeVariation" => bad(cmd, format!("`{var_key}` must be from {} to {most}", SIZE_VARIATIONS.0)), + _ => bad(cmd, format!("{var_key} must be at most {most}")), + }); } *slot = (mode, variation); } diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 977f3f921a..9ca565667d 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -1,6 +1,6 @@ use super::common::{ - PenRecord, Sample, brush_region, path_kind, path_mut, path_of, poly_bounds, pressure_region, samples_param, size_pressure, stroke_paint, - subpath_len, target_paths, within_input_bound, + PenRecord, SIZES, Sample, brush_region, path_kind, path_mut, path_of, poly_bounds, pressure_region, ranged, samples_param, size_pressure, + stroke_paint, subpath_len, target_paths, within_input_bound, }; use super::{ Anchor, Appearance, BTreeSet, BoolOp, Cap, Color, Document, EngineError, FillRule, Join, NewArt, Node, NodeId, NodeKind, Paint, PathData, Point, @@ -227,12 +227,18 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s let Some(p0) = pts.first_mut() else { return Err(bad(C, "needs points")) }; *p0 = end; if pts.len() < 2 { - // No stroke to add: the brush alone changes, when it is not the path's already. + // No stroke to add: the brush alone changes, when it is not the path's already, and the + // path is selected or deselected as a longer continuation leaves it. if let Some(name) = brush_name && s.doc()?.doc.node(target).and_then(|n| n.appearance.stroke()).is_some_and(|st| st.brush.as_deref() != Some(name)) { - s.edit("Paintbrush", |d, _| { + s.edit("Paintbrush", |d, sel| { set_brush(d, target, name); + if keep_selected { + sel.set([id]); + } else { + sel.remove(id); + } Ok(()) })?; } @@ -480,10 +486,7 @@ fn adjacent_to_topmost(doc: &Document, touched: &[NodeId], paint: &Paint) -> Vec pub(super) fn blob(s: &mut Session, p: &Value) -> Result { const C: &str = "path.blob"; let samples = samples_param(p, "points", C)?; - let size = number_or(p, "size", 10.0, C)?; - if !(size.is_finite() && size > 0.0) { - return Err(bad(C, "size must be positive")); - } + let size = ranged(p, "size", 10.0, SIZES, C)?; let angle = number_or(p, "angle", 0.0, C)?; let roundness = number_or(p, "roundness", 100.0, C)?; if !angle.is_finite() || !roundness.is_finite() { diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index 883c9ba5ed..d0f480d132 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -117,11 +117,10 @@ fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec { // eighth of the way round a closed path. Over that much of a circle the path turns by 45°, so a // loop shorter than the reach is not all corners, while a square's or a triangle's corners still are. let mut spans = [reach, 2.0 * reach]; + // The lengths along the path ahead and back, measured once when an anchor needs them. + let (mut ahead, mut back) = (None, None); if closed { - let mut total = 0.0; - for i in 0..n { - total += walk(anchors, closed, (i, true), [f64::INFINITY; 2], reach, 1).1; - } + let total = ahead.get_or_insert_with(|| walk_blocks(anchors, closed, true, reach)).first().map_or(0.0, |lens| lens.iter().take(n).sum()); if !(total.is_finite() && total > 0.0) { return corners; } @@ -137,8 +136,10 @@ fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec { if !turn_between(arrive, leave).is_some_and(|t| t > SMOOTH_CORNER_DEG) { continue; } - let [Some(back_near), Some(back_far)] = walk(anchors, closed, (i, false), spans, reach, MAX_CORNER_WALK).0 else { continue }; - let [Some(ahead_near), Some(ahead_far)] = walk(anchors, closed, (i, true), spans, reach, MAX_CORNER_WALK).0 else { continue }; + let back = back.get_or_insert_with(|| walk_blocks(anchors, closed, false, reach)); + let [Some(back_near), Some(back_far)] = spans.map(|r| point_along(anchors, closed, (i, false), r, back, reach)) else { continue }; + let ahead = ahead.get_or_insert_with(|| walk_blocks(anchors, closed, true, reach)); + let [Some(ahead_near), Some(ahead_far)] = spans.map(|r| point_along(anchors, closed, (i, true), r, ahead, reach)) else { continue }; *flag = [(back_near, ahead_near, spans[0]), (back_far, ahead_far, spans[1])] .into_iter() .all(|(back, ahead, r)| r <= 0.0 || turn_between(a.p - back, ahead - a.p).is_some_and(|t| t > SMOOTH_CORNER_DEG)); @@ -146,9 +147,54 @@ fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec { corners } -/// Most segments [`walk`] passes from an anchor before it stops, which bounds the work for each -/// anchor on a path of very many very short segments. -const MAX_CORNER_WALK: usize = 256; +/// The lengths [`walk`] measures along the segments of `anchors`, in the order a walk ahead +/// (`forward`) or back passes them, twice round, starting at the first anchor ahead or the last +/// anchor back, and added up in blocks: element `l` holds the lengths of each run of 2^`l` +/// segments that starts at a multiple of 2^`l`. Each block adds up only its own segments, so a short +/// stretch keeps its length next to very long ones. The segment past an open path's end has no +/// length. +fn walk_blocks(anchors: &[Anchor], closed: bool, forward: bool, reach: f64) -> Vec> { + let n = anchors.len(); + let lens: Vec = + (0..n).map(|k| walk(anchors, closed, (if forward { k } else { n - 1 - k }, forward), [f64::INFINITY; 2], reach, 1).1).collect(); + let mut blocks = vec![(0..2 * n).map(|k| lens[k % n]).collect::>()]; + while let Some(last) = blocks.last().filter(|b| b.len() > 1) { + let next = last.as_chunks::<2>().0.iter().map(|[a, b]| a + b).collect(); + blocks.push(next); + } + blocks +} + +/// The point `dist` along the path `anchors` from anchor `from.0`, ahead when `from.1` and back +/// otherwise, as [`walk`] finds it: an open path's end for a distance beyond the end, and `None` +/// when a length is not a number or is too large to add. The walk skips whole blocks of `blocks` +/// ([`walk_blocks`] in the same direction) that end no more than `dist` along the path, so a path of +/// very many short segments is not walked one segment at a time from each anchor. +fn point_along(anchors: &[Anchor], closed: bool, from: (usize, bool), dist: f64, blocks: &[Vec], reach: f64) -> Option { + let (n, (i, forward)) = (anchors.len(), from); + let start = if forward { i } else { n - 1 - i }; + let end = start + + if closed { + n + } else if forward { + n - 1 - i + } else { + i + }; + let (mut pos, mut gone) = (start, 0.0); + // The largest block that starts at `pos`, stays within the walk and ends within `dist`, until + // none does; a block whose length is not a number is never skipped. + while let Some((size, len)) = blocks.iter().enumerate().rev().find_map(|(l, lens)| { + let size = 1usize << l; + let len = lens.get(pos >> l).copied()?; + (pos % size == 0 && pos + size <= end && gone + len <= dist).then_some((size, len)) + }) { + pos += size; + gone += len; + } + let at = if forward { pos % n } else { n - 1 - pos % n }; + walk(anchors, closed, (at, forward), [(dist - gone).max(0.0); 2], reach, n).0[0] +} /// A walk along the path `anchors` from anchor `from.0`, ahead when `from.1` and back otherwise, /// past no more than `segments` segments, measured along the lines between each curved segment's @@ -1099,11 +1145,12 @@ mod tests { } /// A 90° bump 400 pt high cut into 1 pt segments, between two long straight segments: with a reach - /// of 10 pt its top is a corner, and with a reach of 1,000 pt, where the walk passes more segments - /// than it measures before it gets that far, its top is not one, as the path turns by about 51° - /// over that reach. + /// of 10 pt, and of 300 pt, where twice the reach passes the bump's 566 segments on each side, its + /// top is a corner, and with a reach of 1,000 pt its top is not one, as the path turns by about 51° + /// over that reach. The turns into and between 1 pt segments that follow two segments 1e16 pt long + /// are corners too. #[test] - fn a_corner_is_not_kept_where_the_reach_is_not_measured() { + fn a_bump_of_many_short_segments_is_a_corner_where_it_turns_over_the_reach() { let side = 400.0 * std::f64::consts::SQRT_2; let steps = side.ceil() as usize; let mut pts = vec![(-3000.0, 0.0)]; @@ -1120,6 +1167,10 @@ mod tests { let top = steps + 1; assert_eq!(anchors[top].p, Point::new(0.0, 400.0)); assert!(smooth_corners(&anchors, false, 10.0)[top]); + assert!(smooth_corners(&anchors, false, 300.0)[top]); + let long = polyline(&[(0.0, 0.0), (1e16, 0.0), (0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 2.0)]); + let corners = smooth_corners(&long, false, 0.5); + assert!(corners[2] && corners[3] && corners[4], "{corners:?}"); assert!(!smooth_corners(&anchors, false, 1000.0)[top]); } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 00b6a338f2..f38e23bb5d 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -179,7 +179,7 @@ pub fn specs() -> Vec { "Paste", ["Edit"], Some("Cmd+V"), - "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", + "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", has_clipboard, |s, p| paste(s, p, PasteMode::Offset) ), @@ -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/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 42113c9578..cbe942183a 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -97,7 +97,7 @@ fn effect_specs() -> Vec { "Expand Appearance", ["Object"], None, - "{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", + "{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}", can_expand, expand_appearance ), @@ -367,7 +367,8 @@ fn edit_effects( /// [`edit_effects`] for several effects of one list (`indices`): `f` gets each target's list and /// the positions of `indices` there, ascending; with `aligned`, a position a target doesn't share -/// is left out of it, and a target sharing none of them is left out. +/// is left out of it, and a target sharing none of them is left out. A position no target has is +/// an error with `none`, and nothing changes. #[allow(clippy::too_many_arguments)] fn edit_effects_at( s: &mut Session, @@ -396,7 +397,12 @@ fn edit_effects_at( // Each target's list and the positions in it, in the order the targets first come up. let mut targets: Vec<(NodeId, Option, Vec)> = vec![]; for &index in indices { - for (id, at, i) in effect_targets(s, p, item, index, cmd)? { + let found = effect_targets(s, p, item, index, cmd)?; + // An aligned effect of a design's art that no other object has is refused, as it is given alone. + if found.is_empty() { + return Err(EngineError::Other(none.into())); + } + for (id, at, i) in found { match targets.iter_mut().find(|t| t.0 == id && t.1 == at) { Some(t) => t.2.push(i), None => targets.push((id, at, vec![i])), @@ -957,31 +963,94 @@ fn is_container(n: &Node) -> bool { /// The raster effects of `n` (its own, its fills' and strokes') as an embedded image rendered at /// the document's raster effects resolution or a Rasterize effect's finer one, with whether they -/// all paint below it (shadows and outer glows: the image then holds just them). A group's or -/// layer's image leaves out its members' raster effects, which are expanded with them. `None` -/// when it has none. -fn raster_image(d: &mut Document, n: &Node) -> Option<(Node, bool)> { +/// all paint below it (shadows and outer glows: the image then holds just them, and paints with +/// their blend mode when they all use one). A group's or layer's image leaves out its members' +/// raster effects, which are expanded with them. `None` when it has none. +/// `Err` when that image would take `budget` past its limits: the object then stays as it is. +fn raster_image(d: &mut Document, n: &Node, budget: &mut RasterBudget) -> std::result::Result, OverBudget> { let fx = rasterfx::raster_fx(n); if fx.is_empty() { - return None; + return Ok(None); } let below = fx.iter().all(effects::RasterFx::is_below); - Some((rasterfx::raster_image(d, n, below, true)?, below)) + let pixels = budget.take(rasterfx::raster_pixels(d, n, below, true))?; + let mut image = rasterfx::raster_image(d, n, below, true); + if image.is_none() { + // No image was made: it takes nothing from the budget. + budget.images += 1; + budget.pixels += pixels; + } + // Rendered alone, over nothing, the shadows and glows can't blend with the art below the + // object, so the image does, as the canvas draws them. + let mut modes = fx.iter().filter_map(effects::RasterFx::mode); + if below + && let (Some(mode), Some(image)) = (modes.next(), image.as_mut()) + && modes.all(|m| m == mode) + { + image.blend = mode; + } + Ok(image.map(|image| (image, below))) +} + +/// The most images of raster effects one Expand Appearance makes. +const MAX_RASTER_IMAGES: u32 = 1_024; + +/// The most pixels the images of raster effects one Expand Appearance makes hold in all. +const MAX_RASTER_PIXELS: u64 = 256_000_000; + +/// The note when objects keep their raster effects because their images would take an Expand +/// Appearance past [`MAX_RASTER_IMAGES`] or [`MAX_RASTER_PIXELS`]. +pub(crate) const RASTER_EFFECTS_LEFT: &str = + "some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all"; + +/// An image of raster effects that would take a [`RasterBudget`] past its limits. +#[derive(Debug)] +struct OverBudget; + +/// What one Expand Appearance has left of [`MAX_RASTER_IMAGES`] and [`MAX_RASTER_PIXELS`], and the +/// objects whose raster effects it left as they are because their images would go past them. +pub(crate) struct RasterBudget { + images: u32, + pixels: u64, + pub(crate) left: usize, +} + +impl RasterBudget { + pub(crate) fn new() -> Self { + Self { images: MAX_RASTER_IMAGES, pixels: MAX_RASTER_PIXELS, left: 0 } + } + + /// Take an image of `pixels` ([`rasterfx::raster_pixels`]) before it is made, and return + /// them; `Err`, with its object counted in `left`, when it would go past what is left. + fn take(&mut self, pixels: u64) -> std::result::Result { + if self.images == 0 || pixels > self.pixels { + self.left += 1; + return Err(OverBudget); + } + self.images -= 1; + self.pixels -= pixels; + Ok(pixels) + } } /// Expand the pieces of `m`, art evaluated from the object of the same id (its pieces share that /// id): those made from its own fills and strokes, or with `all` every member. The other members /// that repeat an id ([`repeats_an_id`]) and hold a random Transform effect ([`has_seeded`]) are -/// expanded as well ([`expand_in_place`]). Then the members get ids of their own. Random in a -/// Transform effect takes its seed from the id, and the canvas draws the pieces with the ids they -/// have before that. Returns what each of those other members' expansions lists, by the member's -/// new id. +/// expanded as well ([`expand_in_place`]), except the objects `skip` lists. Then the members get ids +/// of their own. Random in a Transform effect takes its seed from the id, and the canvas draws the +/// pieces with the ids they have before that. `kept` gets the new id of each object in them that +/// had an id `skip` lists before. Returns what each of those other members' expansions lists, by +/// the member's new id. +#[allow(clippy::too_many_arguments)] fn expand_pieces( d: &mut Document, m: &mut Node, all: bool, brushes: &[vectorcraft_brush::Brush], + skip: &[NodeId], + kept: &mut Vec, stroke_art: effects::StrokeArt, + raster: &mut RasterBudget, ) -> std::collections::HashMap> { let id = m.id; let mut seen = std::collections::HashSet::from([id]); @@ -996,9 +1065,23 @@ fn expand_pieces( if all || c.id == id { effects::expand_art(d, c, stroke_art); } else if has_seeded(c) && repeats_an_id(c, &seen) { - listed = Some(expand_in_place(d, c, brushes)); + listed = Some(expand_in_place(d, c, brushes, skip, raster)); + } + let mut was = vec![]; + if !skip.is_empty() { + c.walk(&mut |n| was.push(n.id)); } fresh_ids_listed(d, c, &mut seen, listed.as_deref_mut().unwrap_or_default()); + if !was.is_empty() { + // A copy of an object `skip` lists is left as it is too. + let mut at = 0; + c.walk(&mut |n| { + if was.get(at).is_some_and(|old| *old != n.id && skip.contains(old)) { + kept.push(n.id); + } + at += 1; + }); + } if let Some(listed) = listed { expanded.insert(c.id, listed); } @@ -1006,38 +1089,87 @@ fn expand_pieces( expanded } +/// `m`, the art a 3D effect expanded into, with each object in it that has effects of its own (a +/// shadow blurred by the light's Softness) expanded as Expand Appearance expands it on its own: +/// a blurred shadow becomes an image. Groups in `m` without effects that hold such an object are +/// looked into; the rest are left as they are. The objects `skip` lists are not expanded. +fn expand_raster_pieces(d: &mut Document, mut m: Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], raster: &mut RasterBudget) -> Node { + for c in m.children_mut().into_iter().flatten() { + if !c.appearance.effects.is_empty() { + if let Some(e) = expanded_node(d, (**c).clone(), brushes, skip, &mut vec![], raster) { + *c = Arc::new(e); + } + } else if c.children().is_some() { + let mut holds = false; + c.walk(&mut |n| holds |= !n.appearance.effects.is_empty()); + if holds { + *c = Arc::new(expand_raster_pieces(d, (**c).clone(), brushes, skip, raster)); + } + } + } + m +} + /// Replace each symbol instance in `m`, art an instance placed (`depth` instances deep), whose -/// active fill or stroke has a geometry effect ([`effects::has_item_geometry`]) by its art as -/// [`effects::expand_outlined`] makes it, and the instances in that art in turn, so -/// [`expand_pieces`] bakes their effects with the rest. An instance stays as it is when it is more -/// than [`vectorcraft_doc::depth::MAX_DEPTH`] instances deep, its symbol is missing, or its art -/// would take the objects placed so far past `budget`. -fn expand_nested_instances(d: &Document, m: &mut Node, depth: usize, budget: &mut u64) { +/// active fill or stroke has a geometry or raster effect ([`effects::has_item_geometry`], +/// [`effects::has_instance_row_raster`]) by its art ([`expanded_instance`]), and the instances in +/// that art in turn, so [`expand_pieces`] bakes their effects with the rest. +fn expand_nested_instances(d: &mut Document, m: &mut Node, depth: usize, budget: &mut u64, raster: &mut RasterBudget) { for c in m.children_mut().into_iter().flatten() { if !matches!(c.kind, NodeKind::SymbolInstance { .. }) { if c.children().is_some() { - expand_nested_instances(d, Arc::make_mut(c), depth, budget); + expand_nested_instances(d, Arc::make_mut(c), depth, budget, raster); } continue; } - let NodeKind::SymbolInstance { symbol, .. } = &c.kind else { continue }; - if depth >= vectorcraft_doc::depth::MAX_DEPTH || !effects::has_item_geometry(c) { - continue; - } - let Some(sym) = d.symbols.iter().find(|s| s.name == *symbol) else { continue }; - let count = sym.art.count() as u64; - if count > *budget { - continue; - } - *budget -= count; - let art = vectorcraft_render::instance_art(&sym.art, c); - if let Some(mut a) = effects::expand_outlined(Some(d), c, Some(&art)) { - expand_nested_instances(d, &mut a, depth + 1, budget); + if let Some(a) = expanded_instance(d, c, depth, budget, raster) { *c = Arc::new(a); } } } +/// Symbol instance `c`, art an instance placed (`depth` instances deep), as art: the raster +/// effects of its active fill or stroke an embedded image ([`raster_image`]) that replaces the art +/// (blur, feather, inner glow) or goes below it (shadows, outer glows), and its art as +/// [`effects::expand_outlined`] makes it without them, or as [`effects::instance_as_art`] does when +/// it has no geometry effect, with the instances in that art expanded in turn. `None`, the instance +/// staying as it is, when its active fill and stroke have no such effect, it is more than +/// [`vectorcraft_doc::depth::MAX_DEPTH`] instances deep, its symbol is missing, or its art would +/// take the objects placed so far past `budget`, or the image of its raster effects would take +/// `raster` past its limits. When that image can't be made, they stay on the art its geometry +/// effects make, and without one it stays as it is. +fn expanded_instance(d: &mut Document, c: &Node, depth: usize, budget: &mut u64, raster: &mut RasterBudget) -> Option { + let NodeKind::SymbolInstance { symbol, .. } = &c.kind else { return None }; + let has_raster = effects::has_instance_row_raster(c); + if depth >= vectorcraft_doc::depth::MAX_DEPTH || !(has_raster || effects::has_item_geometry(c)) { + return None; + } + let sym = d.symbols.iter().find(|s| s.name == *symbol)?; + let count = sym.art.count() as u64; + if count > *budget { + return None; + } + let art = vectorcraft_render::instance_art(&sym.art, c); + let image = if has_raster { raster_image(d, c, raster).ok()? } else { None }; + *budget -= count; + let mut v = c.clone(); + if image.is_some() { + rasterfx::strip_raster(&mut v, false); + } + let below = match image { + Some((image, false)) => return Some(rasterfx::replace_with_image(v, image)), + Some((image, true)) => Some(image), + None => None, + }; + let mut a = effects::expand_outlined(Some(&*d), &v, Some(&art)) + .or_else(|| if below.is_some() { effects::instance_as_art(Some(&*d), &v, Some(&art)) } else { None })?; + expand_nested_instances(d, &mut a, depth + 1, budget, raster); + if let Some(image) = below { + rasterfx::put_below(d, &mut a, image); + } + Some(a) +} + /// Does `n` hold an id of `seen`, or one id twice: does [`effects::fresh_ids`] give it new ids? fn repeats_an_id(n: &Node, seen: &std::collections::HashSet) -> bool { let mut ids = std::collections::HashSet::new(); @@ -1052,9 +1184,9 @@ fn repeats_an_id(n: &Node, seen: &std::collections::HashSet) -> bool { type Listed = (NodeId, usize); /// [`expanded_node`] of `c` in place. Returns what the expansion lists, by places in the walk of `c`. -fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush]) -> Vec { +fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], raster: &mut RasterBudget) -> Vec { let mut listed = vec![]; - if let Some(e) = expanded_node(d, c.clone(), brushes, &mut listed) { + if let Some(e) = expanded_node(d, c.clone(), brushes, skip, &mut listed, raster) { *c = e; } listed @@ -1076,11 +1208,26 @@ fn fresh_ids_listed(d: &mut Document, c: &mut Node, seen: &mut std::collections: /// Expand Appearance of `id` (and, recursively, of a group's or layer's members): every fill and /// stroke becomes an object of its own (a stroke a path stroked by it alone, brushes as their art), /// geometry effects are baked, raster effects become an embedded image, and the object keeps its -/// transparency. -pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], out: &mut Vec) { +/// transparency. An object whose raster effects' image would take `raster` past its limits stays +/// as it is, with what is inside it. +pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], out: &mut Vec, raster: &mut RasterBudget) { + expand_node_except(d, id, brushes, &[], out, raster); +} + +/// [`expand_node`], leaving the objects `skip` lists, and what they hold, as they are. A geometry +/// effect of a group or layer around one still reshapes it with the rest of its members, and the +/// copies of it that such an effect makes are left as they are too. +fn expand_node_except( + d: &mut Document, + id: NodeId, + brushes: &[vectorcraft_brush::Brush], + skip: &[NodeId], + out: &mut Vec, + raster: &mut RasterBudget, +) { let Some(n) = d.node(id).cloned() else { return }; let mut listed = vec![]; - let m = expanded_node(d, n, brushes, &mut listed); + let m = expanded_node(d, n, brushes, skip, &mut listed, raster); out.extend(listed.into_iter().map(|(id, _)| id)); if let Some(mut m) = m { // Art made from type takes its emoji's pixels into the document. @@ -1093,12 +1240,21 @@ pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_b /// [`expand_node`] of `n`, which need not be in `d`: `n` with its appearance expanded, `None` when /// it has nothing to expand. `out` gets the objects whose appearance expands, by places in the walk -/// of the expanded `n`, `n`'s first when its own does. -fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Brush], out: &mut Vec) -> Option { +/// of the expanded `n`, `n`'s first when its own does. The objects `skip` lists are not expanded. +fn expanded_node( + d: &mut Document, + mut n: Node, + brushes: &[vectorcraft_brush::Brush], + skip: &[NodeId], + out: &mut Vec, + raster: &mut RasterBudget, +) -> Option { let id = n.id; - if !expandable(&n) { + if skip.contains(&id) || !expandable(&n) { return None; } + // What `out` held before `n`: an object left by the raster budget lists nothing. + let listed_before = out.len(); // Colour adjustments: the colours inside become the adjusted ones (an embedded image a // recoloured copy), then the rest of the appearance expands. let mut changed = false; @@ -1111,6 +1267,10 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br } _ => None, }; + // The embedded images before the adjustment, when the raster budget may yet leave `n` as it + // is: the recolored copies the adjustment adds then go again. + let images_before = (effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty()) + .then(|| d.images.keys().cloned().collect::>()); if effects::has_adjustment(&n) && let Some(m) = effects::adjust_in_document(d, &n, symbol_art) { @@ -1133,7 +1293,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br for (i, c) in m.children_mut().into_iter().flatten().enumerate() { let c = Arc::make_mut(c); if i == 0 { - expanded = expand_in_place(d, c, brushes); + expanded = expand_in_place(d, c, brushes, skip, raster); fresh_ids_listed(d, c, &mut seen, &mut expanded); } else { effects::fresh_ids(d, c, &mut seen); @@ -1156,13 +1316,23 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br } return Some(m); } - let image = raster_image(d, &n); + // Raster effects whose image would go past the budget stay: so does the object, with what is + // inside it and its color adjustments (a symbol instance stays an instance of its symbol). + let Ok(image) = raster_image(d, &n, raster) else { + out.truncate(listed_before); + if let Some(keys) = images_before { + d.images.retain(|k, _| keys.contains(k)); + } + return None; + }; let mut v = n.clone(); rasterfx::strip_raster(&mut v, false); let mut stroke_art = |d: &mut Document, path: &PathData, rule: FillRule, st: &StrokeLayer| super::pathops::outlined_stroke(d, brushes, path, rule, st); // Members of a group or layer that `expand_pieces` expanded, by id, with what their expansion lists. let mut members = std::collections::HashMap::new(); + // New ids of the copies of objects `skip` lists among those members. + let mut kept = vec![]; let expanded = match image { // Blur, feather and inner glow change the object itself: it becomes the image (a layer // keeps it as its only member). @@ -1174,7 +1344,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br } else if container { // A group's or layer's own fills and strokes become art among its members. effects::evaluate_container(Some(&*d), &v).map(|mut m| { - members = expand_pieces(d, &mut m, false, brushes, &mut stroke_art); + members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster); m }) } else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) @@ -1192,13 +1362,21 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br } _ => None, }; - effects::expand_outlined(Some(&*d), &v, symbol.as_ref()).map(|mut m| { + // A symbol instance whose active fill or stroke has only effects that paint below it + // (now in the image) becomes its art as well. + let row_raster = image.is_some() && effects::has_instance_row_raster(&n); + let outlined = effects::expand_outlined(Some(&*d), &v, symbol.as_ref()) + .or_else(|| if row_raster { effects::instance_as_art(Some(&*d), &v, symbol.as_ref()) } else { None }); + outlined.map(|mut m| { let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES; - expand_nested_instances(d, &mut m, 1, &mut budget); - expand_pieces(d, &mut m, true, brushes, &mut stroke_art); + expand_nested_instances(d, &mut m, 1, &mut budget, raster); + expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art, raster); m }) }; + // A 3D effect's shadow blurred by the light's Softness keeps its blur in the art: it + // expands in turn, to an image. + let m = if effects::has_solid(&v) || effects::has_revolve(&v) { m.map(|m| expand_raster_pieces(d, m, brushes, skip, raster)) } else { m }; match image { Some((image, _)) => { let mut m = m.unwrap_or(v); @@ -1217,6 +1395,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br } } if container { + let skip = if kept.is_empty() { std::borrow::Cow::Borrowed(skip) } else { std::borrow::Cow::Owned([skip, &kept].concat()) }; // The place of each member in the walk of `n`: after `n` and the members before it. let mut at = 1; for c in n.children_mut().into_iter().flatten() { @@ -1229,7 +1408,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br match members.remove(&c.id) { Some(listed) => out.extend(listed), None => { - if let Some(e) = expanded_node(d, (**c).clone(), brushes, out) { + if let Some(e) = expanded_node(d, (**c).clone(), brushes, &skip, out, raster) { *c = Arc::new(e); changed = true; } @@ -1274,9 +1453,20 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result { // geometry it hasn't changed. if vectorcraft_plugins::safe_mode::active() { // A dimension selected with the art it measures is left as it is, and so is the art of a graph design in a - // series. + // series, unless an effect of a group around it, the selected graph or series group or one inside it, draws it + // with that group: an effect of the group's own, or a raster effect of one of its fills or strokes (the group + // then becomes an image of all of it). let mut d = super::dimension::without_kept(&s.doc()?.doc, &roots); - let designs = super::appearance::design_art_in(&d, &roots); + let draws_members = |g: &Node| g.appearance.effects.iter().any(|e| e.visible) || !rasterfx::raster_fx(g).is_empty(); + let designs: Vec = super::appearance::design_art_in(&d, &roots) + .into_iter() + .filter(|art| { + !d.ancestry(*art).is_some_and(|up| { + let from = up.iter().position(|a| roots.contains(a)).unwrap_or(up.len()); + up.get(from..up.len().saturating_sub(1)).is_some_and(|around| around.iter().filter_map(|a| d.node(*a)).any(draws_members)) + }) + }) + .collect(); if !designs.is_empty() { let view = d.to_mut(); for id in designs { @@ -1292,6 +1482,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result { } let failed = vectorcraft_render::decode_failures(); let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok(); + let mut raster = RasterBudget::new(); let ids = s.edit("Expand Appearance", |d, _| { let before = d.clone(); // The art of graph designs in the graphs and series among the roots stays as the graph draws it. A group whose @@ -1307,16 +1498,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result { let mut out = vec![]; let threaded = super::threads::frames(d); for id in &roots { - expand_node(d, *id, &brushes, &mut out); - } - for id in &designs { - if let (Some(was), Some(slot)) = (before.node(*id), d.node_mut(*id)) { - *slot = was.clone(); - } - } - if !designs.is_empty() { - // A mark that expands into a group stays listed: only what lies in the restored art is left out. - out.retain(|id| d.node(*id).is_some() && !d.ancestry(*id).is_some_and(|up| up.iter().any(|a| designs.contains(a)))); + expand_node_except(d, *id, &brushes, &designs, &mut out, &mut raster); } super::dimension::put_back(d, lifted); // A dimension whose source was replaced stays where it was, no longer linked. @@ -1325,6 +1507,9 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result { // stays type under a new id takes its frame's place. super::threads::leave_threads(d, &threaded); if out.is_empty() || (kept && d.layers == before.layers) { + if raster.left > 0 { + return Err(EngineError::Other(RASTER_EFFECTS_LEFT.into())); + } return Err(EngineError::Other("Expand Appearance: the selection has a basic appearance".into())); } super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad("Expand Appearance", e))?; @@ -1332,8 +1517,12 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result { })?; let mut out = json!({ "ids": ids_json(&ids) }); // Raster effects become images rendered from the art. - if let Some(w) = rasterfx::undecoded_warning(failed) { - out["warning"] = json!(w); + let warnings: Vec<&str> = rasterfx::undecoded_warning(failed).into_iter().chain((raster.left > 0).then_some(RASTER_EFFECTS_LEFT)).collect(); + if !warnings.is_empty() { + out["warning"] = json!(warnings.join("; ")); + } + if raster.left > 0 { + out["rasterLeft"] = json!(raster.left); } Ok(out) } diff --git a/crates/engine/src/cmd/effectcmd/tests.rs b/crates/engine/src/cmd/effectcmd/tests.rs index b3389e190d..5a1146f28f 100644 --- a/crates/engine/src/cmd/effectcmd/tests.rs +++ b/crates/engine/src/cmd/effectcmd/tests.rs @@ -1017,6 +1017,49 @@ fn a_3d_shadow_is_one_undo_step_saved_exported_and_expanded() { assert_eq!(shadows, 1); } +/// With the light's Softness, the 3D shadow is blurred: the canvas paints past the hard shadow's +/// edge, the object's bounds take the blur in, SVG export blurs it as it does a Gaussian Blur +/// effect, and Expand Appearance keeps it as an image with no live effect left. +#[test] +fn a_soft_3d_shadow_is_drawn_measured_exported_and_expanded_blurred() { + let (mut s, id) = session_with_rect(); + s.execute("effect.apply", &json!({"effect": effects::EXTRUDE, "ids": [id.0], "item": null})).unwrap(); + let set = |s: &mut Session, params: serde_json::Value| { + s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": params})).unwrap(); + }; + let draw = |s: &Session| { + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels + }; + let bounds = |s: &Session| { + let doc = &s.doc().unwrap().doc; + vectorcraft_render::effect_bounds(&doc.symbol_boxes(), doc.node(id).unwrap()).unwrap() + }; + let blurs = |s: &mut Session| { + let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap(); + let svg = svg["data"].as_str().or_else(|| svg["text"].as_str()).map(str::to_string).unwrap_or_else(|| svg.to_string()); + svg.matches(" 100, "{spread}"); + assert!(soft_bounds.contains_rect(hard_bounds) && soft_bounds.area() > hard_bounds.area(), "{hard_bounds:?} {soft_bounds:?}"); + assert_eq!(blurs(&mut s), hard_blurs + 1, "SVG export blurs the shadow as a Gaussian Blur effect"); + s.execute("effect.expandAppearance", &json!({"ids": [id.0]})).unwrap(); + let (mut live, mut pictures) = (0, 0); + s.doc().unwrap().doc.walk(|n| { + live += usize::from(!n.appearance.effects.is_empty() || n.appearance.items.iter().any(|i| !i.effects().is_empty())); + pictures += usize::from(matches!(n.kind, NodeKind::Image(_))); + }); + assert_eq!((live, pictures), (0, 1), "the blurred shadow expands to an image"); +} + /// Radial Blur's Blur Center: stored as given, drawn about that point of the object's bounds, and /// a value outside 0 to 1 (or not a number) is refused with nothing changed and no undo step. #[test] @@ -1082,3 +1125,28 @@ fn radial_blur_center_stays_in_the_object_when_the_stack_splits() { let differ = (0..300 * 300).filter(|i| plain[i * 4 + 3].abs_diff(split[i * 4 + 3]) > 8).count(); assert!(differ < 50, "{differ} pixels' coverage moved with the room around the art"); } + +/// The raster budget charges each image its pixels before it is made: an image past what is left +/// is refused and counted, and the object keeps its blur. +#[test] +fn an_image_past_the_pixels_left_stays_unmade() { + let (mut s, id) = session_with_rect(); + s.execute("effect.apply", &json!({"ids": [id.0], "effect": "blur.gaussian", "params": {"radius": 3}})).unwrap(); + let mut d = s.doc().unwrap().doc.as_ref().clone(); + let n = d.node(id).cloned().unwrap(); + let pixels = super::rasterfx::raster_pixels(&d, &n, false, true); + assert!(pixels > 10_000, "a 100 pt square at 72 ppi: {pixels}"); + + let mut budget = super::RasterBudget { images: 10, pixels: pixels - 1, left: 0 }; + assert!(super::raster_image(&mut d, &n, &mut budget).is_err()); + assert_eq!((budget.images, budget.pixels, budget.left), (10, pixels - 1, 1), "nothing is taken"); + + let mut budget = super::RasterBudget { images: 10, pixels, left: 0 }; + let (image, _) = super::raster_image(&mut d, &n, &mut budget).unwrap().expect("the image is made"); + let NodeKind::Image(img) = &image.kind else { panic!("not an image") }; + assert_eq!(u64::from(img.width) * u64::from(img.height), pixels, "the charge is the image's size"); + assert_eq!((budget.images, budget.pixels, budget.left), (9, 0, 0)); + + let mut budget = super::RasterBudget { images: 0, pixels, left: 0 }; + assert!(super::raster_image(&mut d, &n, &mut budget).is_err(), "no image is left"); +} diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index 43975fe4e4..a17a02ed15 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -265,18 +265,21 @@ fn gradient_expands(d: &Document, l: &Node) -> bool { /// Whether type `t` has a gradient fill that Fill expands once Object has outlined it: one of the /// paths `type.createOutlines` makes of its glyphs, ruby glyphs and underline and strikethrough -/// bars, each painted as its run with its unplaced gradients fitted to the layout's bounds, has one +/// bars, each painted as its run with its unplaced gradients fitted to the layout's bounds, or the +/// path filled with its run's stroke under a transform that is not a similarity, has one /// ([`gradient_expands`] on that path). Inline graphics and color glyphs become other art. Leaves /// the document as it is and stops at the first such path. fn text_gradient_expands(d: &Document, t: &TextObject) -> bool { - if !t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))) { + let gradient = + |st: &vectorcraft_doc::CharStyle| matches!(st.fill, Paint::Gradient(_)) || (st.has_stroke() && matches!(st.stroke, Paint::Gradient(_))); + if !t.runs.iter().any(|r| gradient(&r.style)) { return false; } let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); let first = t.first_style(); let expands = |run: usize, outline: &BezPath| { let style = t.runs.get(run).map_or(&first, |r| &r.style); - if !matches!(style.fill, Paint::Gradient(_)) { + if !gradient(style) { return false; } let path = PathData::from_bezpath(outline); @@ -284,8 +287,8 @@ fn text_gradient_expands(d: &Document, t: &TextObject) -> bool { return false; } let mut piece = Node::path(NodeId(u64::MAX), path, Appearance::default()); - vectorcraft_render::effects::paint_type_piece(&mut piece, style, lay.bounds, t.xf); - gradient_expands(d, &piece) + let stroke = vectorcraft_render::effects::paint_type_piece(&mut piece, style, lay.bounds, t.xf); + gradient_expands(d, &piece) || stroke.is_some_and(|s| gradient_expands(d, &s)) }; let inline = |gi: usize| lay.inlines.iter().find(|i| i.glyph == gi).is_some_and(|i| t.runs.get(i.run).is_some_and(|r| r.inline.is_some())); lay.glyphs.iter().enumerate().any(|(gi, g)| !inline(gi) && g.image.is_none() && g.colour.is_none() && expands(g.run, &g.outline)) diff --git a/crates/engine/src/cmd/fileinfo.rs b/crates/engine/src/cmd/fileinfo.rs index 6219ebb8f6..b6b1643ea4 100644 --- a/crates/engine/src/cmd/fileinfo.rs +++ b/crates/engine/src/cmd/fileinfo.rs @@ -3,14 +3,28 @@ //! title is the one the file the document was opened from gave itself ([`DocMetadata::title`]), //! else the document's name. The SVG (with `metadata`), PDF and PNG writers carry it, and a PDF or //! `.ai` opens with the File Info it gives ([`read_pdf`]). +//! +//! Metadata templates: `file.info.saveTemplate` writes the File Info as an XMP file +//! ([`vectorcraft_pdf::metadata_template`]), `file.info.applyTemplate` merges one into the File +//! Info, and `file.info.templates` lists those in the metadata templates folder. use serde_json::{Map, Value, json}; use vectorcraft_doc::metadata::{MAX_RATING, iso8601}; use vectorcraft_doc::{ColorMode, CopyrightStatus, DocMetadata, Document}; -use super::{Result, Session, bad}; +use super::{Result, Session, bad, switch_or, text_param}; const C: &str = "file.info"; +const SAVE: &str = "file.info.saveTemplate"; +const APPLY: &str = "file.info.applyTemplate"; +const LIST: &str = "file.info.templates"; +/// The extension of a metadata template file. +const TEMPLATE_EXT: &str = "xmp"; +/// The most templates `file.info.templates` lists. +const MAX_LISTED: usize = 1000; +/// The largest metadata template `file.info.saveTemplate` writes and `file.info.applyTemplate` +/// reads, in bytes (8 MB). The largest template File Info's fields can give is under 4 MB. +const MAX_TEMPLATE_FILE: usize = vectorcraft_pdf::MAX_TEMPLATE_BYTES; /// Longest text field, in characters. const MAX_TEXT: usize = 65_536; /// Longest keyword, in characters. @@ -21,9 +35,13 @@ const READ_ONLY: [&str; 6] = ["created", "modified", "colorMode", "units", "artb /// What `file.info` reports (and takes back). pub(crate) fn info_json(d: &Document) -> Value { - let m = &d.metadata; + info_json_with(d, d.info_title(), &d.metadata) +} + +/// [`info_json`] with the title `title` and the metadata `m` in place of the document's. +fn info_json_with(d: &Document, title: &str, m: &DocMetadata) -> Value { json!({ - "title": d.info_title(), + "title": title, "author": m.author, "authorTitle": m.author_title, "description": m.description, @@ -48,11 +66,25 @@ pub(crate) fn file_info(s: &mut Session, p: &Value) -> Result { Value::Object(o) => o, _ => return Err(bad(C, "params must be an object")), }; + let (title, m) = edited(s, Some(o))?; + commit(s, title, m)?; + Ok(info_json(&s.doc()?.doc)) +} + +/// The active document's File Info title and metadata with `fields` (as `file.info` takes them) +/// applied. +fn edited(s: &Session, fields: Option<&Map>) -> Result<(String, DocMetadata)> { let d = &s.doc()?.doc; let (mut title, mut m) = (d.info_title().to_string(), d.metadata.clone()); - for (k, v) in o { + for (k, v) in fields.into_iter().flatten() { apply(&mut title, &mut m, k, v)?; } + Ok((title, m)) +} + +/// Make `title` and `m` the active document's File Info in one undo step; nothing is recorded when +/// they are what it has. Whether anything changed. +fn commit(s: &mut Session, title: String, mut m: DocMetadata) -> Result { let d = &s.doc()?.doc; // A title File Info changes becomes the document's own, as it always has (the tab and Save As // offer it where the document has no file), and replaces the one its file gave. @@ -60,16 +92,290 @@ pub(crate) fn file_info(s: &mut Session, p: &Value) -> Result { if retitled { m.title = None; } - if retitled || m != d.metadata { - s.edit("File Info", |d, _| { - if retitled { - d.title = title; - } - d.metadata = m; - Ok(()) - })?; + if !retitled && m == d.metadata { + return Ok(false); } - Ok(info_json(&s.doc()?.doc)) + s.edit("File Info", |d, _| { + if retitled { + d.title = title; + } + d.metadata = m; + Ok(()) + })?; + Ok(true) +} + +/// The optional object `p` gives for `key`. +fn fields_param<'a>(p: &'a Value, key: &str, c: &str) -> Result>> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Object(o)) => Ok(Some(o)), + Some(_) => Err(bad(c, format!("`{key}` must be an object"))), + } +} + +impl Session { + /// Have `file.info.saveTemplate`, `file.info.applyTemplate` and `file.info.templates` keep the + /// metadata templates in the folder `dir`, which a save makes when it is missing. + pub fn attach_metadata_templates_dir(&mut self, dir: std::path::PathBuf) { + self.metadata_templates_dir = Some(dir); + } + + /// The metadata templates folder ([`Session::attach_metadata_templates_dir`]); none on the web, + /// which has no folders. + pub fn metadata_templates_dir(&self) -> Option<&std::path::Path> { + self.metadata_templates_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) + } +} + +/// The metadata template of the File Info `title` and `m`: each field that has a value, the title +/// only where it is one of its own ([`super::fileio::is_own_title`]), the rating only from 1 up. +fn template_of(title: &str, m: &DocMetadata) -> vectorcraft_pdf::FileInfo { + let text = |s: &str| (!s.trim().is_empty()).then(|| s.to_string()); + vectorcraft_pdf::FileInfo { + title: super::fileio::is_own_title(title).then(|| title.to_string()), + author: text(&m.author), + author_title: text(&m.author_title), + description: text(&m.description), + keywords: (!m.keywords.is_empty()).then(|| m.keywords.clone()), + rating: (m.rating > 0).then_some(m.rating), + copyright_notice: text(&m.copyright_notice), + copyright_url: text(&m.copyright_url), + copyrighted: match m.copyright_status { + CopyrightStatus::Copyrighted => Some(true), + CopyrightStatus::PublicDomain => Some(false), + CopyrightStatus::Unknown => None, + }, + ..Default::default() + } +} + +/// The path of the template `name` in the folder `dir`: `name` made a safe file name, with +/// [`TEMPLATE_EXT`]. +fn template_path(dir: &std::path::Path, name: &str, c: &str) -> Result { + let name = name.trim(); + if name.is_empty() { + return Err(bad(c, "the template name can't be empty")); + } + Ok(dir.join(super::swatchlib::library_file_name(name, TEMPLATE_EXT)).to_string_lossy().into_owned()) +} + +/// The error for a template over [`MAX_TEMPLATE_FILE`]. +fn too_big(c: &str) -> crate::EngineError { + bad(c, format!("the file is larger than {} MB", MAX_TEMPLATE_FILE >> 20)) +} + +/// File Info › Save Metadata Template: `file.info.saveTemplate {name?, path?, fields?}`. +pub(crate) fn save_template(s: &mut Session, p: &Value) -> Result { + let name = text_param(p, "name", SAVE)?; + let path = text_param(p, "path", SAVE)?; + let (title, m) = edited(s, fields_param(p, "fields", SAVE)?)?; + let xmp = vectorcraft_pdf::metadata_template(&template_of(&title, &m)); + if xmp.len() > MAX_TEMPLATE_FILE { + return Err(too_big(SAVE)); + } + match (name, path) { + (Some(_), Some(_)) => Err(bad(SAVE, "give `name` or `path`, not both")), + (Some(name), None) => { + let dir = s.metadata_templates_dir().ok_or_else(|| bad(SAVE, "no metadata templates folder here"))?.to_path_buf(); + let path = template_path(&dir, name, SAVE)?; + // The name is the file name as it is, so two names never share a file. + let listed = std::path::Path::new(&path).file_stem().map(|s| s.to_string_lossy().into_owned()); + if listed.as_deref() != Some(name.trim()) { + return Err(bad(SAVE, "the template name isn't usable as a file name")); + } + // Only a file in the folder itself is replaced: a link there is not followed. + if std::fs::symlink_metadata(&path).is_ok_and(|m| !m.is_file()) { + return Err(crate::EngineError::Other(format!("{path}: not a file"))); + } + let dir = dir.to_string_lossy().into_owned(); + // The app's own folder, under a name checked above: no root applies. + crate::file_access::unconfined(|| super::fileio::create_dir(&dir).and_then(|()| super::fileio::write_file(&path, xmp.as_bytes())))?; + Ok(json!({ "name": listed, "path": super::fileio::shown_path(&path) })) + } + (None, Some(path)) => { + super::fileio::write_file(path, xmp.as_bytes())?; + Ok(json!({ "path": path })) + } + (None, None) => Ok(json!({ "data": xmp })), + } +} + +/// How `file.info.applyTemplate` merges a template's fields into the File Info. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Merge { + /// Clear the fields a template can hold, then take the template's. + Replace, + /// Keep the fields, and take each one the template gives. + Keep, + /// Keep the fields: add the template's keywords, and take its other fields only where the File + /// Info has none. + Append, +} + +/// File Info › Import: `file.info.applyTemplate {path?|name?|data?, mode, apply?, base?}`. +pub(crate) fn apply_template(s: &mut Session, p: &Value) -> Result { + let mode = match text_param(p, "mode", APPLY)? { + Some("replace") => Merge::Replace, + Some("keep") => Merge::Keep, + Some("append") => Merge::Append, + _ => return Err(bad(APPLY, "mode must be replace, keep or append")), + }; + let apply = switch_or(p, "apply", true, APPLY)?; + let base = fields_param(p, "base", APPLY)?; + let bytes = template_bytes(s, p)?; + let t = vectorcraft_pdf::read_template(&bytes).ok_or_else(|| bad(APPLY, "the file is not an XMP metadata template"))?; + let (mut title, mut m) = edited(s, base)?; + merge(&mut title, &mut m, t, mode); + if !apply { + return Ok(info_json_with(&s.doc()?.doc, &title, &m)); + } + let changed = commit(s, title, m)?; + let mut out = info_json(&s.doc()?.doc); + out["changed"] = json!(changed); + Ok(out) +} + +/// The bytes of the template `p` names: `path`, `name` (in the metadata templates folder) or +/// `data`, exactly one, at most [`MAX_TEMPLATE_FILE`] long. +fn template_bytes(s: &Session, p: &Value) -> Result> { + let given = [text_param(p, "path", APPLY)?, text_param(p, "name", APPLY)?, text_param(p, "data", APPLY)?]; + // At most one byte past the limit is read, so a huge file is never read whole. + let read = |path: &str| super::fileio::read_file_head(path, MAX_TEMPLATE_FILE + 1); + let bytes = match given { + [Some(path), None, None] => read(path)?, + [None, Some(name), None] => { + let dir = s.metadata_templates_dir().ok_or_else(|| bad(APPLY, "no metadata templates folder here"))?; + let mut path = template_path(dir, name, APPLY)?; + // A template `file.info.templates` lists: by its `file` first, then by its `name` with + // the extension in lowercase, then in other letter case. Only files in the folder itself + // are listed: a link there is not followed. + let name = name.trim(); + let own = format!("{name}.{TEMPLATE_EXT}"); + let listed = template_files(dir) + .filter(|f| f == name || f.rsplit_once('.').is_some_and(|(stem, _)| stem == name)) + .min_by_key(|f| (f != name, *f != own)); + if let Some(file) = listed { + path = dir.join(file).to_string_lossy().into_owned(); + } else if std::path::Path::new(&path).file_stem().map(|s| s.to_string_lossy()).as_deref() != Some(name) { + // A name that is not a file name as it is never opens another template. + return Err(bad(APPLY, "the template name isn't usable as a file name")); + } + let plain_file = |path: &str| std::fs::symlink_metadata(path).is_ok_and(|m| m.is_file()); + if std::fs::symlink_metadata(&path).is_ok() && !plain_file(&path) { + return Err(crate::EngineError::Other(format!("{path}: not a file"))); + } + // The app's own folder: no root applies. + crate::file_access::unconfined(|| read(&path))? + } + [None, None, Some(data)] if data.len() > MAX_TEMPLATE_FILE => return Err(too_big(APPLY)), + [None, None, Some(data)] => data.as_bytes().to_vec(), + _ => return Err(bad(APPLY, "give one of `path`, `name` and `data`")), + }; + if bytes.len() > MAX_TEMPLATE_FILE { + return Err(too_big(APPLY)); + } + Ok(bytes) +} + +/// Merge the template `t` into the File Info `title` and `m` as `mode` says. Each field goes in as +/// `file.info` would take it; a value it would refuse is left out. +fn merge(title: &mut String, m: &mut DocMetadata, t: vectorcraft_pdf::FileInfo, mode: Merge) { + if mode == Merge::Replace { + // The title is never cleared: a document always has one. + m.author.clear(); + m.author_title.clear(); + m.description.clear(); + m.keywords.clear(); + m.rating = 0; + m.copyright_status = CopyrightStatus::Unknown; + m.copyright_notice.clear(); + m.copyright_url.clear(); + } + let status = t.copyrighted.map(|c| if c { CopyrightStatus::Copyrighted } else { CopyrightStatus::PublicDomain }); + let fields = [ + ("title", t.title.map(Value::from)), + ("author", t.author.map(Value::from)), + ("authorTitle", t.author_title.map(Value::from)), + ("description", t.description.map(Value::from)), + ("keywords", t.keywords.map(Value::from)), + ("rating", t.rating.map(Value::from)), + ("copyrightStatus", status.map(|s| Value::from(s.id()))), + ("copyrightNotice", t.copyright_notice.map(Value::from)), + ("copyrightUrl", t.copyright_url.map(Value::from)), + ]; + for (k, v) in fields { + let Some(mut v) = v else { continue }; + if mode == Merge::Append { + let empty = match k { + "title" => !super::fileio::is_own_title(title), + "author" => m.author.is_empty(), + "authorTitle" => m.author_title.is_empty(), + "description" => m.description.is_empty(), + "rating" => m.rating == 0, + "copyrightStatus" => m.copyright_status == CopyrightStatus::Unknown, + "copyrightNotice" => m.copyright_notice.is_empty(), + "copyrightUrl" => m.copyright_url.is_empty(), + _ => true, + }; + if !empty { + continue; + } + if k == "keywords" { + let mut all: Vec = m.keywords.iter().cloned().map(Value::from).collect(); + all.extend(v.as_array().cloned().unwrap_or_default()); + v = Value::from(all); + } + } + // `apply` changes the field only when it takes the value. + let _ = apply(title, m, k, &v); + } +} + +/// The file names of the templates in the folder `dir`: its files with a name before the +/// [`TEMPLATE_EXT`] extension, in any case. The app's own folder, read directly; a folder not made +/// yet holds none. +fn template_files(dir: &std::path::Path) -> impl Iterator { + std::fs::read_dir(dir) + .into_iter() + .flatten() + .flatten() + .filter(|e| e.file_type().is_ok_and(|t| t.is_file())) + .map(|e| e.file_name().to_string_lossy().into_owned()) + .filter(|file| file.rsplit_once('.').is_some_and(|(stem, ext)| ext.eq_ignore_ascii_case(TEMPLATE_EXT) && !stem.is_empty())) +} + +/// `file.info.templates {create?}`: the metadata templates in the folder, by name. +pub(crate) fn templates(s: &mut Session, p: &Value) -> Result { + let create = switch_or(p, "create", false, LIST)?; + let Some(dir) = s.metadata_templates_dir().map(|d| d.to_string_lossy().into_owned()) else { + return Ok(json!({ "templates": [] })); + }; + if create { + // The app's own folder: no root applies. + crate::file_access::unconfined(|| super::fileio::create_dir(&dir))?; + } + // The first [`MAX_LISTED`] by name, with no more than that many held at once. + let mut files = std::collections::BTreeSet::new(); + for file in template_files(std::path::Path::new(&dir)) { + files.insert(file); + if files.len() > MAX_LISTED { + files.pop_last(); + } + } + let list: Vec = files + .iter() + .filter_map(|file| { + let (stem, _) = file.rsplit_once('.')?; + let path = std::path::Path::new(&dir).join(file).to_string_lossy().into_owned(); + Some(json!({ "name": stem, "file": file, "path": super::fileio::shown_path(&path) })) + }) + .collect(); + let mut out = json!({ "templates": list }); + if super::fileio::shown_path(&dir) == dir.as_str() { + out["folder"] = json!(dir); + } + Ok(out) } /// The File Info a PDF or PDF-compatible `.ai` gives ([`vectorcraft_pdf::file_info`]) into `m`: each @@ -79,8 +385,10 @@ pub(crate) fn read_pdf(m: &mut DocMetadata, f: vectorcraft_pdf::FileInfo) { let status = f.copyrighted.map(|c| if c { CopyrightStatus::Copyrighted } else { CopyrightStatus::PublicDomain }); let fields = [ ("author", f.author.map(Value::from)), + ("authorTitle", f.author_title.map(Value::from)), ("description", f.description.map(Value::from)), ("keywords", f.keywords.map(Value::from)), + ("rating", f.rating.map(Value::from)), ("copyrightStatus", status.map(|s| Value::from(s.id()))), ("copyrightNotice", f.copyright_notice.map(Value::from)), ("copyrightUrl", f.copyright_url.map(Value::from)), diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index fc5be365d5..6817f28b35 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -39,7 +39,7 @@ pub mod jxlread; mod legacy_ai; mod load; mod mesh3d; -pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, size_note}; +pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, png_clip, size_note}; mod heifread; mod hpgl; mod jp2read; @@ -129,9 +129,9 @@ mod commands; mod export_names; mod formats; -pub(crate) use access::check_images_in; #[cfg(not(target_arch = "wasm32"))] pub(crate) use access::list_dir; +pub(crate) use access::{check_images_in, check_scripts_of}; pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with}; #[cfg(all(test, not(target_arch = "wasm32")))] diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index cb5b4e85cc..9d2d9a4a33 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -121,22 +121,54 @@ pub(crate) fn naming_in_message(msg: &str, path: &str, name: &str) -> String { out } -/// The error for an SVG of a document that links a JavaScript file outside the read roots. +/// The error for a file that would name a JavaScript file the document links outside the read roots. pub(crate) const SCRIPT_OUTSIDE: &str = "a linked JavaScript file is outside the read roots"; -/// `cmd` may write `st`'s document in format `format` (a format id): any format but SVG and SVGZ, -/// and those too unless read roots are in force and the document links a JavaScript file outside -/// them (`svg_scripts`, a relative path taken from the document's folder; a URL is not checked), -/// which the file's `
, , and ; a trailing .ext is dropped, as in `COMPANY-Logo--####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row is refused, before the folder is made or any file is written, while the document links a JavaScript file outside them, or while the row's file would name a linked image's file outside them, as document.export refuses it", + "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with for the document, for the artboard, asset, layer or object, from 1, #### for the counter zero-padded to the run of #, , , (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, ,
, , and ; a trailing .ext is dropped, as in `COMPANY-Logo--####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is written from), is refused, before the folder is made or any file is written, while the document links a JavaScript file outside them, or while the row's file would name a linked image's file outside them, as document.export refuses it", has_doc, screens::export_for_screens ), diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index c5b8858f98..c2140477ad 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -268,6 +268,8 @@ struct RasterOptions { /// PSD: Write Layers. layers: Option, max_editability: Option, + /// PSD: Preserve Text Editability (with layers). + preserve_text: Option, hidden_layers: Option, /// Appearance of Black › Printing / Exporting (`prefs.blackOutput`); agents can set it here too. rich_black: Option, @@ -350,6 +352,7 @@ impl RasterOptions { color_model, layers: self.layers.unwrap_or(true), max_editability: self.max_editability.unwrap_or(false), + preserve_text: self.preserve_text.unwrap_or(false), hidden_layers: self.hidden_layers.unwrap_or(false), embed_icc, }, @@ -374,6 +377,7 @@ fn check_options(format: RasterFormat, o: &RasterExportOptions) -> Result<()> { let r = match format { RasterFormat::Bmp if model == jpeg::ColorModel::Cmyk => Err("BMP files are RGB or grayscale: colorModel rgb or gray".to_string()), RasterFormat::Tga if model != jpeg::ColorModel::Rgb => Err("Targa files are RGB: colorModel rgb".to_string()), + RasterFormat::Psd if o.psd.preserve_text && !o.psd.layers => Err("preserveText writes type layers: it needs layers: true".to_string()), RasterFormat::Bmp => o.bmp.check(), RasterFormat::Tga => o.tga.check(), _ => Ok(()), diff --git a/crates/engine/src/cmd/fileio/export.rs b/crates/engine/src/cmd/fileio/export.rs index c3249ba408..1e27778aac 100644 --- a/crates/engine/src/cmd/fileio/export.rs +++ b/crates/engine/src/cmd/fileio/export.rs @@ -53,10 +53,10 @@ pub(super) fn export_reads(f: &Format, legacy: bool, key: &str) -> bool { pub(super) fn serialize(s: &mut Session, p: &Value) -> Result { let f = writable("document.serialize", Some(text_param(p, "format", "document.serialize")?.unwrap_or("vectorcraft")), None)?; - check_linked_scripts("document.serialize", f.id, s.doc()?)?; let unused = unused_option_notes("document.serialize", f, p); let expanded = expand_presets(s, "document.serialize", p)?; let p = with_black_output(s, &expanded); + check_linked_scripts("document.serialize", f.id, s.doc()?, &p)?; let (doc, display_doc_title) = source(s, f, &p, "document.serialize")?; let doc = &*doc; let mut q = p.clone(); @@ -97,10 +97,10 @@ pub(super) fn export(s: &mut Session, p: &Value) -> Result { super::check_not_lossy_overwrite(s.doc()?, path, p, "document.export")?; } let f = writable("document.export", text_param(p, "format", "document.export")?, path)?; - check_linked_scripts("document.export", f.id, s.doc()?)?; let unused = unused_option_notes("document.export", f, p); let expanded = expand_presets(s, "document.export", p)?; let p = with_black_output(s, &expanded); + check_linked_scripts("document.export", f.id, s.doc()?, &p)?; let (doc, display_doc_title) = source(s, f, &p, "document.export")?; let doc = &*doc; let mut q = p.clone(); @@ -199,8 +199,12 @@ fn selected_part(n: &Arc, keep: &HashSet, holders: &HashSet 0.0 { b.inflate(reach, reach) } else { b }); + (n.visual_bounds_with(symbols).is_none_or(brushed) || renderer.effect_bounds(symbols, n).is_some_and(brushed) || painted()).then(|| n.clone()) } let symbols = doc.symbol_boxes().with_brush_art(); let mut d = doc.clone(); @@ -369,10 +375,11 @@ pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result { super::check_not_lossy_overwrite(s.doc()?, path, p, C)?; } let f = writable(C, text_param(p, "format", C)?, path)?; - check_linked_scripts(C, f.id, s.doc()?)?; let unused = unused_option_notes(C, f, p); let expanded = expand_presets(s, C, p)?; let p = with_black_output(s, &expanded); + // The selection is written on one artboard of its own: every artboard, whatever `p` picks. + check_linked_scripts(C, f.id, s.doc()?, &without_artboards(&p))?; let (d, bounds) = selection(s, C, f.id == "txt")?; // The selected objects' links are looked for from the document they are in. check_images_in(C, f.id, &d, crate::cmd::links::LinkBase::of(s.doc()?), &without_artboards(&p))?; diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index 75b202c8ab..acd25aea28 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -308,7 +308,7 @@ const PSD_LAYERS: FormatOption = FormatOption { name: "layers", ty: "boolean", default: "true", - description: "write layers: each top-level layer a pixel layer with its opacity and blend mode (a background colour is a Background layer); false: one flat image, on white where transparent", + description: "write layers: each top-level layer a pixel layer with its opacity and blend mode (a background colour is a Background layer); false: one flat image, on white where transparent. The user and object slices are written either way", }; const MAX_EDITABILITY: FormatOption = FormatOption { @@ -318,6 +318,13 @@ const MAX_EDITABILITY: FormatOption = FormatOption { description: "with layers: layers and sublayers become groups and every object a layer of its own, named as the Layers panel names it (text by its text); clipping, masked or knockout layers stay one layer", }; +const PRESERVE_TEXT: FormatOption = FormatOption { + name: "preserveText", + ty: "boolean", + default: "false", + description: "with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers (with their pixels); a layer holding such type becomes a group of its type layers and pixel layers of the art between them, unless other art in it blends in a mode other than normal; refused with layers: false", +}; + const PSD_HIDDEN_LAYERS: FormatOption = FormatOption { name: "hiddenLayers", ty: "boolean", @@ -339,6 +346,7 @@ const PSD_OPTIONS: &[FormatOption] = &[ ANTI_ALIAS, COLOR_MODEL, PSD_LAYERS, + PRESERVE_TEXT, MAX_EDITABILITY, PSD_HIDDEN_LAYERS, EMBED_ICC, 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/legacy_ai.rs b/crates/engine/src/cmd/fileio/legacy_ai.rs index 23168f1e25..028d9fe5a6 100644 --- a/crates/engine/src/cmd/fileio/legacy_ai.rs +++ b/crates/engine/src/cmd/fileio/legacy_ai.rs @@ -142,7 +142,9 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result let one = super::save::artboard_doc(doc, b); let (full, placed) = crate::cmd::place::document::full_documents(&one); let mut d = full.into_owned(); - expand_appearances(&mut d); + if expand_appearances(&mut d) { + note(&mut enc.warnings, super::super::effectcmd::RASTER_EFFECTS_LEFT); + } if mode == SeeThrough::Flatten { expand_image_patterns(&mut d)?; } @@ -175,14 +177,17 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result Ok(enc) } -/// Expand Appearance of every layer's art whose appearance the format can't hold. -fn expand_appearances(d: &mut Document) { +/// Expand Appearance of every layer's art whose appearance the format can't hold. Returns whether +/// objects kept raster effects whose images would go past Expand Appearance's limits. +fn expand_appearances(d: &mut Document) -> bool { let brushes = vectorcraft_brush::library(d); let layers: Vec = d.layers.iter().map(|l| l.id).collect(); let mut out = vec![]; + let mut raster = super::super::effectcmd::RasterBudget::new(); for id in layers { - super::super::effectcmd::expand_node(d, id, &brushes, &mut out); + super::super::effectcmd::expand_node(d, id, &brushes, &mut out, &mut raster); } + raster.left > 0 } /// Expand every layer's pattern fills that paint an image with see-through pixels, a colorize paint, diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 52ed7f0e7f..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; @@ -73,8 +71,10 @@ pub struct RasterImage { pub height: u32, /// The resolution the file declares (see [`super::ppi::resolution`]). pub ppi: Option<(f64, f64)>, - /// A DCS file's clipping path, in the image's pixel space ([`crate::cmd::place::dcs`]). - pub clip: Option, + /// The clipping path its file draws it through, in the image's pixel space, with its fill rule: + /// a DCS file's (nonzero, [`crate::cmd::place::dcs`]), or a PSD or PSB file's (even-odd, + /// [`psdread::clipping_path`]). + pub clip: Option<(vectorcraft_geom::PathData, vectorcraft_geom::FillRule)>, } pub(super) fn err(e: impl std::fmt::Display) -> EngineError { @@ -131,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 @@ -157,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 @@ -890,16 +898,19 @@ 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 d = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.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; - (rgba_over || d.total_bytes() > MAX_RASTER_ALLOC).then(|| format!("an image of {w} × {h} pixels is too large to draw")) + 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 == 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")) } /// What Open, Place and the Links panel say of encoded image `bytes` that [`too_large_note`] is @@ -909,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")) } @@ -942,7 +953,8 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { /// or TIFF keeps its inks, at the 8 or 16 bits the file has, and its CMYK ICC profile as a CMYK /// TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). An image the decoder reads and that is stored as /// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in; -/// other samples become 8-bit RGBA. +/// other samples become 8-bit RGBA. A Photoshop document's PNG keeps the clipping path the file +/// names ([`png_with_clip`]). pub fn raster_image(bytes: &[u8]) -> Result { let ppi = super::ppi::resolution(bytes); if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) { @@ -950,7 +962,8 @@ pub fn raster_image(bytes: &[u8]) -> Result { } if psdread::is_psd(bytes) { let cms = vectorcraft_color::cms::active(); - return as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, None, ppi); + let img = as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, None, ppi)?; + return Ok(png_with_clip(img, psdread::clipping_path(bytes))); } if jxlread::is_jxl(bytes) { let (img, icc, orientation) = jxlread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?; @@ -967,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. @@ -998,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(); @@ -1012,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 } }, }; @@ -1098,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()) } }; @@ -1118,10 +1127,48 @@ fn stored(bytes: Vec, mime: &'static str, (width, height): (u32, u32), ppi: Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip: None }) } +/// The keyword of the PNG text chunk holding the clipping path of the file a PNG was made from +/// ([`png_with_clip`]). +const CLIP_KEYWORD: &str = "VectorCraft clip"; + +/// Longest clipping path a PNG keeps (bytes of its JSON). +const MAX_PNG_CLIP: usize = 16 << 20; + +/// `img`, a PNG made from a PSD or PSB file, with `clip`, the clipping path that file names in the +/// image's pixel space (even-odd): the image keeps it, and its PNG keeps it in a text chunk, so the +/// Links commands know a clip group of that path as the file's ([`png_clip`]). A path whose JSON is +/// longer than [`MAX_PNG_CLIP`] is left out, and the image comes in unclipped. +fn png_with_clip(mut img: RasterImage, clip: Option) -> RasterImage { + let Some(clip) = clip else { return img }; + let Some(json) = serde_json::to_string(&clip).ok().filter(|j| j.len() <= MAX_PNG_CLIP) else { return img }; + let png = vectorcraft_render::encode::png::with_text(img.blob.bytes.to_vec(), &[(CLIP_KEYWORD, json.into())]); + img.blob = ImageBlob::new("image/png", png); + img.key = img.blob.content_key(); + img.clip = Some((clip, vectorcraft_geom::FillRule::EvenOdd)); + img +} + +/// The clipping path a PNG made from a PSD or PSB file keeps ([`png_with_clip`]), in its pixel +/// space; `None` for other images, and for a text chunk longer than [`MAX_PNG_CLIP`] or a path +/// past [`vectorcraft_geom::path::MAX_READ_ANCHORS`]. Reads only the chunks before the image data. +pub(crate) fn png_clip(png: &[u8]) -> Option { + if !png.starts_with(b"\x89PNG\r\n\x1a\n") { + return None; + } + let keyword = [CLIP_KEYWORD.as_bytes(), &[0]].concat(); + let json = super::ppi::png_chunks(png) + .take_while(|(ty, _)| *ty != b"IDAT") + .find_map(|(ty, data)| data.strip_prefix(keyword.as_slice()).filter(|_| ty == b"tEXt"))?; + if json.len() > MAX_PNG_CLIP { + return None; + } + vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok()) +} + /// An image as a document of its physical size at the resolution it declares (as Place sizes it; /// 72 ppi, 1 px = 1 pt, when it declares none), the image named after the file. pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result { - let RasterImage { key, blob, width, height, ppi, .. } = raster_image(bytes)?; + let RasterImage { key, blob, width, height, ppi, clip } = raster_image(bytes)?; let (sx, sy) = crate::cmd::place::pt_per_px(ppi); let mut d = Document::new(width as f64 * sx, height as f64 * sy); let layer = d.layers[0].id; @@ -1131,7 +1178,7 @@ pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result { id, NodeKind::Image(Box::new(ImageObject { key: key.clone(), width, height, xf, link: None, placement: Default::default(), pixels: None })), ); - let mut n = file_clipped(&mut d, n, psdread::clipping_path(bytes)); + let mut n = file_clipped(&mut d, n, clip.map(|(path, _)| path)); n.name = Some(name.to_string()); d.images.insert(key, blob); d.insert(Some(layer), 0, n).map_err(err)?; diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index 77902b4a15..75e2dba02b 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "Export PDF", [], None, - "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", + "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", has_doc, export_pdf ), @@ -499,6 +499,7 @@ fn export_pdf(s: &mut Session, p: &Value) -> Result { let expanded = expand_preset(s, C, p)?; let p = &*expanded; let st = s.doc()?; + super::check_linked_scripts(C, "pdf", st, p)?; let display_doc_title = super::has_own_title(&st.doc); let titled = super::titled_for_export(&st.doc, st.path.as_deref(), "pdf"); let mut q = p.clone(); 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/psdread.rs b/crates/engine/src/cmd/fileio/psdread.rs index ed9f08a731..8571a19e4e 100644 --- a/crates/engine/src/cmd/fileio/psdread.rs +++ b/crates/engine/src/cmd/fileio/psdread.rs @@ -174,23 +174,48 @@ pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> { /// blocks whose signature is `8BIM` are given. pub(super) fn resources(resources: &[u8], signed: bool) -> impl Iterator { let mut r = Reader::new(resources); - std::iter::from_fn(move || { - if r.rest().is_empty() { - return None; + std::iter::from_fn(move || if r.rest().is_empty() { None } else { block(&mut r).ok() }) + .filter(move |(ours, ..)| *ours || !signed) + .map(|(_, id, name, data)| (id, name, data)) +} + +/// The data of the first `8BIM` image resource block `id` of `resources`. `None` when there is +/// none before the blocks end or before a block that is cut short ahead of it. An error when +/// that block itself is cut short. +pub(super) fn resource(resources: &[u8], id: u16) -> Result, String> { + let mut r = Reader::new(resources); + while !r.rest().is_empty() { + match block(&mut r) { + Ok((true, i, _, data)) if i == id => return Ok(Some(data)), + Ok(_) => {} + Err(Some((true, i))) if i == id => return Err(TRUNCATED.into()), + Err(_) => return Ok(None), } - let ours = r.take(4).ok()? == b"8BIM"; - let id = r.u16().ok()?; + } + Ok(None) +} + +/// An image resource block: whether its signature is `8BIM`, its id, its name (the bytes of its +/// Pascal string) and its data. +type Block<'a> = (bool, u16, &'a [u8], &'a [u8]); + +/// The image resource block that `r` starts with. When it is cut short, the error gives whether +/// its signature is `8BIM` and its id, when those were read. +fn block<'a>(r: &mut Reader<'a>) -> Result, Option<(bool, u16)>> { + let ours = r.take(4).map_err(|_| None)? == b"8BIM"; + let id = r.u16().map_err(|_| None)?; + let mut rest = || -> Result<(&'a [u8], &'a [u8]), String> { // A Pascal string padded to an even size, length byte included. - let len = usize::from(r.u8().ok()?); - let name = r.take(len).ok()?; - r.take((len + 1) % 2).ok()?; - let size = usize::try_from(r.u32().ok()?).ok()?; - let data = r.take(size).ok()?; - r.take(size % 2).ok()?; - Some((ours, id, name, data)) - }) - .filter(move |(ours, ..)| *ours || !signed) - .map(|(_, id, name, data)| (id, name, data)) + let len = usize::from(r.u8()?); + let name = r.take(len)?; + r.take((len + 1) % 2)?; + let size = usize::try_from(r.u32()?).map_err(|_| TRUNCATED.to_string())?; + let data = r.take(size)?; + r.take(size % 2)?; + Ok((name, data)) + }; + let (name, data) = rest().map_err(|_| Some((ours, id)))?; + Ok((ours, id, name, data)) } /// The resource naming the document's clipping path. diff --git a/crates/engine/src/cmd/fileio/psdslices.rs b/crates/engine/src/cmd/fileio/psdslices.rs index ea87f70797..cf5506ff3b 100644 --- a/crates/engine/src/cmd/fileio/psdslices.rs +++ b/crates/engine/src/cmd/fileio/psdslices.rs @@ -18,7 +18,7 @@ use vectorcraft_doc::{SliceKind, SliceOptions}; use vectorcraft_geom::Rect; -use super::psdread::{Reader, TRUNCATED, header, resources}; +use super::psdread::{Reader, TRUNCATED, header, resource}; /// The image resource that holds the slices. const SLICES: u16 = 1050; @@ -51,12 +51,12 @@ struct Stored { } /// The slices PSD or PSB file `bytes` stores. `None` when it stores none (no `8BIM` resource 1050 -/// before the image resources end or are cut short). An error when the file isn't a PSD or PSB -/// file, or its slices can't be read. +/// before the image resources end, or before a block that is cut short ahead of it). An error when +/// the file isn't a PSD or PSB file, resource 1050 is cut short, or its slices can't be read. fn read(bytes: &[u8]) -> Result, String> { let mut r = Reader::new(bytes); let h = header(&mut r)?; - let Some((_, _, data)) = resources(h.resources, true).find(|(id, _, _)| *id == SLICES) else { return Ok(None) }; + let Some(data) = resource(h.resources, SLICES)? else { return Ok(None) }; Ok(Some(Stored { slices: decode(data)?, size: (h.width, h.height) })) } @@ -87,8 +87,9 @@ fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result, St if count > MAX_SLICES { return Err(format!("the file has {count} slices, more than the {MAX_SLICES} read")); } + let one_after_another = records_one_after_another(Reader::new(r.rest()), count, *budget); let mut out = vec![]; - for _ in 0..count { + for i in 0..count { // The ID and group ID. r.take(8)?; let origin = r.u32()?; @@ -116,9 +117,10 @@ fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result, St format!("#{red:02x}{green:02x}{blue:02x}") }; // Photoshop 7 and later may follow a record with a descriptor (version 16); a record that - // doesn't start one is the next slice. A descriptor read that uses up the budget is an - // error. - if r.rest().starts_with(&16u32.to_be_bytes()) { + // doesn't start one is the next slice. When the records follow one another, only the + // last one may be followed by a descriptor. A descriptor read that uses up the budget is + // an error. + if (!one_after_another || i + 1 == count) && r.rest().starts_with(&16u32.to_be_bytes()) { let mut ahead = Reader::new(r.rest()); ahead.u32()?; match descriptor(&mut ahead, 0, budget) { @@ -139,6 +141,37 @@ fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result, St Ok(out) } +/// Whether `r` holds `count` version 6 records one after another, followed by nothing or by one +/// descriptor (version 16) that reads within `budget`, as ag-psd writes them. A record whose ID is +/// 16 then isn't taken for a descriptor. Otherwise each record may be followed by a descriptor. +fn records_one_after_another(mut r: Reader<'_>, count: usize, mut budget: usize) -> bool { + if !(0..count).all(|_| skip_record(&mut r).is_ok()) { + return false; + } + r.rest().is_empty() || (r.rest().starts_with(&16u32.to_be_bytes()) && r.u32().is_ok() && descriptor(&mut r, 0, &mut budget).is_ok()) +} + +/// Reads past the version 6 record `r` starts with, in the layout [`version_6`] reads. Its strings +/// are checked and read past without being decoded. +fn skip_record(r: &mut Reader<'_>) -> Result<(), String> { + // The ID and group ID. + r.take(8)?; + if r.u32()? == 1 { + r.take(4)?; + } + units(r)?; + // The type and the rectangle. + r.take(20)?; + for _ in 0..4 { + units(r)?; + } + r.take(1)?; + units(r)?; + // The alignments and the background color. + r.take(12)?; + Ok(()) +} + /// Versions 7 and 8: the descriptor's `slices` list, each slice an object. fn from_descriptor(d: &[(String, Value)]) -> Result, String> { let Some(Value::List(list)) = field(d, "slices") else { return Err("the slices' descriptor has no list of slices".into()) }; @@ -221,12 +254,17 @@ fn text_len(n: usize) -> Result { /// A Unicode string: a count of UTF-16 units, then the units; trailing NULs dropped. fn unicode(r: &mut Reader<'_>) -> Result { - let n = text_len(r.u32()? as usize)?; - let bytes = r.take(n.checked_mul(2).ok_or(TRUNCATED)?)?; + let bytes = units(r)?; let units: Vec = bytes.as_chunks::<2>().0.iter().map(|u| u16::from_be_bytes(*u)).collect(); Ok(String::from_utf16_lossy(&units).trim_end_matches('\0').to_string()) } +/// A Unicode string's units, as bytes: a count of UTF-16 units, then the units. +fn units<'a>(r: &mut Reader<'a>) -> Result<&'a [u8], String> { + let n = text_len(r.u32()? as usize)?; + r.take(n.checked_mul(2).ok_or(TRUNCATED)?) +} + /// A descriptor's value, as far as the slices need it. #[derive(Clone, Debug, PartialEq)] enum Value { diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 867b9f9f87..09b7924442 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -889,7 +889,6 @@ pub(crate) fn job_for(s: &Session, st: &DocState, plan: SavePlan) -> Result) -> Result { let cmd = plan.mode.command(); - super::check_linked_scripts(cmd, plan.format.id, st)?; let mut own = doc_to_save(st, plan.format); let mut params = plan.options.clone(); if is_svg(plan.format) { @@ -934,6 +933,14 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option { + std::borrow::Cow::Owned(Value::Object(o.iter().filter(|(k, _)| *k != "useArtboards").map(|(k, v)| (k.clone(), v.clone())).collect())) + } + _ => std::borrow::Cow::Borrowed(¶ms), + }; + super::check_linked_scripts(cmd, plan.format.id, st, &checked)?; Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards }) } @@ -1318,7 +1325,7 @@ pub(super) fn specs() -> Vec { "Save Document", [], None, - "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to _.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel", + "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to _.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel", has_doc, |s, p| save(s, SaveMode::Save, p) ), @@ -1345,7 +1352,7 @@ pub(super) fn specs() -> Vec { "Save as Template…", ["File"], None, - "{…as document.save} {path? (saved with the format's extension: one naming another format is replaced, and one is added to a name without it), format?: template (default) | ait (also when format is not given and the path ends in .ait), compress?, version?, preview?, precision?} a template that opens as a new untitled document: a native template (.vctemplate), or a PDF-compatible .ait written as a .ai file is (the .ai options and the PDF options, as document.save takes them for .ai; aiVersion 7 is an error); the document is unchanged → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \" template.\", folder: the Templates folder (preference templatesFolder), warnings}", + "{…as document.save} {path? (saved with the format's extension: one naming another format is replaced, and one is added to a name without it), format?: template (default) | ait (also when format is not given and the path ends in .ait), compress?, version?, preview?, precision?} a template that opens as a new untitled document: a native template (.vctemplate), or a PDF-compatible .ait written as a .ai file is (the .ai options and the PDF options, as document.save takes them for .ai; aiVersion 7 is an error); the document is unchanged → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \" template.\", folder: the Templates folder (preference templatesFolder), warnings}. Under automation read roots, it is refused, before any file is written, while the document links a JavaScript file outside them, as document.save refuses it", has_doc, |s, p| save(s, SaveMode::Template, p) ), diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index 61e5fede2a..d74443a446 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -350,8 +350,8 @@ struct ScreenParams { /// Where files go: `none` (all in the folder), `rows` (the rows' sub-folders, as /// `subfolders`), `format` (a folder per extension), `item`, or `itemFormat`. folders: Option, - /// Export PDFs As: `single` (the artboards a PDF row writes are the pages of one file) or - /// `multiple` (a file per artboard, the default). + /// Export PDFs As: `single` (the artboards a PDF row writes are the pages of one file; refused + /// with assets, layers or `selection: "each"`) or `multiple` (a file per artboard, the default). pdfs: Option, } @@ -399,12 +399,18 @@ impl ScreenParams { if p.is_object() { Self::deserialize(p).map_err(|e| bad(C, e.to_string())) } else { Ok(Self::default()) } } - /// An error when more than one of `assets`, `layers`, `selection` and `fullDocument` is given. + /// An error when more than one of `assets`, `layers`, `selection` and `fullDocument` is given, + /// and when `pdfs: "single"` is given with `assets`, `layers` or `selection: "each"`, whose + /// files each hold the art of one item. fn one_source(&self) -> Result<()> { let sources = [self.full_document, self.assets.is_some(), self.layers.is_some(), self.selection.is_some()].iter().filter(|b| **b).count(); if sources > 1 { return Err(bad(C, "give one of assets, layers, selection or fullDocument")); } + let per_piece = self.assets.is_some() || self.layers.is_some() || self.selection.as_deref() == Some("each"); + if per_piece && self.pdfs.as_deref() == Some("single") { + return Err(bad(C, "pdfs `single` writes artboards as the pages of one PDF: assets, layers and selection `each` write a PDF each")); + } Ok(()) } @@ -764,7 +770,7 @@ fn leave_out_folder(r: &mut Value, folder: &str) { /// Export settings kept in the document or a preset, as the request being served may see them: a /// `folder` outside the read roots ([`super::access::shown`]) is left out. -fn leave_out_unreadable_settings_folder(mut settings: Map) -> Map { +pub(super) fn leave_out_unreadable_settings_folder(mut settings: Map) -> Map { if settings.get("folder").and_then(Value::as_str).is_some_and(|f| !f.is_empty() && !super::access::shown(f)) { settings.remove("folder"); } @@ -1089,6 +1095,29 @@ pub(crate) fn with_export_preset(s: &Session, cmd: &str, settings: &mut Map) -> bool { + if r.format.id != "pdf" { + return super::access::names_linked_scripts(C, r.format.id, &r.options, item.doc.artboards.len()); + } + let (doc, options) = match (single, &item.every_artboard) { + (Some(boards), _) => { + let mut options = r.options.clone(); + options["range"] = json!(boards.iter().map(|b| (b + 1).to_string()).collect::>().join(", ")); + (&item.doc, options) + } + (None, Some(all)) => (all, r.options.clone()), + (None, None) => match r.options_for(item.region, item.artboard) { + Ok(options) => (&item.doc, options), + Err(_) => return true, + }, + }; + super::access::names_linked_scripts(C, "pdf", &options, doc.artboards.len()) +} + /// Every chosen artboard (asset, layer, selected object) in every format row, one file each (a PDF /// holds its artboard alone), or with `fullDocument` one file per row (a PDF of every artboard, /// else the bounds of all art). Items that share a name get `-2`, `-3`… instead of overwriting, and @@ -1105,10 +1134,6 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result o.one_source()?; // ``: the document's file, as Save names it, or its title before it is saved. let st = s.doc()?; - // Before the folder is made or any row is written. - for r in &rows { - super::check_linked_scripts(C, r.format.id, st)?; - } let naming = Naming::of(&o, st.path.as_deref().unwrap_or(&st.doc.title))?; let selection = o.selection_mode()?; let selected = if selection.is_some() { selected_artwork(s)? } else { vec![] }; @@ -1125,6 +1150,10 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result }; let crop = rows.iter().any(|r| r.format.id != "pdf"); let items = items(&doc, &o, selection, &selected, &naming.filename, crop, true)?; + // Before the folder is made or any row is written, with the artboards each file holds. + let single: Option> = items.iter().map(|i| i.artboard).collect::>>().filter(|a| naming.single_pdf && a.len() > 1); + let st = s.doc()?; + super::check_scripts_of(C, &st.doc, st.path.as_deref(), || rows.iter().any(|r| items.iter().any(|i| names_scripts(i, r, single.as_deref()))))?; // The file each item writes for each SVG row, before the folder is made or any row is written. let base = crate::cmd::links::LinkBase::of(s.doc()?); for r in rows.iter().filter(|r| matches!(r.format.id, "svg" | "svgz")) { diff --git a/crates/engine/src/cmd/fileio/svg.rs b/crates/engine/src/cmd/fileio/svg.rs index 44928bf176..bcc01e37a4 100644 --- a/crates/engine/src/cmd/fileio/svg.rs +++ b/crates/engine/src/cmd/fileio/svg.rs @@ -180,12 +180,24 @@ pub(super) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) -> }) } +/// The native document Preserve Editing embeds: `doc`, without an Export for Screens `folder` +/// outside the read roots of the request being served (the open document keeps it). +fn native_attachment(doc: &Document) -> Vec { + let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone()); + if settings.len() == doc.export_settings.len() { + return vectorcraft_format::save(doc, false); + } + let mut kept = doc.clone(); + kept.export_settings = settings; + vectorcraft_format::save(&kept, false) +} + /// Encode `doc` as SVG (or gzipped, SVGZ): one file per chosen artboard, with the images they /// link to and the writer's warnings. pub(super) fn encode(doc: &Document, p: &Value, compressed: bool) -> Result { let (opts, boards, chosen) = plan(doc, p)?; // Preserve editing embeds the native document (once, shared by every file). - let native = opts.preserve_editing.then(|| vectorcraft_format::save(doc, false)); + let native = opts.preserve_editing.then(|| native_attachment(doc)); // Draw linked files as vectors when available, or their previews with a warning. Keep // that preparation out of the native attachment so missing links remain relinkable. let (full, warnings) = crate::cmd::place::document::full_documents(doc); 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_pdfoutput.rs b/crates/engine/src/cmd/fileio/tests_pdfoutput.rs index 04726fee46..c98a121ded 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfoutput.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfoutput.rs @@ -38,3 +38,19 @@ fn export_pdf_converts_colours_writes_the_output_intent_and_real_text() { let bad = s.execute("document.exportPdf", &json!({"output": {"conversion": "destination", "destination": "Missing"}})); assert!(matches!(bad, Err(crate::EngineError::BadParams { .. })), "{bad:?}"); } + +/// Over a saved preset whose Profiles setting is `none`, `"default"` leaves the setting unset, +/// while `null` keeps the preset's value; an unknown value is a bad parameter. +#[test] +fn profiles_default_unsets_a_presets_profiles_setting() { + use vectorcraft_pdf::{PdfPreset, PdfSettings, ProfileInclusion}; + let mut settings = PdfSettings::default(); + settings.output.profiles = Some(ProfileInclusion::None); + let saved = [PdfPreset { name: "No profiles".into(), description: String::new(), settings }]; + let resolve = |output: Value| pdf::resolve("document.exportPdf", &json!({"preset": "No profiles", "output": output}), &saved); + assert_eq!(resolve(json!({"profiles": "default"})).unwrap().output.profiles, None); + assert_eq!(resolve(json!({"profiles": null})).unwrap().output.profiles, Some(ProfileInclusion::None)); + assert_eq!(resolve(json!({"profiles": "all"})).unwrap().output.profiles, Some(ProfileInclusion::All)); + let bad = resolve(json!({"profiles": "sometimes"})); + assert!(matches!(bad, Err(crate::EngineError::BadParams { .. })), "{bad:?}"); +} 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_psd.rs b/crates/engine/src/cmd/fileio/tests_psd.rs index d4f03d78a3..42f87af488 100644 --- a/crates/engine/src/cmd/fileio/tests_psd.rs +++ b/crates/engine/src/cmd/fileio/tests_psd.rs @@ -69,6 +69,23 @@ fn psd_writes_layers_groups_and_text_named_after_it() { assert!(s.execute("document.export", &json!({"format": "psd", "colorModel": "lab"})).is_err()); } +#[test] +fn preserve_text_writes_point_type_as_type_layers_and_needs_layers() { + let mut s = session(); + let file = export(&mut s, json!({"preserveText": true})); + let (_, count, names) = layers(&file); + assert_eq!((count, names), (-4, vec!["Layer 1".into(), "".into(), "Hello".into(), "Words".into()]), "Words becomes a group"); + assert_eq!(file.windows(8).filter(|w| w == b"8BIMTySh").count(), 1, "one type layer"); + assert_eq!(export(&mut s, json!({"preserveText": false})), export(&mut s, json!({}))); + // Without layers there are no type layers to write. + let err = s.execute("document.export", &json!({"format": "psd", "layers": false, "preserveText": true})).unwrap_err().to_string(); + assert!(err.contains("preserveText") && err.contains("layers: true"), "{err}"); + assert!(s.execute("document.export", &json!({"format": "psd", "preserveText": "yes"})).is_err()); + // Other formats don't take it. + let r = s.execute("document.export", &json!({"format": "png", "preserveText": true})).unwrap(); + assert!(r["warnings"].to_string().contains("preserveText"), "{r}"); +} + #[test] fn psd_is_listed_with_its_options_and_writes_one_file_per_artboard() { let mut s = Session::new(); @@ -79,7 +96,7 @@ fn psd_is_listed_with_its_options_and_writes_one_file_per_artboard() { (psd["label"].as_str(), psd["write"].as_bool(), psd["read"].as_bool(), psd["raster"].as_bool()), (Some("PSD"), Some(true), Some(true), Some(true)) ); - for k in ["colorModel", "layers", "maxEditability", "hiddenLayers", "embedIcc", "ppi", "antiAlias", "background"] { + for k in ["colorModel", "layers", "preserveText", "maxEditability", "hiddenLayers", "embedIcc", "ppi", "antiAlias", "background"] { assert!(psd["options"].get(k).is_some(), "psd takes {k}"); } let r = s.execute("document.export", &json!({"format": "psd", "useArtboards": true})).unwrap(); 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 6d66b8da4e..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(); @@ -414,6 +431,98 @@ fn a_plain_image_replacing_a_clipped_psd_keeps_its_rotation() { assert!(after.iter().zip(before).all(|(a, b)| (a - b).abs() < 1e-9), "{after:?} != {before:?}"); } +/// A square saved as "Square" and the clipping path naming it. +fn square_resources() -> Vec { + let square = saved_path(false, &[(true, &[[0.25, 0.25], [0.75, 0.25], [0.75, 0.75], [0.25, 0.75]])]); + [resource(2000, b"Square", &square), clipping_name(b"Square")].concat() +} + +/// `bytes` written as `name` in `dir`, by its path. +fn write_file(dir: &std::path::Path, name: &str, bytes: &[u8]) -> String { + let p = dir.join(name); + std::fs::write(&p, bytes).unwrap(); + p.to_string_lossy().into_owned() +} + +/// links.relink and links.update put a linked PSD file's image in the clip group of the clipping +/// path its new file names, take that clip group's clipping path away when the new file names +/// none, and give it back when a later file names one again. +#[test] +fn relink_and_update_follow_the_clipping_path_of_a_linked_psd() { + let dir = vectorcraft_testkit::TempDir::new("psd-relink-clip"); + let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources())); + let square = write_file(&dir, "square.psd", &red_psd(&square_resources())); + let plain = write_file(&dir, "plain.psd", &red_psd(&[])); + let triangle = vec![[50.0, 0.0], [100.0, 50.0], [0.0, 50.0]]; + let squared = vec![[25.0, 12.5], [75.0, 12.5], [75.0, 37.5], [25.0, 37.5]]; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let r = s.execute("file.place", &json!({"path": cut, "at": [50, 25]})).unwrap(); + let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), r["image"].as_u64().unwrap()); + assert_eq!(clip_group(&s.doc().unwrap().doc, group), (triangle.clone(), true, NodeId(image))); + s.execute("links.relink", &json!({"ids": [image], "path": square})).unwrap(); + assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared.clone(), true, NodeId(image)), "the new file's clipping path"); + s.execute("links.relink", &json!({"ids": [image], "path": plain})).unwrap(); + let d = &s.doc().unwrap().doc; + match d.node(group).map(|n| &n.kind) { + Some(NodeKind::Group { children, clip: false }) => assert_eq!(children.iter().map(|c| c.id.0).collect::>(), [image]), + other => panic!("a plain group of the image: {other:?}"), + } + s.execute("links.relink", &json!({"ids": [image], "path": cut})).unwrap(); + assert_eq!(clip_group(&s.doc().unwrap().doc, group), (triangle.clone(), true, NodeId(image)), "clipped again"); + // The file is saved again with another clipping path. + std::fs::write(&cut, red_psd(&square_resources())).unwrap(); + s.execute("links.update", &json!({"ids": [image]})).unwrap(); + assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared, true, NodeId(image)), "links.update reads the clipping path again"); +} + +/// The PNG a PSD file's merged image is kept as holds the clipping path the file names, and only a +/// text chunk within the size limit that reads as a path gives one back. +#[test] +fn the_kept_png_holds_the_clipping_path_within_bounds() { + let img = raster_image(&red_psd(&triangle_resources())).unwrap(); + let (path, rule) = img.clip.clone().expect("the file's clipping path"); + assert_eq!(rule, vectorcraft_geom::FillRule::EvenOdd); + assert_eq!(super::load::png_clip(&img.blob.bytes), Some(path)); + let plain = raster_image(&red_psd(&[])).unwrap(); + assert!(plain.clip.is_none() && super::load::png_clip(&plain.blob.bytes).is_none()); + let with = |text: String| vectorcraft_render::encode::png::with_text(plain.blob.bytes.to_vec(), &[("VectorCraft clip", text.into())]); + assert_eq!(super::load::png_clip(&with("not a path".into())), None); + assert_eq!(super::load::png_clip(&with(" ".repeat((16 << 20) + 1))), None, "a chunk past the limit is not read"); +} + +/// A plain image relinked to a PSD file that names a clipping path goes into a clip group of that +/// path, under the even-odd rule; a clipping mask made in the document stays around it. +#[test] +fn a_plain_image_relinked_to_a_clipped_psd_is_clipped_by_its_path() { + let dir = vectorcraft_testkit::TempDir::new("psd-relink-plain"); + let plain = write_file(&dir, "plain.psd", &red_psd(&[])); + let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources())); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let r = s.execute("file.place", &json!({"path": plain, "at": [50, 25]})).unwrap(); + let image = NodeId(r["ids"][0].as_u64().unwrap()); + s.execute("links.relink", &json!({"ids": [image.0], "path": cut})).unwrap(); + let d = &s.doc().unwrap().doc; + let group = d.parent_of(image).expect("a clip group"); + assert_eq!(clip_group(d, group), (vec![[50.0, 0.0], [100.0, 50.0], [0.0, 50.0]], true, image)); + // The clipping path's fill rule changed in the document makes it the document's own mask: a + // relink keeps it and puts the file's clip group inside it. + let clip = match d.node(group).map(|n| &n.kind) { + Some(NodeKind::Group { children, .. }) => children[0].id, + other => panic!("{other:?}"), + }; + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + if let Some(vectorcraft_doc::Node { kind: NodeKind::Path { rule, .. }, .. }) = doc.node_mut(clip) { + *rule = vectorcraft_geom::FillRule::NonZero; + } + s.execute("links.relink", &json!({"ids": [image.0], "path": cut})).unwrap(); + let d = &s.doc().unwrap().doc; + let inner = d.parent_of(image).unwrap(); + assert_eq!(d.parent_of(inner), Some(group), "the document's mask holds the file's clip group"); + assert!(clip_group(d, inner).1, "the file's clip group is even-odd"); +} + #[test] fn a_fill_that_starts_with_all_pixels_puts_the_image_around_the_path() { let hole = saved_path(true, &[(true, &[[0.25, 0.25], [0.75, 0.25], [0.75, 0.75], [0.25, 0.75]])]); diff --git a/crates/engine/src/cmd/fileio/tests_psdslices.rs b/crates/engine/src/cmd/fileio/tests_psdslices.rs index 42dc33c600..cc210ffa2a 100644 --- a/crates/engine/src/cmd/fileio/tests_psdslices.rs +++ b/crates/engine/src/cmd/fileio/tests_psdslices.rs @@ -262,6 +262,32 @@ fn photoshop_7_descriptors_after_version_6_records_are_read_past() { assert_eq!(names, ["a", "b"]); } +#[test] +fn a_version_6_record_whose_id_is_16_is_a_slice_not_a_descriptor() { + // The 16th record has ID 16, group ID 0, origin 2, no name and the Image type: its first 18 + // bytes also read as a descriptor of version 16 with no items. + let records: Vec = (1..=17).map(|id| if id == 16 { user("", [1, 1, 4, 4]) } else { user("a", [0, 0, 5, 5]) }).collect(); + let descriptor_after = [16u32.to_be_bytes().to_vec(), descriptor(&[("topOutset", D::Long(0))])].concat(); + for trailing in [vec![], descriptor_after] { + let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&records, &trailing)), json!({})); + assert!(warnings(&r).is_empty(), "{r}"); + let got = slices(&s); + assert_eq!(got.len(), 17, "{got:?}"); + assert_eq!((got[15].0, got[15].1.name.as_str()), (Rect::new(1.0, 1.0, 4.0, 4.0), "")); + assert_eq!(got[16].1.name, "a"); + } + // A descriptor after each record whose class ID is four zero bytes, with no items, followed by + // records with no strings: the records don't also read one after another. + let empty = [ustr(""), 0u32.to_be_bytes().to_vec(), vec![0; 4], 0u32.to_be_bytes().to_vec()].concat(); + let trailing = [16u32.to_be_bytes().to_vec(), empty].concat(); + for rect in [[0, 0, 0, 0], [0, 0, 5, 5]] { + let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&[user("", rect), user("", rect), user("", rect)], &trailing)), json!({})); + let w = warnings(&r); + assert!(!w.iter().any(|w| w.starts_with("the slices can't be read")), "{w:?}"); + assert_eq!(slices(&s).len(), if rect[2] > 0 { 3 } else { 0 }, "{w:?}"); + } +} + #[test] fn version_6_descriptors_share_one_budget_of_values() { // Each record's descriptor holds 2,501 values, well under the 200,000 one descriptor may hold; @@ -371,6 +397,29 @@ fn slices_that_cant_be_read_warn_and_the_file_still_opens() { assert!(warnings(&r).is_empty() && slices(&s).is_empty(), "{r}"); } +#[test] +fn a_slices_resource_cut_short_warns_and_the_file_still_opens() { + let good = v6(&[user("a", [0, 0, 5, 5])], &[]); + // Image resource `id`, the last of the image resources, declares 10 bytes more than they hold. + let cut = |layers: bool, id: u16, data: &[u8]| { + let mut f = with_resource(&psd(layers), id, data); + let sig = [&b"8BIM"[..], &id.to_be_bytes()].concat(); + let at = f.windows(6).rposition(|w| w == sig.as_slice()).unwrap() + 8; + f[at..at + 4].copy_from_slice(&(data.len() as u32 + 10).to_be_bytes()); + f + }; + for layers in [true, false] { + let (s, r) = open(&cut(layers, 1050, &good), json!({})); + let w = warnings(&r); + assert!(w.iter().any(|w| w.starts_with("the slices can't be read (") && w.contains("cut short")), "{w:?}"); + assert!(slices(&s).is_empty()); + assert!(s.doc().unwrap().doc.art_bounds().is_some()); + // Another resource cut short says nothing about slices. + let (s, r) = open(&cut(layers, 1051, &[0, 1]), json!({})); + assert!(warnings(&r).is_empty() && slices(&s).is_empty(), "{r}"); + } +} + #[test] fn slices_are_clipped_to_the_canvas_and_those_outside_it_are_left_out() { let data = v6(&[user("over", [-5, -5, 5, 30]), user("out", [25, 0, 30, 5]), user("empty", [4, 4, 4, 9]), user("in", [1, 1, 2, 2])], &[]); @@ -452,8 +501,85 @@ fn damaged_slices_never_panic() { let mut f = base.clone(); f[at] = v; let mut s = Session::new(); - let _ = s.execute("document.open", &json!({"name": "poster.psd", "dataBase64": b64(&f)})); - let _ = s.execute("document.psdInfo", &json!({"dataBase64": b64(&f)})); + // The engine's guard reports a panic as an internal error. + for r in [ + s.execute("document.open", &json!({"name": "poster.psd", "dataBase64": b64(&f)})), + s.execute("document.psdInfo", &json!({"dataBase64": b64(&f)})), + ] { + assert!(!matches!(r, Err(crate::EngineError::Internal { .. })), "byte {at} set to {v}: {r:?}"); + } } } } + +/// The PSD file `document.export` writes from `s`, with its layers or flat. +fn export(s: &mut Session, layers: bool) -> Vec { + let r = s.execute("document.export", &json!({"format": "psd", "layers": layers})).unwrap(); + vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap() +} + +#[test] +fn an_opened_files_slices_survive_a_psd_export() { + let link = + S { url: "https://example.com/", target: "_blank", message: "Go", alt: "Logo", argb: [255, 0x12, 0x34, 0x56], ..user("logo", [2, 4, 10, 8]) }; + let plain = S { kind: 0, cell: "a < b & c", ..user("note", [10, 10, 20, 20]) }; + let html = S { kind: 0, html: true, cell: "Hi", argb: [0, 1, 2, 3], ..user("", [0, 12, 6, 18]) }; + let auto = S { origin: 0, ..user("auto", [0, 0, 20, 2]) }; + let f = with_resource(&psd(true), 1050, &v6(&[link, plain, html, auto], &[])); + let (mut s, _) = open(&f, json!({})); + let opened = slices(&s); + assert_eq!(opened.len(), 3); + for layers in [true, false] { + let out = export(&mut s, layers); + let (again, r) = open(&out, json!({})); + assert!(warnings(&r).is_empty(), "{r}"); + // The same rectangles and options; the auto slices are laid out again around them. + let mut got = slices(&again); + let mut want = opened.clone(); + let order = |v: &mut Vec<(Rect, SliceOptions)>| v.sort_by(|a, b| a.0.y0.total_cmp(&b.0.y0).then(a.0.x0.total_cmp(&b.0.x0))); + order(&mut got); + order(&mut want); + assert_eq!(got, want); + let layout = again.doc().unwrap().doc.slice_layout(); + assert!(layout.iter().any(|a| a.source == vectorcraft_doc::SliceSource::Auto)); + assert_eq!(s.execute("document.psdInfo", &json!({"dataBase64": b64(&out)})).unwrap()["slices"], json!(3)); + } +} + +#[test] +fn object_slices_are_written_as_user_slices_and_html_text_as_its_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap(); + let rect = r["id"].as_u64().unwrap(); + s.execute("object.slice.make", &json!({"ids": [rect]})).unwrap(); + s.execute("select.set", &json!({"ids": [rect]})).unwrap(); + s.execute("object.slice.options", &json!({"kind": "noImage", "name": "box", "text": "x", "background": "#00ff00"})).unwrap(); + let t = s.execute("text.create", &json!({"x": 100, "y": 50, "text": "A & B"})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.slice.make", &json!({"ids": [t]})).unwrap(); + s.execute("select.set", &json!({"ids": [t]})).unwrap(); + s.execute("object.slice.options", &json!({"kind": "htmlText"})).unwrap(); + let (again, _) = open(&export(&mut s, false), json!({})); + let got = slices(&again); + assert_eq!(got.len(), 2, "{got:?}"); + let doc = &s.doc().unwrap().doc; + let rb = doc.slice_bounds(vectorcraft_doc::NodeId(rect)).unwrap(); + let boxed = got.iter().find(|g| g.1.name == "box").unwrap(); + // Within a pixel of the object's bounds. + for (a, b) in [(boxed.0.x0, rb.x0), (boxed.0.y0, rb.y0), (boxed.0.x1, rb.x1), (boxed.0.y1, rb.y1)] { + assert!((a - b).abs() <= 1.0, "{:?} against {rb:?}", boxed.0); + } + assert_eq!((boxed.1.kind, boxed.1.text.as_str(), boxed.1.background.as_str()), (SliceKind::NoImage, "x", "#00ff00")); + let text = got.iter().find(|g| g.1.name.is_empty()).unwrap(); + assert_eq!((text.1.kind, text.1.text.as_str()), (SliceKind::NoImage, "A & B")); +} + +#[test] +fn twenty_exported_slices_open_again_with_the_one_whose_id_is_16() { + let columns: Vec = (0..20).map(|x| user("", [x, 0, x + 1, 20])).collect(); + let (mut s, _) = open(&with_resource(&psd(false), 1050, &v6(&columns, &[])), json!({})); + assert_eq!(slices(&s).len(), 20); + let (again, r) = open(&export(&mut s, true), json!({})); + assert!(warnings(&r).is_empty(), "{r}"); + assert_eq!(slices(&again), slices(&s)); +} 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..b9dd20aaf5 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"}]}), @@ -1164,6 +1245,41 @@ fn single_file_pdfs_hold_every_chosen_artboard() { assert!(s.execute("document.exportForScreens", &json!({"pdfs": "both", "formats": [{"format": "pdf"}]})).is_err()); } +/// Export PDFs As › Single file holds artboards: with assets, layers or a file per selected object, +/// whose files each hold one item's art, it is refused (the Example line too) instead of writing +/// the first item alone under the document's name; Multiple files writes a PDF of each item. The +/// selection as one file is one PDF either way. +#[test] +fn single_file_pdfs_are_refused_for_assets_layers_and_each_object() { + let mut s = session(1); + s.execute("layer.new", &json!({"name": "Second"})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 30, "y": 5, "width": 8, "height": 8})).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + let layers: Vec = doc.layers.iter().map(|l| l.id.0).collect(); + let art: Vec = doc.layers.iter().filter_map(|l| l.children()).flatten().map(|c| c.id.0).collect(); + assert_eq!((layers.len(), art.len()), (2, 2)); + let a = s.execute("assets.add", &json!({"ids": [art[0]], "name": "Square"})).unwrap()["assets"][0].as_u64().unwrap(); + let b = s.execute("assets.add", &json!({"ids": [art[1]], "name": "Dot"})).unwrap()["assets"][0].as_u64().unwrap(); + s.execute("select.all", &json!({})).unwrap(); + let pdf = json!([{"format": "pdf"}]); + for source in [json!({"assets": [a, b]}), json!({"layers": layers}), json!({"selection": "each"})] { + let mut p = source.clone(); + p["formats"] = pdf.clone(); + p["pdfs"] = json!("multiple"); + let r = export(&mut s, p.clone()); + assert_eq!(names(&r).len(), 2, "a PDF each: {:?} ({source})", names(&r)); + for (name, bytes) in files(&r) { + assert_eq!(vectorcraft_pdf::import(&bytes).unwrap().artboards.len(), 1, "{name}"); + } + p["pdfs"] = json!("single"); + let e = s.execute("document.exportForScreens", &p).unwrap_err().to_string(); + assert!(e.contains("pdfs `single`"), "{e} ({source})"); + assert!(super::screens::first_file(&s, &p).is_err(), "{source}"); + } + let r = export(&mut s, json!({"selection": "one", "pdfs": "single", "formats": pdf})); + assert_eq!(names(&r), ["Selection.pdf"]); +} + /// The warnings of reply `r` that name an option the file doesn't read. fn unused(r: &Value) -> Vec { r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).filter(|w| w.contains("was not used")).map(str::to_string).collect() 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_svgenc.rs b/crates/engine/src/cmd/fileio/tests_svgenc.rs index d1d9123139..7884c1e86b 100644 --- a/crates/engine/src/cmd/fileio/tests_svgenc.rs +++ b/crates/engine/src/cmd/fileio/tests_svgenc.rs @@ -1,7 +1,10 @@ //! SVG encodings, profiles and embedded fonts through the engine: the options reach the file, //! files in each encoding open again, and `document.serialize` reads them as text. +use std::sync::Arc; + use serde_json::json; +use vectorcraft_doc::Document; use super::*; @@ -109,6 +112,106 @@ fn a_chosen_artboard_s_svg_keeps_an_object_whose_shadow_reaches_it() { assert_eq!(paths(&mut s), 1, "its shadow reaches 10 pt onto the artboard"); } +/// A 100 × 100 document whose 3 pt. Round brush paints with a 20 pt nib, and the left edge of its +/// artboard. +fn nib_doc() -> (Document, f64) { + let mut d = Document::new(100.0, 100.0); + let mut lib = vectorcraft_brush::library(&d); + let Some(vectorcraft_brush::BrushKind::Calligraphic(c)) = lib.iter_mut().find(|b| b.name == "3 pt. Round").map(|b| &mut b.kind) else { + panic!("the 3 pt. Round brush") + }; + c.size = 20.0; + vectorcraft_brush::store(&mut d, &lib); + let x0 = d.artboards[0].rect.x0; + (d, x0) +} + +/// A line from (`x`, 40) to (`x`, 60) with a 1 pt stroke in `paint`, painted by the 20 pt nib of +/// [`nib_doc`] when `brushed`: the nib paints 10 pt either side of the line. +fn nib_line(d: &mut Document, x: f64, paint: vectorcraft_color::Paint, brushed: bool) -> vectorcraft_doc::Node { + let mut look = vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::None, paint, 1.0); + if brushed { + look.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + } + let line = vectorcraft_geom::shapes::line((x, 40.0).into(), (x, 60.0).into()); + vectorcraft_doc::Node::path(d.alloc_id(), line, look) +} + +fn black() -> vectorcraft_color::Paint { + vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) +} + +/// A brushed path just left of a chosen artboard, whose brush art paints onto it, is in that +/// artboard's SVG and SVGZ; a brushed path too far off for its brush art to reach it is not. +#[test] +fn a_chosen_artboard_s_svg_keeps_brush_art_reaching_in() { + let (mut d, x0) = nib_doc(); + let layer = d.layers[0].id; + let near = nib_line(&mut d, x0 - 5.0, black(), true); + let far = nib_line(&mut d, x0 - 200.0, black(), true); + let (near, far) = (d.insert(Some(layer), 0, near).unwrap(), d.insert(Some(layer), 0, far).unwrap()); + let kept = export::art_over(&d, d.artboards[0].rect, &mut vectorcraft_render::Renderer::new()); + assert!(kept.node(near).is_some(), "the nib paints 5 pt onto the artboard"); + assert!(kept.node(far).is_none(), "the nib paints 190 pt short of the artboard"); + let mut s = Session::new(); + s.add_document(d, None); + let svg = s.execute("document.serialize", &json!({"format": "svg", "artboard": 0})).unwrap(); + let svg = svg["text"].as_str().unwrap().to_string(); + assert!(vectorcraft_testkit::svg_shapes(&svg) > 0, "{svg}"); + let svgz = s.execute("document.serialize", &json!({"format": "svgz", "artboard": 0})).unwrap(); + let svgz = vectorcraft_format::base64_decode(svgz["dataBase64"].as_str().unwrap()).unwrap(); + assert_eq!(vectorcraft_svg::text_of(&svgz).unwrap(), svg, "the SVGZ is the SVG gzipped"); +} + +/// The room for brush art also keeps a brushed path in a plain group on a sublayer. A brushed +/// stroke without a paint draws no brush art, a clipping group's clip keeps its members' brush art +/// inside it, and a compound path is painted with its own appearance, not its paths': those stay +/// out when only brush art could reach the artboard. +#[test] +fn a_chosen_artboard_s_svg_keeps_nested_brush_art_but_not_unpainted_or_clipped_art() { + use vectorcraft_doc::{LayerColor, Node, NodeKind}; + let (mut d, x0) = nib_doc(); + let layer = d.layers[0].id; + let x = x0 - 5.0; + // A brushed line in a plain group on a sublayer. + let line = nib_line(&mut d, x, black(), true); + let nested = line.id; + let group = Node::new(d.alloc_id(), NodeKind::Group { children: vec![Arc::new(line)], clip: false }); + let mut sublayer = Node::layer(d.alloc_id(), "Sublayer", LayerColor::Preset(1)); + sublayer.children_mut().unwrap().push(Arc::new(group)); + d.insert(Some(layer), 0, sublayer).unwrap(); + // A brushed stroke without a paint. + let unpainted = nib_line(&mut d, x, vectorcraft_color::Paint::None, true); + let unpainted = d.insert(Some(layer), 0, unpainted).unwrap(); + // A clipping group whose clip, far left of the artboard, holds a brushed line just off it. + let mut clip = Node::path( + d.alloc_id(), + vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x0 - 100.0, 40.0, x0 - 90.0, 60.0)), + vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::None, vectorcraft_color::Paint::None, 0.0), + ); + if let NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + let member = nib_line(&mut d, x, black(), true); + let clipped = Node::new(d.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(member)], clip: true }); + let clipped = d.insert(Some(layer), 0, clipped).unwrap(); + // Compound paths of a brushed line: plain itself, then brushed itself. + let mut compounds = vec![]; + for own in [false, true] { + let member = nib_line(&mut d, x, black(), true); + let mut compound = + Node::new(d.alloc_id(), NodeKind::Compound { children: vec![Arc::new(member)], rule: vectorcraft_geom::FillRule::NonZero }); + compound.appearance = nib_line(&mut d, x, black(), own).appearance; + compounds.push(d.insert(Some(layer), 0, compound).unwrap()); + } + let kept = export::art_over(&d, d.artboards[0].rect, &mut vectorcraft_render::Renderer::new()); + assert!(kept.node(nested).is_some(), "the brushed line in the group on the sublayer"); + assert!(kept.node(unpainted).is_none(), "a brushed stroke without a paint"); + assert!(kept.node(clipped).is_none(), "a clipping group whose clip misses the artboard"); + assert!(kept.node(compounds[0]).is_none(), "a compound path that is not brushed itself"); + assert!(kept.node(compounds[1]).is_some(), "a compound path that is brushed itself"); +} + /// #3544: an SVG of one artboard on its own (an `artboard` or `range`, Export for Screens, an asset) /// has the artboard's (or asset's) name as ``; Save's SVG and Export for Screens' Full /// Document keep the document's. 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<u8> { 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.rs b/crates/engine/src/cmd/flatten.rs index cc803c59b9..399f2ec4bd 100644 --- a/crates/engine/src/cmd/flatten.rs +++ b/crates/engine/src/cmd/flatten.rs @@ -40,7 +40,7 @@ use vectorcraft_render::effects; use super::edit::roots_of; use super::menucmds::{MAX_PIXELS, isolated_doc, unique_key}; -use super::pathops::{node_path, outline_strokes, outline_strokes_under, separate, shape_node}; +use super::pathops::{leaves, node_path, outline_strokes, separate, shape_node}; use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, has_doc, str_param, targets, unique_name}; mod analysis; diff --git a/crates/engine/src/cmd/flatten/analysis.rs b/crates/engine/src/cmd/flatten/analysis.rs index 4525a3aa5c..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<String> { - 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() } @@ -185,9 +183,12 @@ impl Sets { /// horizontal extent, would otherwise compare every pair). An open box inside a later box of /// its group, ending no further right, is closed early, and a box inside an open box of its group, /// ending no further right, isn't opened: whatever overlaps it overlaps that box. An open box that -/// a later box of its group overlaps, starting lower and ending no further right or lower, keeps -/// only its part above the later box's top, so boxes staggered right and down each meet only the -/// one before. Fails only when cancelled ([`vectorcraft_doc::cancel`]). +/// a later box of its group overlaps and ends no further right than keeps only the part the later +/// box doesn't cover: its part above the later box's top when the later box starts lower and ends +/// no higher than it, and its part below the later box's bottom when the later box starts no lower +/// and ends higher than it. The open box's top then moves down in the tree, so boxes staggered right +/// and down, or right and up, each meet only the one before. Fails only when cancelled +/// ([`vectorcraft_doc::cancel`]). pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Result<Vec<Vec<usize>>, Cancelled> { Ok(sweep(bounds, None)?.groups()) } @@ -206,27 +207,25 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets, }; let boxes: Vec<(usize, Rect)> = bounds.iter().enumerate().filter_map(|(i, b)| b.filter(finite).map(|b| (i, b))).collect(); let n = boxes.len(); - // Each box's place in the tree: by top (then index). - let mut by_top: Vec<usize> = (0..n).collect(); - by_top.sort_by(|&a, &b| boxes[a].1.y0.total_cmp(&boxes[b].1.y0).then(a.cmp(&b))); - let tops: Vec<f64> = by_top.iter().map(|&k| boxes[k].1.y0).collect(); - let mut leaf = vec![0usize; n]; - for (pos, &k) in by_top.iter().enumerate() { - leaf[k] = pos; - } - // The lowest bottom of the open boxes below each node (−∞: none open), in the tree of the - // boxes without transparency (every box without `see_through`) and the see-through boxes'. - let size = n.next_power_of_two().max(1); - let mut low = [vec![f64::NEG_INFINITY; 2 * size], if see_through.is_some() { vec![f64::NEG_INFINITY; 2 * size] } else { vec![] }]; - let tree = |k: usize| usize::from(see_through.is_some_and(|s| s[boxes[k].0])); - let set = |low: &mut [f64], pos: usize, v: f64| { - let mut i = pos + size; - low[i] = v; - while i > 1 { - i /= 2; - low[i] = low[2 * i].max(low[2 * i + 1]); - } + // The places an open box's top can be at in the tree: a box's top, or just below a box's + // bottom, where a later box cuts it short (`-0.0` as `0.0`). + let mut places: Vec<f64> = boxes.iter().flat_map(|(_, b)| [b.y0 + 0.0, b.y1.next_up() + 0.0]).collect(); + places.sort_by(f64::total_cmp); + places.dedup_by(|a, b| a.total_cmp(b).is_eq()); + let place = |y: f64| { + let y = y + 0.0; + let p = places.partition_point(|t| t.total_cmp(&y).is_lt()); + places.get(p).is_some_and(|t| t.total_cmp(&y).is_eq()).then_some(p) }; + // Each box's part still open, from its top to its bottom, and the place of its top while it + // is open. + let mut top: Vec<f64> = boxes.iter().map(|(_, b)| b.y0).collect(); + let mut bottom: Vec<f64> = boxes.iter().map(|(_, b)| b.y1).collect(); + let mut open: Vec<Option<usize>> = vec![None; n]; + // The tree of the open boxes without transparency (every box without `see_through`) and the + // see-through boxes'. + let mut trees = [Open::new(places.len()), Open::new(if see_through.is_some() { places.len() } else { 0 })]; + let tree = |k: usize| usize::from(see_through.is_some_and(|s| s[boxes[k].0])); let mut by_left: Vec<usize> = (0..n).collect(); by_left.sort_by(|&a, &b| boxes[a].1.x0.total_cmp(&boxes[b].1.x0)); let mut by_right: Vec<usize> = (0..n).collect(); @@ -241,7 +240,9 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets, while let Some(&c) = by_right.get(closing) && boxes[c].1.x1 < b.x0 { - set(&mut low[tree(c)], leaf[c], f64::NEG_INFINITY); + if let Some(p) = open[c].take() { + trees[tree(c)].take(p, c, &bottom); + } closing += 1; } // The open boxes it joins with their top at most this bottom and their bottom at least @@ -253,21 +254,32 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets, Some(_) if shadows => &[0, 1], Some(_) => &[1], }; - let below = tops.partition_point(|t| *t <= b.y1); + let below = places.partition_point(|t| *t <= b.y1); met.clear(); for &t in looks { + let tr = &trees[t]; stack.clear(); - stack.push((1, 0, size)); + stack.push((1, 0, tr.size)); while let Some((node, lo, hi)) = stack.pop() { work += 1; if work.is_multiple_of(4096) { vectorcraft_doc::cancel::check()?; } - if lo >= below || low[t][node] < b.y0 { + if lo >= below || tr.low[node] < b.y0 { continue; } if hi - lo == 1 { - met.push(by_top[lo]); + // The boxes with their top here, lowest bottom first. + for &(_, o) in tr.at[lo].iter().rev() { + if bottom[o] < b.y0 { + break; + } + work += 1; + if work.is_multiple_of(4096) { + vectorcraft_doc::cancel::check()?; + } + met.push(o); + } continue; } let mid = (lo + hi) / 2; @@ -286,30 +298,91 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets, let ob = boxes[o].1; see_through.is_none_or(|s| s[boxes[o].0]) && b.x1 <= ob.x1 && ob.y0 <= b.y0 && b.y1 <= ob.y1 }); - // Whatever overlaps a box inside this one overlaps this one, and joins it when this one is - // see-through. Likewise, whatever later overlaps the part of an open box at or below this - // one's top, when that box ends no further right or lower than this one, overlaps this - // one: the open box then keeps only the part above this one's top. - let cut = b.y0.next_down(); + // Whatever overlaps the open part of a box inside this one overlaps this one, and joins it + // when this one is see-through. Likewise, whatever later overlaps the part of an open box + // this one covers, when that box ends no further right than this one, overlaps this one: + // the open box then keeps only the part above this one's top, when this one reaches its + // bottom, or only the part below this one's bottom, when this one reaches its top. for &o in &met { sets.join(boxes[k].0, boxes[o].0); - let ob = boxes[o].1; - if !shadows || Some(o) == holder || b.x1 < ob.x1 || b.y1 < ob.y1 { + let Some(p) = open[o] else { continue }; + if !shadows || Some(o) == holder || b.x1 < boxes[o].1.x1 { continue; } - if b.y0 <= ob.y0 { - set(&mut low[tree(o)], leaf[o], f64::NEG_INFINITY); - } else if holder.is_none() && cut < low[tree(o)][leaf[o] + size] { - set(&mut low[tree(o)], leaf[o], cut); + let (t, u) = (top[o], bottom[o]); + let tr = &mut trees[tree(o)]; + if b.y0 <= t && u <= b.y1 { + tr.take(p, o, &bottom); + open[o] = None; + continue; + } + if holder.is_some() || (b.y1 < u && t < b.y0) { + continue; + } + let (t, u) = if u <= b.y1 { (t, b.y0.next_down()) } else { (b.y1.next_up(), u) }; + // Every top it can get has a place; one without stays as it is. + let Some(q) = place(t) else { continue }; + tr.take(p, o, &bottom); + (top[o], bottom[o]) = (t, u); + open[o] = (t <= u).then_some(q); + if t <= u { + tr.put(q, o, &bottom); } } - if holder.is_none() { - set(&mut low[tree(k)], leaf[k], b.y1); + if holder.is_none() + && let Some(p) = place(b.y0) + { + open[k] = Some(p); + trees[tree(k)].put(p, k, &bottom); } } Ok(sets) } +/// The open boxes of [`sweep`] by the place of their tops, in a tree that knows the lowest bottom +/// below each of its branches. +struct Open { + size: usize, + /// The lowest bottom of the open boxes below each node (−∞: none open). + low: Vec<f64>, + /// The open boxes at each place, by bottom ([`order`]) and then index. + at: Vec<BTreeSet<(i64, usize)>>, +} + +impl Open { + fn new(places: usize) -> Self { + let size = places.next_power_of_two().max(1); + Self { size, low: vec![f64::NEG_INFINITY; 2 * size], at: vec![BTreeSet::new(); places] } + } + + /// Opens box `k` at place `p`, with its bottom `bottom[k]`. + fn put(&mut self, p: usize, k: usize, bottom: &[f64]) { + self.at[p].insert((order(bottom[k]), k)); + self.fix(p, bottom); + } + + /// Closes box `k` at place `p`, while its bottom is still `bottom[k]`. + fn take(&mut self, p: usize, k: usize, bottom: &[f64]) { + self.at[p].remove(&(order(bottom[k]), k)); + self.fix(p, bottom); + } + + fn fix(&mut self, p: usize, bottom: &[f64]) { + let mut i = p + self.size; + self.low[i] = self.at[p].last().map_or(f64::NEG_INFINITY, |&(_, k)| bottom[k]); + while i > 1 { + i /= 2; + self.low[i] = self.low[2 * i].max(self.low[2 * i + 1]); + } + } +} + +/// `v` as an integer in the same order as [`f64::total_cmp`]. +fn order(v: f64) -> i64 { + let b = v.to_bits() as i64; + b ^ (((b >> 63) as u64) >> 1) as i64 +} + /// Boxes in blocks of nearby ones, each block with the box around it, to find the boxes a box /// touches. struct Blocks { @@ -775,6 +848,136 @@ mod tests { assert_eq!(sets.groups(), vec![(0..n).collect::<Vec<_>>()]); } + /// `n` boxes of one size, each a little right of and above the one before, all overlapping and + /// none inside another. + fn staggered_up(n: usize) -> Vec<Option<Rect>> { + let w = 2.0 * n as f64; + (0..n).map(|i| Some(Rect::new(i as f64, -(i as f64), w + i as f64, w - i as f64))).collect() + } + + /// Each box of a stagger right and up meets only the box before it, which keeps only its part + /// below the new box's bottom, not every box still open; so does each box of a stagger left and + /// down, which the sweep meets right and up. + #[test] + fn boxes_staggered_up_meet_only_the_box_before() { + let n = 512; + let bounds = staggered_up(n); + let all = vec![(0..n).collect::<Vec<_>>()]; + let mut sets = sweep(&bounds, None).unwrap(); + assert_eq!(sets.meets, n - 1); + assert_eq!(sets.groups(), every_pair(&bounds)); + assert_eq!(sets.groups(), all); + let mut sets = sweep(&bounds, Some(&vec![true; n])).unwrap(); + assert_eq!(sets.meets, n - 1); + assert_eq!(sets.groups(), all); + let mut reversed = bounds.clone(); + reversed.reverse(); + let mut sets = sweep(&reversed, None).unwrap(); + assert_eq!(sets.meets, n - 1); + assert_eq!(sets.groups(), all); + let mut sets = sweep(&reversed, Some(&vec![true; n])).unwrap(); + assert_eq!(sets.meets, n - 1); + assert_eq!(sets.groups(), all); + } + + /// An open box cut short from above keeps the part a later box would meet without meeting the + /// box that cut it: a part below that box, a part further right, or any part when that box is + /// opaque or held; a box cut from above and from below keeps its middle. + #[test] + fn a_box_is_cut_short_from_above_only_where_the_later_box_covers_it() { + let k = Rect::new(5.0, -5.0, 15.0, 10.0); + let cases = [ + // Below `k`: the last box overlaps only the bottom of the first. + ("below", vec![Some(Rect::new(0.0, 0.0, 10.0, 20.0)), Some(k), Some(Rect::new(8.0, 15.0, 9.0, 25.0))], vec![true, true, false]), + // Further right than `k`: `k` cuts nothing and the last box overlaps the first. + ("right", vec![Some(Rect::new(0.0, 0.0, 20.0, 20.0)), Some(k), Some(Rect::new(17.0, 2.0, 25.0, 4.0))], vec![true, true, false]), + // Just below `k`'s bottom, and touching it. + ( + "edge", + vec![Some(Rect::new(0.0, 0.0, 10.0, 20.0)), Some(k), Some(Rect::new(8.0, 10.0, 9.0, 12.0)), Some(Rect::new(8.0, 10.5, 9.0, 12.0))], + vec![false, true, false, false], + ), + // An opaque `k` doesn't join the opaque last box, which joins the see-through first one. + ("opaque", vec![Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(k), Some(Rect::new(6.0, -10.0, 7.0, 2.0))], vec![true, false, false]), + // A see-through `k` held by a see-through box around it isn't opened and cuts nothing short. + ( + "held", + vec![ + Some(Rect::new(0.0, -6.0, 30.0, 28.0)), + Some(Rect::new(1.0, 0.0, 10.0, 20.0)), + Some(k), + Some(Rect::new(6.0, 11.0, 7.0, 13.0)), + Some(Rect::new(6.0, 4.0, 7.0, 6.0)), + ], + vec![true, false, true, false, false], + ), + // Cut from above, then from below: a later box inside what is left joins the first. + ( + "middle", + vec![ + Some(Rect::new(0.0, 0.0, 10.0, 30.0)), + Some(Rect::new(2.0, -5.0, 12.0, 10.0)), + Some(Rect::new(3.0, 20.0, 13.0, 40.0)), + Some(Rect::new(5.0, 15.0, 6.0, 16.0)), + Some(Rect::new(5.0, 9.0, 6.0, 10.0)), + Some(Rect::new(5.0, 20.0, 6.0, 20.0)), + ], + vec![false, true, true, false, false, false], + ), + // Signed zeros, a point and a box that isn't finite. + ( + "zeros", + vec![ + Some(Rect::new(-0.0, -0.0, 4.0, 8.0)), + Some(Rect::new(0.0, -2.0, 6.0, -0.0)), + Some(Rect::new(1.0, 0.0, 1.0, 0.0)), + Some(Rect::new(2.0, f64::NEG_INFINITY, 3.0, 1.0)), + Some(Rect::new(3.0, f64::MAX, 3.0, f64::MAX)), + Some(Rect::new(3.5, 0.0, 3.5, 0.0)), + ], + vec![false, true, false, true, true, false], + ), + ]; + for (what, bounds, see) in cases { + assert_eq!(overlapping(&bounds).unwrap(), every_pair(&bounds), "{what}"); + let mut sets = sweep(&bounds, Some(&see)).unwrap(); + assert_eq!(sets.groups(), every_pair_joining(&bounds, |i, j| see[i] || see[j]), "{what}, with transparency"); + let mut sets = sweep(&bounds, Some(&vec![true; bounds.len()])).unwrap(); + assert_eq!(sets.groups(), every_pair(&bounds), "{what}, all see-through"); + } + } + + /// Boxes stepping right and alternately up and down, so that open boxes are cut short from + /// above and from below, of mixed sizes, some see-through, group as comparing every pair groups + /// them. + #[test] + fn boxes_stepping_up_and_down_group_as_comparing_every_pair() { + let mut seed = 0x6a09_e667_f3bc_c908u64; + let mut next = |m: f64| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % 1000) as f64 / 1000.0 * m + }; + for round in 0..40 { + let n = 10 + round * 3; + let mut y = 0.0; + let bounds: Vec<Option<Rect>> = (0..n) + .map(|i| { + let up = if (i / (1 + round % 3)) % 2 == 0 { -1.0 } else { 1.0 }; + y += up * (next(4.0).floor() + 1.0); + let x = i as f64 + next(2.0).floor(); + let (w, h) = (next(12.0).floor() + 4.0, next(16.0).floor() + 2.0); + Some(Rect::new(x, y, x + w, y + h)) + }) + .collect(); + assert_eq!(overlapping(&bounds).unwrap(), every_pair(&bounds), "round {round}"); + let see: Vec<bool> = (0..n).map(|_| next(1.0) < if round % 2 == 0 { 0.5 } else { 0.9 }).collect(); + let mut sets = sweep(&bounds, Some(&see)).unwrap(); + assert_eq!(sets.groups(), every_pair_joining(&bounds, |i, j| see[i] || see[j]), "round {round}, with transparency"); + } + } + /// An open box keeps the part a later box would meet without meeting the box that cut it short: /// a part lower than that box, a part further right, or any part when that box is opaque. #[test] diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index b159fa7361..b8aebf8324 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -1,9 +1,11 @@ +use std::collections::HashSet; + use super::analysis::{Scratch, finite, flatten_groups, has_effects, masked, outlined_text, overlapping, painted, reach}; use super::compose::{Builder, CLEAR, Composer, Elem, Fill, Kind, Px, WHITE}; use super::options::FlattenOptions; use super::{ Affine, Appearance, AppearanceItem, Arc, BlendMode, Color, ColorMode, Document, EngineError, FillLayer, FillRule, ImageBlob, ImageObject, Inks, - MAX_PIXELS, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, composite, effects, isolated_doc, outline_strokes_under, planes_cmyk, po, + MAX_PIXELS, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, composite, effects, isolated_doc, leaves, outline_strokes, planes_cmyk, po, separate, shape_node, shapes, unique_key, }; @@ -14,6 +16,8 @@ pub(super) struct Plan { pub(super) flat: Vec<Flat>, /// Objects without transparency (they stay, but for the outline options). pub(super) kept: Vec<NodeId>, + /// What the outline and overprint options do to each of `kept`, in its order. + pub(super) work: Vec<Kept>, /// The objects with transparency of their own. pub(super) transparent: Vec<NodeId>, } @@ -112,7 +116,12 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render: let reaches: Vec<Option<Rect>> = plain.iter().zip(&clipped).map(|(n, c)| reach(n).zip(reach(c)).map(|(a, b)| a.intersect(b))).collect(); let see_through: Vec<bool> = plain.iter().map(|n| o.shows_transparency(&baked, n) || o.draws_see_through_image(n)).collect(); let cmyk = src.color_mode == ColorMode::Cmyk; - let mut out = Plan { flat: vec![], kept: vec![], transparent: roots.iter().zip(&see_through).filter(|(_, t)| **t).map(|(id, _)| *id).collect() }; + let mut out = Plan { + flat: vec![], + kept: vec![], + work: vec![], + transparent: roots.iter().zip(&see_through).filter(|(_, t)| **t).map(|(id, _)| *id).collect(), + }; // Baking above stopped early when cancelled; each group is a place to stop (a plan changes nothing). vectorcraft_doc::cancel::check()?; let mut queue = groups(src, roots, &plain, &reaches, &see_through, o)?; @@ -193,9 +202,101 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render: }; out.flat.push(Flat { roots: ids, regions, area, raster, lines }); } + out.work = out.kept.iter().map(|id| Kept::of(src, *id, o)).collect(); Ok(out) } +/// What the outline and overprint options do to one object without transparency, found in one +/// walk of it. +pub(super) struct Kept { + pub(super) id: NodeId, + /// Whether the options change it. + pub(super) changes: bool, + /// The type the text option outlines and the stroked paths the stroke option outlines, those + /// that show and are not pieces of a compound path: what the Flattener Preview highlights. + pub(super) shown_text: Vec<NodeId>, + pub(super) shown_strokes: Vec<NodeId>, + /// In paint order: the type the text option outlines and the leaf shapes ([`leaves`]) other + /// than type that the stroke option outlines. + steps: Vec<Step>, + /// The objects with overprints, each with the type or leaf shape that holds it (itself + /// included) when a step replaces that. + overprinted: Vec<(NodeId, Option<NodeId>)>, +} + +/// One object [`apply`] outlines. +enum Step { + /// Type; `leaf`: only groups and layers hold it, so its outlines are leaf shapes for the + /// stroke option. + Text { id: NodeId, leaf: bool }, + /// A leaf shape other than type. + Leaf(NodeId), +} + +/// Where [`Kept::visit`] is in the object it walks. +#[derive(Clone, Copy)] +struct At { + /// Neither the node nor what holds it is hidden, and it is not a piece of a compound path. + shown: bool, + /// Only groups and layers hold the node. + leaf: bool, + /// The type or leaf shape holding the node that a step replaces. + holder: Option<NodeId>, +} + +impl Kept { + /// What the options `o` do to `root` of `d`: nothing when `d` doesn't hold it. + fn of(d: &Document, root: NodeId, o: &FlattenOptions) -> Kept { + let mut k = Kept { id: root, changes: false, shown_text: vec![], shown_strokes: vec![], steps: vec![], overprinted: vec![] }; + if let Some(n) = d.node(root) { + k.visit(n, o, At { shown: true, leaf: true, holder: None }); + } + k + } + + /// Note what the options `o` do to `n` and to everything under it. + fn visit(&mut self, n: &Node, o: &FlattenOptions, at: At) { + kept_seen(n); + let shown = at.shown && n.visible; + let mut holder = at.holder; + if matches!(n.kind, NodeKind::Text(_)) { + if o.text_to_outlines { + self.changes = true; + if shown { + self.shown_text.push(n.id); + } + self.steps.push(Step::Text { id: n.id, leaf: at.leaf }); + holder = Some(n.id); + } + } else { + if o.strokes_to_outlines && stroked(n) { + self.changes = true; + if shown { + self.shown_strokes.push(n.id); + } + } + if o.strokes_to_outlines && at.leaf && matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }) + { + self.steps.push(Step::Leaf(n.id)); + holder = Some(n.id); + } + } + if !o.preserve_overprints && overprints(n) { + self.changes = true; + self.overprinted.push((n.id, holder)); + } + let Some(children) = n.children() else { return }; + let inside = At { + shown: shown && !matches!(n.kind, NodeKind::Compound { .. }), + leaf: at.leaf && matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }), + holder, + }; + for c in children { + self.visit(c, o, inside); + } + } +} + /// `roots` of `src` (`plain`: as plain art; `reaches`: where each can paint, clipped) in the /// groups that flatten together ([`flatten_groups`]), each in paint order, by their first object. /// Objects that overlap (as [`overlapping`] groups them) stay in one group when one of them is @@ -668,7 +769,7 @@ pub(crate) fn flatten_expanded(doc: &Document, o: &FlattenOptions) -> Result<Opt roots.extend(children.iter().skip(usize::from(l.clips())).filter(|c| c.visible && !c.is_ruler_guide()).map(|c| c.id)); } let plan = plan(doc, &roots, o, true)?; - if plan.flat.is_empty() && !plan.kept.iter().any(|id| doc.node(*id).is_some_and(|n| kept_work(n, o))) { + if plan.flat.is_empty() && !plan.work.iter().any(|k| k.changes) { return Ok(None); } let mut d = doc.clone(); @@ -753,19 +854,8 @@ pub(super) fn apply(d: &mut Document, sel: &mut vectorcraft_doc::Selection, plan d.insert(Some(layer), usize::MAX, guide)?; } let brushes = if o.strokes_to_outlines { vectorcraft_brush::library(d) } else { vec![] }; - for mut id in plan.kept { - if o.text_to_outlines { - id = outline_texts_under(d, id)?; - } - if o.strokes_to_outlines { - id = outline_strokes_under(d, &brushes, id)?.0; - } - if !o.preserve_overprints - && let Some(n) = d.node_mut(id) - { - drop_overprints(n); - } - ids.push(id); + for k in plan.work { + ids.push(outline_kept(d, &brushes, k, o)?); } ids.sort_by_key(|id| d.index_path(*id)); sel.set(ids.iter().copied()); @@ -838,6 +928,21 @@ fn guide_seen(n: &Node) { #[cfg(not(test))] fn guide_seen(_: &Node) {} +#[cfg(test)] +thread_local! { + /// The nodes that [`Kept::of`] has looked at on this thread, in order. + static KEPT_SEEN: std::cell::RefCell<Vec<NodeId>> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// Note that [`Kept::of`] looked at `n`. +#[cfg(test)] +fn kept_seen(n: &Node) { + KEPT_SEEN.with(|s| s.borrow_mut().push(n.id)); +} + +#[cfg(not(test))] +fn kept_seen(_: &Node) {} + /// An image of `r` (in a clip group when it is clipped). fn raster_node(d: &mut Document, r: Raster) -> Node { let key = unique_key(d, "flattened"); @@ -858,38 +963,65 @@ fn raster_node(d: &mut Document, r: Raster) -> Node { crate::cmd::rasterfx::clip_group(d, path, FillRule::NonZero, image) } -/// Replace the type under `root` by its outlines: → the id now standing for `root`. -fn outline_texts_under(d: &mut Document, root: NodeId) -> Result<NodeId> { - let mut texts = vec![]; - if let Some(n) = d.node(root) { - n.walk(&mut |c| { - if matches!(c.kind, NodeKind::Text(_)) { - texts.push(c.clone()); +/// Do what [`Kept`] `k` found to its object of `d` (`brushes`: the document's brushes, for the +/// stroke option): its type outlined, then the strokes of its leaf shapes, the outlines of its +/// type included, then its overprints dropped. → the id now standing for the object. +fn outline_kept(d: &mut Document, brushes: &[vectorcraft_brush::Brush], k: Kept, o: &FlattenOptions) -> Result<NodeId> { + let mut root = k.id; + let mut replaced = HashSet::new(); + let dropping = !o.preserve_overprints; + // Each replacement loses its overprints before it goes in: no new object is looked up. + let mut put = |d: &mut Document, old: NodeId, mut new: Node, root: &mut NodeId| -> Result<()> { + if dropping { + drop_overprints(&mut new); + } + let nid = new.id; + *d.node_mut(old).ok_or(EngineError::NoNode(old))? = new; + replaced.insert(old); + if old == *root { + *root = nid; + } + Ok(()) + }; + // The leaf shapes of each outlined type that only groups and layers hold, by step. + let mut outlined: Vec<Vec<Node>> = Vec::with_capacity(k.steps.len()); + for step in &k.steps { + let mut lv = vec![]; + if let Step::Text { id, leaf } = *step + && let Some(out) = d.node(id).and_then(outlined_text) + { + let out = d.reid(&out); + if leaf && o.strokes_to_outlines { + leaves(&out, &mut lv); } - }); + put(d, id, out, &mut root)?; + } + outlined.push(lv); } - let mut out = root; - for t in texts { - let Some(o) = outlined_text(&t) else { continue }; - let o = d.reid(&o); - let nid = o.id; - *d.node_mut(t.id).ok_or(EngineError::NoNode(t.id))? = o; - if t.id == root { - out = nid; + if o.strokes_to_outlines { + for (step, lv) in k.steps.iter().zip(outlined) { + let shapes = match *step { + Step::Leaf(id) => d.node(id).cloned().into_iter().collect(), + Step::Text { .. } => lv, + }; + for l in shapes.iter().filter(|l| !matches!(l.kind, NodeKind::Text(_))) { + if let Some(new) = outline_strokes(d, brushes, l) { + put(d, l.id, new, &mut root)?; + } + } } } - Ok(out) -} - -/// Whether the outline and overprint options change `n`, an object without transparency. -pub(super) fn kept_work(n: &Node, o: &FlattenOptions) -> bool { - let mut any = false; - n.walk(&mut |c| { - any |= (o.text_to_outlines && matches!(c.kind, NodeKind::Text(_))) - || (o.strokes_to_outlines && stroked(c)) - || (!o.preserve_overprints && overprints(c)); - }); - any + if dropping { + for (id, holder) in k.overprinted { + if holder.is_some_and(|h| replaced.contains(&h)) { + continue; + } + if let Some(n) = d.node_mut(id) { + drop_own_overprints(n); + } + } + } + Ok(root) } /// Whether `n` is a path with a visible stroke (outlining turns it into a fill). @@ -898,12 +1030,8 @@ pub(super) fn stroked(n: &Node) -> bool { && n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.visible && !s.paint.is_none() && s.width > 0.0)) } -fn overprints(n: &Node) -> bool { - n.appearance.items.iter().any(AppearanceItem::overprint) - || matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke)) -} - -fn drop_overprints(n: &mut Node) { +/// Drop the overprints of `n` itself. +fn drop_own_overprints(n: &mut Node) { if overprints(n) { for i in &mut n.appearance.items { *i.overprint_mut() = false; @@ -914,6 +1042,16 @@ fn drop_overprints(n: &mut Node) { } } } +} + +fn overprints(n: &Node) -> bool { + n.appearance.items.iter().any(AppearanceItem::overprint) + || matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke)) +} + +/// Drop the overprints of `n` and of everything under it. +fn drop_overprints(n: &mut Node) { + drop_own_overprints(n); if let Some(ch) = n.children_mut() { for c in ch { drop_overprints(Arc::make_mut(c)); @@ -994,6 +1132,208 @@ mod tests { assert_eq!(run(&[deep, deep]).0, vec![(sub, g2), (sub, g2)]); } + /// The objects [`kept_session`] makes. + struct KeptArt { + /// Each group with its stroked rectangle (its fill overprints) and its stroked type. + groups: Vec<(NodeId, NodeId, NodeId)>, + /// A stroked rectangle and stroked type with an overprint, on their own. + rect: NodeId, + text: NodeId, + /// A stroked compound path and its pieces. + compound: NodeId, + pieces: Vec<NodeId>, + /// A group holding an unstroked rectangle and a hidden stroked rectangle. + hidden_group: NodeId, + hidden: NodeId, + /// An unstroked rectangle. + plain: NodeId, + } + + /// A document without transparency: `n` groups, then the other objects of [`KeptArt`]. + fn kept_session(n: usize) -> (Session, KeptArt) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = |v: serde_json::Value| NodeId(v["id"].as_u64().unwrap()); + let rect = |s: &mut Session, x: f64| id(s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap()); + let text = |s: &mut Session, x: f64| { + let t = id(s.execute("text.create", &json!({"x": x, "y": 80, "text": "Hi", "size": 24})).unwrap()); + s.execute("paint.setStroke", &json!({"color": "#000000", "ids": [t.0]})).unwrap(); + t + }; + let select = |s: &mut Session, ids: &[NodeId]| { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap(); + }; + let overprint = |s: &mut Session, on: NodeId| { + s.execute("attributes.set", &json!({"ids": [on.0], "overprintFill": true})).unwrap(); + }; + let unstroked = |s: &mut Session, on: NodeId| { + s.execute("paint.setStroke", &json!({"none": true, "ids": [on.0]})).unwrap(); + }; + let mut groups = vec![]; + for i in 0..n { + let x = (i % 10) as f64 * 30.0; + let (r, t) = (rect(&mut s, x), text(&mut s, x)); + overprint(&mut s, r); + select(&mut s, &[r, t]); + groups.push((id(s.execute("object.group", &json!({})).unwrap()), r, t)); + } + let (r, t) = (rect(&mut s, 0.0), text(&mut s, 100.0)); + overprint(&mut s, t); + let (a, b) = (rect(&mut s, 200.0), rect(&mut s, 210.0)); + select(&mut s, &[a, b]); + let compound = id(s.execute("object.compoundPath.make", &json!({})).unwrap()); + s.execute("paint.setStroke", &json!({"color": "#000000", "ids": [compound.0]})).unwrap(); + let pieces = s.doc().unwrap().doc.node(compound).unwrap().children().unwrap().iter().map(|c| c.id).collect(); + let (shown, hidden) = (rect(&mut s, 300.0), rect(&mut s, 310.0)); + unstroked(&mut s, shown); + select(&mut s, &[shown, hidden]); + let hidden_group = id(s.execute("object.group", &json!({})).unwrap()); + s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap(); + let plain = rect(&mut s, 350.0); + unstroked(&mut s, plain); + (s, KeptArt { groups, rect: r, text: t, compound, pieces, hidden_group, hidden, plain }) + } + + /// Every option on: type and strokes outlined, overprints dropped. + fn outlining() -> FlattenOptions { + FlattenOptions { text_to_outlines: true, strokes_to_outlines: true, preserve_overprints: false, ..FlattenOptions::default() } + } + + /// The top-level objects of `d`'s first layer, in paint order. + fn top_level(d: &Document) -> Vec<NodeId> { + d.layers[0].children().unwrap().iter().map(|c| c.id).collect() + } + + fn sorted(mut ids: Vec<NodeId>) -> Vec<NodeId> { + ids.sort(); + ids + } + + /// The nodes [`Kept::of`] looked at while `f` ran, sorted. + fn kept_seen_by(f: impl FnOnce()) -> Vec<NodeId> { + KEPT_SEEN.with(|v| v.borrow_mut().clear()); + f(); + sorted(KEPT_SEEN.with(|v| v.take())) + } + + /// The Flattener Preview, `object.flattenTransparency` and flattening a whole document each look + /// at every node of the objects without transparency once, with type and strokes outlined and + /// overprints dropped, an object they leave as it is included. + #[test] + fn kept_objects_are_looked_at_once() { + let (mut s, _) = kept_session(100); + let o = outlining(); + let doc = s.doc().unwrap().doc.clone(); + let roots = top_level(&doc); + let mut nodes = vec![]; + for r in &roots { + doc.node(*r).unwrap().walk(&mut |c| nodes.push(c.id)); + } + nodes.sort(); + assert_eq!(nodes.len(), 309); + let preview = kept_seen_by(|| drop(super::super::report::report(&doc, &roots, &o).unwrap())); + assert!(preview == nodes, "the preview looked at {} nodes of {}", preview.len(), nodes.len()); + let whole = kept_seen_by(|| drop(flatten_document(&doc, &o).unwrap().unwrap())); + assert!(whole == nodes, "flattening the document looked at {} nodes of {}", whole.len(), nodes.len()); + let ids: Vec<u64> = roots.iter().map(|r| r.0).collect(); + let command = kept_seen_by(|| { + s.execute( + "object.flattenTransparency", + &json!({"ids": ids, "textToOutlines": true, "strokesToOutlines": true, "preserveOverprints": false}), + ) + .unwrap(); + }); + assert!(command == nodes, "object.flattenTransparency looked at {} nodes of {}", command.len(), nodes.len()); + } + + /// [`apply`]'s outlining of `kept` (objects of `d` without transparency) with `o`, done as a + /// walk of each object for each option: → the ids standing for them, in paint order. + fn outlined_walk_by_walk(d: &mut Document, kept: &[NodeId], o: &FlattenOptions) -> Vec<NodeId> { + let brushes = if o.strokes_to_outlines { vectorcraft_brush::library(d) } else { vec![] }; + let mut ids = vec![]; + for &root in kept { + let mut id = root; + if o.text_to_outlines { + let mut texts = vec![]; + d.node(id).unwrap().walk(&mut |c| { + if matches!(c.kind, NodeKind::Text(_)) { + texts.push(c.clone()); + } + }); + for t in texts { + let Some(out) = outlined_text(&t) else { continue }; + let out = d.reid(&out); + if t.id == root { + id = out.id; + } + *d.node_mut(t.id).unwrap() = out; + } + } + if o.strokes_to_outlines { + id = crate::cmd::pathops::outline_strokes_under(d, &brushes, id).unwrap().0; + } + if !o.preserve_overprints { + drop_overprints(d.node_mut(id).unwrap()); + } + ids.push(id); + } + ids.sort_by_key(|id| d.index_path(*id)); + ids + } + + /// With each mix of the text, stroke and overprint options, the objects without transparency + /// end as a walk of each of them for each option leaves them: the same art, ids and selection. + #[test] + fn kept_objects_change_as_a_walk_per_option_changes_them() { + let (s, _) = kept_session(3); + let doc = Document::clone(&s.doc().unwrap().doc); + let roots = top_level(&doc); + for bits in 0..8u8 { + let o = FlattenOptions { + text_to_outlines: bits & 1 != 0, + strokes_to_outlines: bits & 2 != 0, + preserve_overprints: bits & 4 != 0, + ..FlattenOptions::default() + }; + let p = plan(&doc, &roots, &o, true).unwrap(); + assert!(p.flat.is_empty(), "{o:?}"); + // In the order the plan's groups come in. + let kept = p.kept.clone(); + assert_eq!(sorted(kept.clone()), sorted(roots.clone()), "{o:?}"); + let mut once = doc.clone(); + let mut sel = vectorcraft_doc::Selection::default(); + let (ids, ..) = apply(&mut once, &mut sel, p, &o).unwrap(); + let mut walked = doc.clone(); + let want = outlined_walk_by_walk(&mut walked, &kept, &o); + assert_eq!(ids, want, "{o:?}"); + assert!(once == walked, "{o:?}"); + assert_eq!(once == doc, bits == 4, "{o:?}: only with every option off does nothing change"); + } + } + + /// The Flattener Preview lists the kept objects the options change, and of those the type and + /// the stroked paths that show and are not pieces of a compound path. + #[test] + fn the_preview_lists_what_the_options_change_in_kept_objects() { + let (s, a) = kept_session(2); + let doc = &s.doc().unwrap().doc; + let roots = top_level(doc); + let r = super::super::report::report(doc, &roots, &outlining()).unwrap(); + let (g, rects, texts): (Vec<_>, Vec<_>, Vec<_>) = + (a.groups.iter().map(|g| g.0).collect(), a.groups.iter().map(|g| g.1).collect(), a.groups.iter().map(|g| g.2).collect()); + assert_eq!(r.affected, [g.clone(), vec![a.rect, a.text, a.compound, a.hidden_group]].concat()); + // Both lists come in the order the plan's groups do. + assert_eq!(sorted(r.text.clone()), sorted([texts, vec![a.text]].concat())); + assert_eq!(sorted(r.strokes.clone()), sorted([rects, vec![a.rect, a.compound]].concat())); + assert!(!r.strokes.contains(&a.hidden) && !r.strokes.iter().any(|id| a.pieces.contains(id)) && !r.affected.contains(&a.plain)); + // Dropping overprints alone changes the objects that overprint. + let o = FlattenOptions { preserve_overprints: false, ..FlattenOptions::default() }; + let r = super::super::report::report(doc, &roots, &o).unwrap(); + assert_eq!((r.affected, r.text, r.strokes), ([g, vec![a.text]].concat(), vec![], vec![])); + // With every option off, nothing. + assert!(super::super::report::report(doc, &roots, &FlattenOptions::default()).unwrap().affected.is_empty()); + } + /// In a file without transparency with Clip Complex Regions on, art under a group's opaque /// image within one of its pixels joins the group, also where a long image is made at a lower /// resolution and its pixels are wider than at the preset's. diff --git a/crates/engine/src/cmd/flatten/options.rs b/crates/engine/src/cmd/flatten/options.rs index 16cf8e5de7..2d558ea2e2 100644 --- a/crates/engine/src/cmd/flatten/options.rs +++ b/crates/engine/src/cmd/flatten/options.rs @@ -1,5 +1,5 @@ use super::analysis::draws_image; -use super::apply::{apply, kept_work, plan}; +use super::apply::{apply, plan}; use super::presets::{FlattenerPreset, saved_preset}; use super::report::target_roots; use super::{BTreeSet, Deserialize, Document, EngineError, Node, NodeKind, Paint, Result, Serialize, Session, Value, bad, json, str_param}; @@ -194,7 +194,7 @@ pub(super) fn flatten(s: &mut Session, p: &Value) -> Result<Value> { let plan = plan(&src, &roots, &o, true)?; let warning = crate::cmd::rasterfx::undecoded_warning(failed); let options = serde_json::to_value(&o).unwrap_or_default(); - if plan.flat.is_empty() && !plan.kept.iter().any(|id| src.node(*id).is_some_and(|n| kept_work(n, &o))) { + if plan.flat.is_empty() && !plan.work.iter().any(|k| k.changes) { return Ok(json!({ "ids": roots.iter().map(|i| i.0).collect::<Vec<_>>(), "rasterized": 0, "vector": 0, "options": options })); } let (ids, vector, rasterized) = s.edit("Flatten Transparency", |d, sel| { diff --git a/crates/engine/src/cmd/flatten/report.rs b/crates/engine/src/cmd/flatten/report.rs index 41b08b7a05..650309d424 100644 --- a/crates/engine/src/cmd/flatten/report.rs +++ b/crates/engine/src/cmd/flatten/report.rs @@ -1,4 +1,4 @@ -use super::apply::{kept_work, opaque, plan, stroked}; +use super::apply::{opaque, plan, stroked}; use super::options::FlattenOptions; use super::{ Appearance, Color, Deserialize, Document, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, Serialize, Session, Value, bad, isolated_doc, @@ -263,15 +263,10 @@ pub fn report(doc: &Document, roots: &[NodeId], o: &FlattenOptions) -> Result<Fl r.rasterized.push(a.outline()); } } - for root in plan.kept.iter().filter_map(|id| doc.node(*id)).filter(|n| kept_work(n, o)) { - r.affected.push(root.id); - visit(root, &mut |n| { - if o.text_to_outlines && matches!(n.kind, NodeKind::Text(_)) { - r.text.push(n.id); - } else if o.strokes_to_outlines && stroked(n) { - r.strokes.push(n.id); - } - }); + for k in plan.work.iter().filter(|k| k.changes) { + r.affected.push(k.id); + r.text.extend(&k.shown_text); + r.strokes.extend(&k.shown_strokes); } r.affected.sort_by_key(|id| doc.index_path(*id)); Ok(r) diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs index 28662f013c..f98386bcf1 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -53,6 +53,24 @@ pub fn specs() -> Vec<CommandSpec> { always, font_list ), + cmd!( + query "text.similarFonts", + "Show Similar Fonts", + [], + None, + "{family (any of its names), limit?: whole number 1..100000 (default: all)} → {family: the family's own name, families: [names]}: the families `text.fontList` lists, ordered as a font menu's Show Similar Fonts orders them: the family itself first, then those that set the same script (Japanese, Thai or neither), then the others, each group nearest first by VectorCraft's own measure of the faces nearest an upright Regular (OS/2 PANOSE digits, weight and width classes, x-height, cap height and average character width, the italic angle, and the kind; a family that shares none of these numbers with it comes after those that share one); an error when the family isn't available or the font menus don't list it, or `limit` is not a whole number from 1 to 100000", + always, + similar_fonts + ), + cmd!( + query "text.glyphCategories", + "Glyph Categories", + [], + None, + "{family, style?} the OpenType categories of the font's glyphs, what the Glyphs panel's Show menu lists after Alternates for Current Selection: from the font's GSUB table, the glyphs that the single, alternate, multiple and ligature substitutions of each kind's features give, each glyph once by id, in this order: `ligatures` (liga, dlig, hlig), `swashes` (swsh, cswh), `stylisticAlternates` (salt), `ss01` to `ss20`, `smallCaps` (smcp, c2sc), `ornaments` (ornm), `fractions` (frac, afrc, numr, dnom) and `figures` (lnum, onum, pnum, tnum); a kind without glyphs is left out; contextual lookups are not followed → {family, style, categories: [{id, name?: a stylistic set's name in the font, glyphs: [glyph id]}]} (style omitted: the family's first style; an error when the family or style isn't available)", + always, + glyph_categories + ), cmd!( "text.rescanFonts", "Refresh Font List", @@ -1137,6 +1155,74 @@ fn font_list(_: &mut Session, p: &Value) -> Result<Value> { } } +/// The most families `text.similarFonts` takes as its `limit`. +const MAX_SIMILAR: u64 = 100_000; + +fn similar_fonts(_: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "text.similarFonts"; + let db = vectorcraft_text::FontDb::global(); + let family = match p.get("family") { + Some(Value::String(f)) if !f.trim().is_empty() => f.as_str(), + Some(Value::String(_)) | None => return Err(bad(C, "`family` is required")), + Some(_) => return Err(bad(C, "`family` must be a string")), + }; + let limit = match p.get("limit") { + None => None, + Some(v) => Some( + v.as_u64() + .filter(|n| (1..=MAX_SIMILAR).contains(n)) + .ok_or_else(|| bad(C, format!("`limit` must be a whole number from 1 to {MAX_SIMILAR}")))?, + ), + }; + // Any of the family's names, spelled as the font menus list it; a family they don't list is not available. + let menu = db.menu_family_list(); + let listed = db.has_family(family).then(|| db.canonical(family, "").0).and_then(|c| menu.iter().find(|f| f.eq_ignore_ascii_case(&c)).cloned()); + let Some(family) = listed else { return Err(bad(C, format!("font family `{family}` is not available"))) }; + let mut families = db.similar_families(&family, &menu); + if let Some(n) = limit.and_then(|n| usize::try_from(n).ok()) { + families.truncate(n); + } + Ok(json!({ "family": family, "families": families })) +} + +/// `text.glyphCategories`: the OpenType categories of a font's glyphs +/// ([`vectorcraft_text::FontFace::glyph_categories`]). +fn glyph_categories(_: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "text.glyphCategories"; + let text = |key: &str| match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(s)) => Ok(Some(s.as_str())), + Some(_) => Err(bad(C, format!("`{key}` must be a string"))), + }; + let family = text("family")?.ok_or_else(|| bad(C, "missing `family`"))?; + let db = vectorcraft_text::FontDb::global(); + if !db.has_family(family) { + return Err(bad(C, format!("font family `{family}` is not available"))); + } + let styles = db.styles(family); + let style = match text("style")? { + Some(style) => styles + .iter() + .find(|s| s.eq_ignore_ascii_case(style)) + .cloned() + .ok_or_else(|| bad(C, format!("style `{style}` of `{family}` is not available")))?, + None => styles.first().cloned().unwrap_or_else(|| "Regular".into()), + }; + let face = db.face(family, &style).ok_or_else(|| bad(C, format!("style `{style}` of `{family}` is not available")))?; + let categories: Vec<Value> = face + .glyph_categories() + .iter() + .map(|c| { + let mut v = json!({"id": c.kind.id(), "glyphs": c.glyphs}); + if let Some(name) = &c.name { + v["name"] = json!(name); + } + v + }) + .collect(); + Ok(json!({"family": face.family, "style": face.style, "categories": categories})) +} + pub(crate) fn rescan(s: &mut Session, _: &Value) -> Result<Value> { let db = vectorcraft_text::FontDb::global(); #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/cmd/freeform.rs b/crates/engine/src/cmd/freeform.rs index ad0164a62c..71a5e36ccf 100644 --- a/crates/engine/src/cmd/freeform.rs +++ b/crates/engine/src/cmd/freeform.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> { "Add Freeform Point", [], None, - "{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind; the points on a label's characters are not stored → {index}", + "{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its points); the points on a label's characters are not stored → {index}", has_doc, add_point ), diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 97917a2469..af0f4cfcda 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> { "Gradient", ["Window", "Gradient"], None, - "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters their gradient without its placement, fitted to each label", + "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label", has_doc, edit_gradient ), @@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> { "Gradient Vector", [], None, - "{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters their gradient without the placement this command sets, fitted to each label", + "{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without the placement this command sets, fitted to each label", has_doc, set_gradient_geom ), @@ -534,7 +534,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> { // Objects were given or selected, even when all of them are graph design art left out below: the stroke mode is then // not one for new art. let selected = !ids.is_empty(); - let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids); + let ids = super::appearance::drop_design_art_rows(s, ids, item, !stroke, C)?; // How the gradient lies on a stroke (the panel's Stroke buttons). let mode = match str_param(p, "strokeMode") { None => None, @@ -558,7 +558,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> { _ => None, }); let for_default = match p.get("aspect").and_then(Value::as_f64) { - Some(a) if a < 0.0 && !ids.is_empty() && default_kind != Some(GradientKind::Conic) => { + Some(a) if a < 0.0 && selected && default_kind != Some(GradientKind::Conic) => { let mut q = p.clone(); q["aspect"] = json!(-a); std::borrow::Cow::Owned(q) @@ -568,7 +568,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> { // A spread for selected gradients leaves a freeform default (which has no ends) as it is. let spreads = matches!(spread_param(p), Ok(Some(sp)) if !sp.is_pad()); let for_default = match for_default { - q if spreads && !ids.is_empty() && default_kind == Some(GradientKind::Freeform) => { + q if spreads && selected && default_kind == Some(GradientKind::Freeform) => { let mut q = q.into_owned(); if let Some(o) = q.as_object_mut() { o.remove("spread"); @@ -579,8 +579,14 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> { }; let new_default = apply_gradient_edit_in_model(&default_paint, &with_stored_stops(&for_default, &default_paint, &stored), None, &|_| true, model) .map_err(|e| bad(C, e))?; - let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform); let of = super::appearance::reference_of(s, p, item, C)?; + // Only design art was given or selected: nothing changes, the defaults and the remembered paint included. + if selected && ids.is_empty() { + // An aligned `item` of the art alone is still checked: a row the art lacks, or that no other object has, is an error. + edit_items(s, &ids, item, of, C, "Gradient", !stroke, |_, _| Ok(()))?; + return Ok(json!({"ids": []})); + } + let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform); let shown_at = super::appearance::first_edited(s, item, of, &ids); // The objects returned: with a design's art, those with a row equal to the art's. let edited = edit_items(s, &ids, item, of, C, "Gradient", !stroke, |n, index| { @@ -770,7 +776,7 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result<Value> { if targets.is_empty() { return Err(EngineError::Other("nothing selected".into())); } - let targets = super::appearance::drop_design_art(&s.doc()?.doc, targets); + let targets = super::appearance::drop_design_art_rows(s, targets, item, !stroke, C)?; let model = super::paint::new_color_model(s, &Value::Null); let of = super::appearance::reference_of(s, p, item, C)?; // The objects returned: with a design's art, those with a row equal to the art's. diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 7be0a122df..301d361a1a 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -48,10 +48,12 @@ use generate::generate; #[cfg(test)] use series::default_series_color; pub(crate) use series::{ - LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows, - capture_label_styles, capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, is_design_art, - label_object_opacity_differs, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where, series_groups_among, - series_marks_in, series_object_opacity_differs, shown_paint, + LabelTextChange, RowWrites, capture_label_anti_alias, capture_label_changes, capture_label_kind_rows, capture_label_object_opacity, + capture_label_paragraphs, capture_label_rows, capture_label_styles, capture_label_styles_given, capture_label_text, capture_line_changes, + capture_line_fill_stroke_rows, capture_line_kind_rows, capture_line_paint_writes, capture_line_row_writes, capture_line_rows, + capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, follow_wedge_shades, graph_part_members, is_design_art, + is_graph_line, label_object_opacity_differs, label_rows, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where, + series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, wedge_shades, }; #[cfg(test)] diff --git a/crates/engine/src/cmd/graph/commands.rs b/crates/engine/src/cmd/graph/commands.rs index 7084fe19f6..27da7936a8 100644 --- a/crates/engine/src/cmd/graph/commands.rs +++ b/crates/engine/src/cmd/graph/commands.rs @@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> { "Type…", ["Object", "Graph"], None, - "{id?, type?, seriesIndexes?: [index], columnWidth?: % (1–1000; past 100 columns overlap), clusterWidth?: % (1–1000), legend?: bool, markPoints?: bool, connectPoints?: bool, edgeToEdge?: bool (line graphs: true runs the lines across the whole plot, false puts the points at the centres of their categories), ticks?: n, axisMin?: number|null (null = calculated), axisMax?: number|null, valueAxis?: left|right|both (the bar graphs' value axis stays along the bottom), separateScales?: bool, rightTicks?: n, rightAxisMin?, rightAxisMax?, tickLength?: none|short|full, tickMarks?: n per division, rightTickLength?, rightTickMarks?, categoryTickLength?: none|short|full, categoryTickMarks?: n, ticksBetweenLabels?: bool, prefix?, suffix?, rightPrefix?, rightSuffix?: text around the value axis numbers, firstRowInFront?: bool, firstColumnInFront?: bool (which overlapping columns are drawn on top: the first category over the next within each series, the first series over the others), filledLines?: bool (Draw Filled Lines: connecting lines as 3 pt bands filled with the series colour), dropShadow?: bool (Add Drop Shadow: a translucent black shadow down and right of the columns, bars, lines and pie wedges), legendAcrossTop?: bool (Add Legend Across Top: the legend in rows above the plot), pieLegend?: none|standard|wedges (Legends in Wedges: the series labels inside their wedges), piePosition?: ratio|even|stacked (several pies sized by their totals, at one size (the default), or stacked), pieSort?: all|first|none (wedges largest first in each pie, in the first pie's order, or in data order (the default)); the query lists the pie options for pie graphs} change the graph type and options; with `seriesIndexes`, or (no `id`) with only series selected with Group Selection, `type` goes to those series only and `valueAxis` (left|right; both is refused) puts them on that value axis, while the other options still apply to the whole graph (Combine different graph types: column, stacked column, line and area mix, and so do bar and stacked bar; a series given the graph's type follows the graph again) (axisMin and axisMax together override the calculated value axis: exactly that range in `ticks` divisions, 5 when 0; with the value axis on both sides, separateScales gives the series on the right axis a scale of their own, set the same way with rightTicks, rightAxisMin and rightAxisMax); a value of the wrong type, such as \"10\" for a number or \"true\" for a bool, or a negative count, is refused and the graph stays as it was; a null is read as a key left out, except that a null axis bound goes back to the calculated value; no options → the current ones", + "{id?, type?, seriesIndexes?: [index], columnWidth?: % (1–1000; past 100 columns overlap), clusterWidth?: % (1–1000), legend?: bool, markPoints?: bool, connectPoints?: bool, edgeToEdge?: bool (line graphs: true runs the lines across the whole plot, false puts the points at the centres of their categories), ticks?: n, axisMin?: number|null (null = calculated), axisMax?: number|null, valueAxis?: left|right|both (the bar graphs' value axis stays along the bottom), separateScales?: bool, rightTicks?: n, rightAxisMin?, rightAxisMax?, tickLength?: none|short|full, tickMarks?: n per division, rightTickLength?, rightTickMarks?, categoryTickLength?: none|short|full, categoryTickMarks?: n, ticksBetweenLabels?: bool, prefix?, suffix?, rightPrefix?, rightSuffix?: text around the value axis numbers, firstRowInFront?: bool, firstColumnInFront?: bool (which overlapping columns are drawn on top: the first category over the next within each series, the first series over the others), filledLines?: bool (Draw Filled Lines: connecting lines as bands `lineWidth` wide filled with the series colour), lineWidth?: pt (Line Width of Draw Filled Lines: 0.01–1000; 3), dropShadow?: bool (Add Drop Shadow: a translucent black shadow down and right of the columns, bars, lines and pie wedges), legendAcrossTop?: bool (Add Legend Across Top: the legend in rows above the plot), pieLegend?: none|standard|wedges (Legends in Wedges: the series labels inside their wedges), piePosition?: ratio|even|stacked (several pies sized by their totals, at one size (the default), or stacked), pieSort?: all|first|none (wedges largest first in each pie, in the first pie's order, or in data order (the default)); the query lists the pie options for pie graphs} change the graph type and options; with `seriesIndexes`, or (no `id`) with only series selected with Group Selection, `type` goes to those series only and `valueAxis` (left|right; both is refused) puts them on that value axis, while the other options still apply to the whole graph (Combine different graph types: column, stacked column, line and area mix, and so do bar and stacked bar; a series given the graph's type follows the graph again) (axisMin and axisMax together override the calculated value axis: exactly that range in `ticks` divisions, 5 when 0; with the value axis on both sides, separateScales gives the series on the right axis a scale of their own, set the same way with rightTicks, rightAxisMin and rightAxisMax); a value of the wrong type, such as \"10\" for a number or \"true\" for a bool, or a negative count, is refused and the graph stays as it was; options that leave the graph as it is record no step of history; a null is read as a key left out, except that a null axis bound goes back to the calculated value; no options → the current ones", has_selection, set_type ), diff --git a/crates/engine/src/cmd/graph/edit.rs b/crates/engine/src/cmd/graph/edit.rs index 378a8e3745..728eff6427 100644 --- a/crates/engine/src/cmd/graph/edit.rs +++ b/crates/engine/src/cmd/graph/edit.rs @@ -230,6 +230,7 @@ fn query_type_options(spec: &GraphSpec, count: usize, picked: &[usize]) -> Value "prefix": one_line(&spec.prefix), "suffix": one_line(&spec.suffix), "rightPrefix": one_line(&spec.right_prefix), "rightSuffix": one_line(&spec.right_suffix), "dropShadow": spec.drop_shadow, "legendAcrossTop": spec.legend_across_top, "firstRowInFront": spec.first_row_in_front, "firstColumnInFront": spec.first_column_in_front, "filledLines": spec.filled_lines, + "lineWidth": spec.filled_line_width(), }); // Only the options this graph's types use: overlap order for columns and bars, filled lines for lines. let kinds: Vec<GraphKind> = (0..count.max(1)).map(|i| spec.series_kind(i)).collect(); @@ -241,6 +242,7 @@ fn query_type_options(spec: &GraphSpec, count: usize, picked: &[usize]) -> Value } if !has(&[GraphKind::Line, GraphKind::Scatter, GraphKind::Radar]) { o.remove("filledLines"); + o.remove("lineWidth"); } } // Pie graphs: Legend, Position and Sort (their Legend stands for the legend checkbox). @@ -266,6 +268,7 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "graph.setType"; let id = target(s, p, C)?; let mut spec = spec_of(s, id)?; + let stored = spec.clone(); // The series to retype: `seriesIndexes`, else, with no `id`, a selection made only of this graph's series (Group // Selection). Anything else selected, the graph itself for one, is the whole graph. let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).min(vectorcraft_doc::MAX_GRAPH_SERIES); @@ -311,6 +314,7 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> { "firstRowInFront", "firstColumnInFront", "filledLines", + "lineWidth", "pieLegend", "piePosition", "pieSort", @@ -404,6 +408,15 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> { spec.first_row_in_front = switch_or(p, "firstRowInFront", spec.first_row_in_front, C)?; spec.first_column_in_front = switch_or(p, "firstColumnInFront", spec.first_column_in_front, C)?; spec.filled_lines = switch_or(p, "filledLines", spec.filled_lines, C)?; + if let Some(w) = p.get("lineWidth").filter(|v| !v.is_null()) { + let w = w.as_f64().ok_or_else(|| bad(C, format!("`lineWidth` must be a number, not {w}")))?; + let (min, max) = (vectorcraft_doc::MIN_FILLED_LINE_WIDTH, vectorcraft_doc::MAX_FILLED_LINE_WIDTH); + if !(min..=max).contains(&w) { + return Err(bad(C, format!("`lineWidth` must be from {min} to {max} pt, not {w}"))); + } + // The default width is stored as no width. + spec.line_width = (w != vectorcraft_doc::DEFAULT_FILLED_LINE_WIDTH).then_some(w); + } spec.legend_across_top = switch_or(p, "legendAcrossTop", spec.legend_across_top, C)?; // After `legend`, which the Graph Type dialog sends too. if let Some(v) = text_param(p, "pieLegend", C)? { @@ -418,6 +431,10 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> { spec.connect_points = switch_or(p, "connectPoints", spec.connect_points, C)?; spec.edge_to_edge = switch_or(p, "edgeToEdge", spec.edge_to_edge, C)?; spec.ticks = count_given(p, "ticks", 100, C)?.unwrap_or(spec.ticks); + // Options that leave the graph as it is record no step of history. + if spec == stored { + return Ok(json!({ "id": id.0 })); + } let label = format!("{} Graph", spec.kind.label()); s.edit("Graph Type", |d, sel| { regenerate(d, id, spec)?; diff --git a/crates/engine/src/cmd/graph/generate.rs b/crates/engine/src/cmd/graph/generate.rs index f589ed9ae5..7341636a90 100644 --- a/crates/engine/src/cmd/graph/generate.rs +++ b/crates/engine/src/cmd/graph/generate.rs @@ -393,6 +393,16 @@ impl<'a> Plot<'a> { series_marks(self.g, i, series_fill, stroke, width) } + /// The stroke paint and width series `s`'s filled marks and its legend swatch get when the series keeps no stroke + /// of its own: a white line between stacked segments, area bands and pie wedges, none on other marks. + fn mark_stroke(&self, s: usize) -> (Paint, f64) { + match self.kind(s) { + GraphKind::StackedColumn | GraphKind::StackedBar | GraphKind::Area => (Paint::solid(Color::WHITE), 0.25), + GraphKind::Pie => (Paint::solid(Color::WHITE), 0.5), + _ => (Paint::None, 0.0), + } + } + fn series_label(&self, i: usize) -> String { self.g.series.get(i).cloned().unwrap_or_default() } @@ -471,7 +481,8 @@ impl<'a> Plot<'a> { } let sweep = v / total * std::f64::consts::TAU; let bp = wedge_path(ring, a0, sweep); - let (fill, stroke, sw) = self.mark(s, true, Paint::solid(Color::WHITE), 0.5); + let (stroke, width) = self.mark_stroke(s); + let (fill, stroke, sw) = self.mark(s, true, stroke, width); let dark = is_dark(&fill); let n = self.b.path(PathData::from_bezpath(&bp), fill, stroke, sw); self.push_shadowed(s, n); @@ -532,7 +543,7 @@ impl<'a> Plot<'a> { } for v in tick_values(lo, hi, step).into_iter().skip(1) { let ring: Vec<Point> = (0..ncat).map(|c| at(c, v)).collect(); - axes.push(self.b.path(polyline(&ring, true), Paint::None, Paint::solid(Color::rgb(0.6, 0.6, 0.6)), 0.25)); + axes.push(self.b.ring(polyline(&ring, true))); } let ax = self.b.group("Axes", axes); self.b.out.push(ax); @@ -887,7 +898,8 @@ impl<'a> Plot<'a> { let Some(base) = (if v >= 0.0 { pos.get_mut(ax) } else { neg.get_mut(ax) }) else { continue }; let (v0, v1) = (geo.vpos(ax, *base), geo.vpos(ax, *base + v)); *base += v; - let paint = self.mark(s, true, Paint::solid(Color::WHITE), 0.25); + let (stroke, width) = self.mark_stroke(s); + let paint = self.mark(s, true, stroke, width); let rect = bar_rect(geo.horizontal, a, w, v0, v1); // A segment of 0 has no area to shade. let n = self.bar_node(Bar { s, rect, value: v, down: v1 < v0, per_unit: geo.per_unit(ax) }, paint, v != 0.0); @@ -907,7 +919,8 @@ impl<'a> Plot<'a> { let at = |c: usize, v: &[f64]| Point::new(geo.cat_mid(c), geo.vpos(a, v.get(c).copied().unwrap_or(0.0))); let mut pts: Vec<Point> = (0..ncat).map(|c| at(c, &above)).collect(); pts.extend((0..ncat).rev().map(|c| at(c, below))); - let (fill, stroke, w) = self.mark(s, true, Paint::solid(Color::WHITE), 0.25); + let (stroke, width) = self.mark_stroke(s); + let (fill, stroke, w) = self.mark(s, true, stroke, width); let n = self.b.path(polyline(&pts, true), fill, stroke, w); self.push_series(s, n); *below = above; @@ -951,10 +964,11 @@ impl<'a> Plot<'a> { } /// The swatch of series `s` at `(x, y)`: series drawn with markers show their marker design in the legend, and - /// series drawn with a column design that design. + /// series drawn with a column design that design. A default swatch has the stroke of its series' marks. fn legend_swatch(&mut self, s: usize, (x, y): (f64, f64)) { let marked = matches!(self.g.kind, GraphKind::Scatter | GraphKind::Radar) || self.kind(s) == GraphKind::Line; - let paint = self.mark(s, true, Paint::None, 0.0); + let (stroke, width) = self.mark_stroke(s); + let paint = self.mark(s, true, stroke, width); let column = nth(self.column_looks, s).filter(|_| self.columnar(s)); let swatch = self.b.swatch(column, nth(&self.designs, s).filter(|_| marked), Rect::new(x, y, x + 8.0, y + 8.0), paint); self.push_series(s, swatch); diff --git a/crates/engine/src/cmd/graph/labels.rs b/crates/engine/src/cmd/graph/labels.rs index 8e56ad8ae6..b5d5632356 100644 --- a/crates/engine/src/cmd/graph/labels.rs +++ b/crates/engine/src/cmd/graph/labels.rs @@ -82,9 +82,49 @@ fn kept_rows(styles: &vectorcraft_doc::LabelStyles, role: Role) -> Option<&vecto } } -/// Give label `n` the object rows `kept` keeps: a fill row and a stroke row for the kept paints, in their kept order and -/// place relative to the characters, and the object opacity and blend mode. An opacity read from a file is held to 0..1 -/// and a weight to 0..1000 pt; one that is not a number is left out (a stroke then takes 1 pt). +/// What a graph line is, for the rows it keeps: an axis line or tick mark, or a ring of a radar graph. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Line { + Axis, + Ring, +} + +impl Line { + /// The stroke and weight the graph draws lines of this kind with when they keep no rows. They have no fill. + fn default_stroke(self) -> (Paint, f64) { + match self { + Line::Axis => (Paint::solid(Color::BLACK), 0.5), + Line::Ring => (Paint::solid(Color::rgb(0.6, 0.6, 0.6)), 0.25), + } + } + + /// The rows ([`super::series::label_rows`]) a line of this kind shows as the graph draws it with no kept rows. + pub(super) fn default_rows(self) -> vectorcraft_doc::LabelRows { + let (stroke, width) = self.default_stroke(); + let paint = vectorcraft_doc::SeriesPaint { fill: Some(Paint::None), stroke: Some(stroke), stroke_width: Some(width), ..Default::default() }; + vectorcraft_doc::LabelRows { paint, ..Default::default() } + } +} + +/// The rows lines of kind `line` keep, if any. +pub(super) fn kept_line_rows(styles: &vectorcraft_doc::LabelStyles, line: Line) -> Option<&vectorcraft_doc::LabelRows> { + match line { + Line::Axis => styles.axis_rows.as_ref(), + Line::Ring => styles.ring_rows.as_ref(), + } +} + +/// The slot of `styles` that holds the rows lines of kind `line` keep. +pub(super) fn line_slot(styles: &mut vectorcraft_doc::LabelStyles, line: Line) -> &mut Option<vectorcraft_doc::LabelRows> { + match line { + Line::Axis => &mut styles.axis_rows, + Line::Ring => &mut styles.ring_rows, + } +} + +/// Give label or graph line `n` the object rows `kept` keeps: a fill row and a stroke row for the kept paints, in their +/// kept order and place relative to the contents, and the object opacity and blend mode. An opacity read from a file is +/// held to 0..1 and a weight to 0..1000 pt; one that is not a number is left out (a stroke then takes 1 pt). fn apply_label_rows(n: &mut Node, kept: &vectorcraft_doc::LabelRows) { use vectorcraft_doc::{AppearanceItem, FillLayer, StrokeLayer}; let rows = &kept.paint; @@ -124,7 +164,20 @@ impl Gen<'_> { let mut bp = BezPath::new(); bp.move_to(a); bp.line_to(b); - self.path(PathData::from_bezpath(&bp), Paint::None, Paint::solid(Color::BLACK), 0.5) + self.kept_line(Line::Axis, PathData::from_bezpath(&bp)) + } + /// A ring of a radar graph through `pd`. + pub(super) fn ring(&mut self, pd: PathData) -> Arc<Node> { + self.kept_line(Line::Ring, pd) + } + /// A graph line of kind `line` through `pd`, with the rows lines of its kind keep, else its default stroke. + fn kept_line(&mut self, line: Line, pd: PathData) -> Arc<Node> { + let (stroke, width) = line.default_stroke(); + let mut n = Node::path(self.d.alloc_id(), pd, Appearance::basic(Paint::None, stroke, width)); + if let Some(rows) = kept_line_rows(self.styles, line) { + apply_label_rows(&mut n, rows); + } + Arc::new(n) } pub(super) fn text(&mut self, role: Role, at: Point, s: &str, justify: Justify) -> Arc<Node> { let t = self.text_object(role, at, s, justify); @@ -177,10 +230,11 @@ impl Gen<'_> { Arc::new(g) } /// A series' line joining its data points (Connect Data Points): a 1 pt stroke in the series colour, or with Draw - /// Filled Lines a band FILLED_LINE_WIDTH wide filled with it and outlined in black. + /// Filled Lines a band as wide as the graph's Line Width ([`GraphSpec::filled_line_width`]) filled with it and outlined + /// in black. pub(super) fn data_line(&mut self, g: &GraphSpec, s: usize, pd: PathData, filled: bool) -> Arc<Node> { let band = if filled { - vectorcraft_pathops::outline_stroke(&pd, FILLED_LINE_WIDTH, vectorcraft_pathops::Cap::Butt, vectorcraft_pathops::Join::Miter, 4.0) + vectorcraft_pathops::outline_stroke(&pd, g.filled_line_width(), vectorcraft_pathops::Cap::Butt, vectorcraft_pathops::Join::Miter, 4.0) } else { PathData::default() }; @@ -190,7 +244,7 @@ impl Gen<'_> { let slot = g.series_paints.get(s); let fill = slot.and_then(|p| p.fill.clone().or_else(|| p.stroke.clone().filter(|st| !st.is_none()))).unwrap_or_else(|| default_series_paint(s)); - return self.path(band, fill, Paint::solid(Color::BLACK), 0.25); + return self.path(band, fill, Paint::solid(Color::BLACK), vectorcraft_doc::FILLED_LINE_OUTLINE_WIDTH); } let (fill, stroke, w) = series_marks(g, s, false, default_series_paint(s), 1.0); self.path(pd, fill, stroke, w) @@ -234,9 +288,6 @@ const SHADOW_OFFSET: f64 = 2.0; pub(super) const SHADOW_OPACITY: f32 = 0.35; -/// Draw Filled Lines: how wide a filled line is. -const FILLED_LINE_WIDTH: f64 = 3.0; - const FILLED_LINE_BUDGET: usize = 20_000; /// Does graph `g`, with `series` series, draw Filled Lines (up to FILLED_LINE_BUDGET data points)? diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index ee33f23517..c79f795b50 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -1,9 +1,10 @@ use vectorcraft_color::BlendMode; +use vectorcraft_doc::swatches::walk_with_masks; use vectorcraft_geom::Shape; use super::axis::radar_axis; use super::generate::is_dark; -use super::labels::{Role, filled_lines_on, label_para, label_size, label_style}; +use super::labels::{Line, Role, filled_lines_on, kept_line_rows, label_para, label_size, label_style, line_slot}; use super::{ Affine, Arc, CharStyle, Color, Document, GraphKind, GraphSpec, HashMap, Node, NodeId, NodeKind, Paint, Rect, Result, Session, Value, bad, refresh_bounds, @@ -154,13 +155,32 @@ pub(crate) fn paint_targets(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> { } /// `ids` with each graph series group replaced by the paths directly inside it, as [`paint_targets`] reads a series -/// group: the graph draws its series groups again with no rows of their own. A series group with no such path, other -/// ids and the art of a graph design pass through, and the order of `ids` is kept. +/// group: the graph draws its series groups again with no rows of their own. A graph's Axes group is replaced by the +/// lines and labels directly inside it, and its Legend group by the labels directly inside it, which the graph keeps +/// rows for ([`capture_label_rows`]). A group with no such member, other ids and the art of a graph design pass +/// through, and the order of `ids` is kept. pub(crate) fn series_group_marks(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> { series_group_marks_where(doc, ids, |_| true) } -/// [`series_group_marks`] for the series groups `stands` accepts; the others pass through. +/// The lines and labels directly in `n` when it is the Axes group of a graph, or the labels directly in it when it is +/// the graph's Legend group, in paint order. `None` for any other object. +pub(crate) fn graph_part_members(doc: &Document, n: &Node) -> Option<Vec<NodeId>> { + if !matches!(n.kind, NodeKind::Group { .. }) || n.extras().series_index.is_some() { + return None; + } + let axes = match n.name.as_deref() { + Some("Axes") => true, + Some("Legend") => false, + _ => return None, + }; + let spec = doc.parent_of(n.id).and_then(|parent| doc.node(parent)).and_then(|parent| parent.extras().graph.as_deref())?; + let member = |c: &Node| matches!(c.kind, NodeKind::Text(_)) || (axes && line_in(spec, n, c).is_some()); + Some(n.children().into_iter().flatten().filter(|c| member(c)).map(|c| c.id).collect()) +} + +/// [`series_group_marks`] for the series groups, Axes groups and Legend groups `stands` accepts; the others pass +/// through. pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: impl Fn(&Node) -> bool) -> Vec<NodeId> { let mut seen = std::collections::HashSet::new(); let mut out = Vec::new(); @@ -171,6 +191,10 @@ pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: i group.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. })).map(|m| m.id).collect(); if marks.is_empty() { out.push(*id) } else { out.extend(marks) } } + Some(part) if stands(part) => match graph_part_members(doc, part) { + Some(members) if !members.is_empty() => out.extend(members), + _ => out.push(*id), + }, _ => out.push(*id), } } @@ -767,6 +791,68 @@ fn set_legend_fills(n: &mut Node, on_dark: &HashMap<NodeId, bool>) { } } +/// Whether each wedge shows a dark fill, for each pie in `n` (`n` itself or one inside it, opacity-mask art included) +/// with Legends in Wedges whose legend labels' fill is not their own, so a redraw sets it by its wedge. Read before a +/// paste links the pie's colors to the document's swatches, for [`follow_wedge_shades`]. +pub(crate) fn wedge_shades(n: &Node) -> HashMap<NodeId, Vec<bool>> { + let mut out = HashMap::new(); + walk_with_masks(n, &mut |m| { + if let Some(g) = m.extras().graph.as_deref() + && g.kind == GraphKind::Pie + && g.legend + && g.pie_legend_in_wedges + && !g.label_styles.legend_fill_is_own() + { + out.insert(m.id, pie_wedges(m).iter().map(|w| w.dark).collect()); + } + }); + out +} + +/// Give the legend labels of each pie in `n` that [`wedge_shades`] read as `was` the contrast a redraw sets, where a +/// wedge now shows a fill of the other darkness: white on a dark wedge, black on a light one. Pies whose wedges all kept +/// their darkness keep their labels as they are. +pub(crate) fn follow_wedge_shades(n: &mut Node, was: &HashMap<NodeId, Vec<bool>>) { + let mut changed = vec![]; + walk_with_masks(n, &mut |m| { + if let Some(before) = was.get(&m.id) + && pie_wedges(m).iter().map(|w| w.dark).ne(before.iter().copied()) + { + changed.push(m.id); + } + }); + if !changed.is_empty() { + restore_contrast(n, &changed); + } +} + +/// Set the legend labels of the pies `ids` in `n` (`n` itself or ones inside it, opacity-mask art included) as a redraw +/// sets them on their wedges. +fn restore_contrast(n: &mut Node, ids: &[NodeId]) { + if ids.contains(&n.id) { + let on_dark = match n.extras().graph.as_deref() { + Some(g) => redrawn_on_dark(n, g).unwrap_or_else(|| legend_on_dark(n, g)), + None => HashMap::new(), + }; + set_legend_fills(n, &on_dark); + } + let holds = |c: &Node| { + let mut found = false; + walk_with_masks(c, &mut |m| found |= ids.contains(&m.id)); + found + }; + if n.extras().mask.as_ref().is_some_and(|m| holds(&m.art)) + && let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) + { + restore_contrast(Arc::make_mut(&mut m.art), ids); + } + for c in n.children_mut().into_iter().flatten() { + if holds(c) { + restore_contrast(Arc::make_mut(c), ids); + } + } +} + /// The legend labels of graph `n`: the type in its Legend group, as [`own_labels`] finds them. fn legend_labels(n: &Node) -> Vec<&Node> { legend_in(n.children().map_or(&[], |c| c.as_slice())) @@ -1122,21 +1208,34 @@ pub(crate) fn capture_label_anti_alias(doc: &mut Document, ids: &[NodeId], metho /// Keep a formatting change made to graph labels `ids` (Character or Appearance, on the whole graph or on labels /// picked with Group Selection) for every label of their kind: `change` is applied to the kind's kept style (or /// the default one), so the labels look the same when the graph is drawn again. Called inside the same edit, so -/// they undo together. Returns whether a kept style changed. +/// they undo together. A kind that keeps no style and that `change` leaves at the default style keeps none, unless +/// `change` sets the legend fill. Returns whether a kept style changed. pub(crate) fn capture_label_styles(doc: &mut Document, ids: &[NodeId], change: &dyn Fn(&mut CharStyle)) -> bool { let mut changed = false; for (graph, role) in label_kinds(doc, ids) { - changed |= store_label_style(doc, graph, role, change); + changed |= store_label_style(doc, graph, role, change, true); + } + changed +} + +/// [`capture_label_styles`], except that a kind that keeps no style keeps the default style when `change` leaves it +/// unchanged, for a command that gives character attributes (a size equal to the labels' own, for example). +pub(crate) fn capture_label_styles_given(doc: &mut Document, ids: &[NodeId], change: &dyn Fn(&mut CharStyle)) -> bool { + let mut changed = false; + for (graph, role) in label_kinds(doc, ids) { + changed |= store_label_style(doc, graph, role, change, false); } changed } /// Apply `change` to the style graph `graph` keeps for its labels of kind `role` (or the default one). A `change` that /// sets the fill of legend labels marks it as set on them, so a black one stays black on dark pie wedges. Returns whether -/// the kept style or that mark changed. -fn store_label_style(doc: &mut Document, graph: NodeId, role: Role, change: &dyn Fn(&mut CharStyle)) -> bool { +/// the kept style or that mark changed. With `unless_default`, a kind that keeps no style and that `change` leaves at +/// the default style keeps none, unless `change` sets the legend fill. +fn store_label_style(doc: &mut Document, graph: NodeId, role: Role, change: &dyn Fn(&mut CharStyle), unless_default: bool) -> bool { let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { return false }; - let mut style = label_style(&spec.label_styles, role); + let was = label_style(&spec.label_styles, role); + let mut style = was.clone(); // The kept fill can already be the one `change` sets (black, the default): `change` sets the fill when it gives one // of two different fills something else. let sets_fill = role == Role::Legend @@ -1152,6 +1251,9 @@ fn store_label_style(doc: &mut Document, graph: NodeId, role: Role, change: &dyn Role::Category => &mut styles.categories, Role::Legend => &mut styles.legend, }; + if unless_default && slot.is_none() && style == was && !(sets_fill && !styles.legend_fill_set) { + return false; + } let mut changed = slot.as_ref() != Some(&style); *slot = Some(style); if sets_fill && !styles.legend_fill_set { @@ -1214,37 +1316,382 @@ pub(crate) fn label_rows(n: &Node) -> Option<vectorcraft_doc::LabelRows> { (rows != vectorcraft_doc::LabelRows::default()).then_some(rows) } +/// The graph and kind of graph line `id`: a path directly in a graph's Axes group. Looked up through its parents, with no +/// pass over the document. +fn graph_line(doc: &Document, id: NodeId) -> Option<(NodeId, Line)> { + let line = doc.node(id)?; + if !matches!(line.kind, NodeKind::Path { .. }) { + return None; + } + let path = doc.ancestry(id)?; + let [.., graph, axes, _] = path.as_slice() else { return None }; + let spec = doc.node(*graph)?.extras().graph.as_deref()?; + Some((*graph, line_in(spec, doc.node(*axes)?, line)?)) +} + +/// The kind of graph line `line` is when `axes` is the Axes group of a graph drawn from `spec` and `line` a path directly +/// in it. A radar graph's rings are its closed paths; its spokes, open, are axis lines. +fn line_in(spec: &GraphSpec, axes: &Node, line: &Node) -> Option<Line> { + if axes.name.as_deref() != Some("Axes") || axes.extras().series_index.is_some() || !matches!(axes.kind, NodeKind::Group { .. }) { + return None; + } + let NodeKind::Path { path, .. } = &line.kind else { return None }; + Some(if spec.kind == GraphKind::Radar && path.is_closed() { Line::Ring } else { Line::Axis }) +} + +/// The graph lines among `ids`, each with its graph and kind, from the back to the front and each once: a later line's +/// capture replaces an earlier one's, so the frontmost line of a kind sets what the kind keeps. +fn lines_of(doc: &Document, ids: &[NodeId]) -> Vec<(NodeId, NodeId, Line)> { + let mut out: Vec<(NodeId, NodeId, Line)> = ids.iter().filter_map(|id| graph_line(doc, *id).map(|(g, line)| (*id, g, line))).collect(); + out.sort_by_cached_key(|(id, ..)| doc.index_path(*id)); + out.dedup_by_key(|(id, ..)| *id); + out +} + +/// Which of the object rows ([`label_rows`]) a graph label or line shows its kind keeps after an edit. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Keep { + /// All of them. + All, + /// Only the object opacity and blend mode; the fill and stroke rows stay as the kind keeps them. + Object, + /// The fill and stroke rows; the object opacity and blend mode stay as the kind keeps them. + Rows, + /// The fill row with `fill`, the stroke row with `stroke`, and the object opacity and blend mode with `object`; the + /// others stay as the kind keeps them. Each row keeps its place relative to the characters; a row taken from the + /// label or line paints above a kept row on the same side of them, unless the label or line shows it below its own row + /// of that kind. + Kinds { fill: bool, stroke: bool, object: bool }, +} + +/// The kinds (true: fill) of the rows in `rows` from the bottom up, each with whether it paints below the characters. +fn row_places(rows: &vectorcraft_doc::LabelRows) -> Vec<(bool, bool)> { + let order = if rows.stroke_under { [false, true] } else { [true, false] }; + let has = |fill: bool| if fill { rows.paint.fill.is_some() } else { rows.paint.stroke.is_some() }; + let below = usize::from(rows.below.unwrap_or(0)); + order.into_iter().filter(|k| has(*k)).enumerate().map(|(i, k)| (k, i < below)).collect() +} + +/// Where the rows paint when the row of kind `taken` (true: fill) comes from `shown` and the row of the other kind from +/// `kept`, each keeping its place relative to the characters: `below` and `stroke_under` of [`vectorcraft_doc::LabelRows`]. +fn merged_places(kept: &vectorcraft_doc::LabelRows, shown: &vectorcraft_doc::LabelRows, taken: bool) -> (Option<u8>, bool) { + let in_shown = row_places(shown); + let t = in_shown.iter().copied().find(|p| p.0 == taken); + let o = row_places(kept).into_iter().find(|p| p.0 != taken); + let order = match (t, o) { + (Some(t), Some(o)) => { + // Rows on different sides of the characters: the one below them is lower. On the same side: as the label or + // line shows them, else the taken row on top. + let at = |kind: bool| in_shown.iter().position(|p| p.0 == kind); + let o_first = if t.1 != o.1 { + o.1 + } else { + match (at(!taken), at(taken)) { + (Some(o_at), Some(t_at)) => o_at < t_at, + _ => true, + } + }; + if o_first { vec![o, t] } else { vec![t, o] } + } + (t, o) => t.into_iter().chain(o).collect(), + }; + let below = order.iter().filter(|p| p.1).fold(0u8, |k, _| k + 1); + ((below > 0).then_some(below), order.len() == 2 && !order[0].0) +} + +/// `shown` with the parts of the rows `kept` keeps that `keep` leaves as they are. +fn keep_rows(kept: vectorcraft_doc::LabelRows, shown: vectorcraft_doc::LabelRows, keep: Keep) -> vectorcraft_doc::LabelRows { + match keep { + Keep::All => shown, + Keep::Object => { + let mut kept = kept; + (kept.paint.opacity, kept.paint.blend) = (shown.paint.opacity, shown.paint.blend); + kept + } + Keep::Rows => { + let mut shown = shown; + (shown.paint.opacity, shown.paint.blend) = (kept.paint.opacity, kept.paint.blend); + shown + } + Keep::Kinds { fill, stroke, object } => { + let places = match (fill, stroke) { + (true, true) => (shown.below, shown.stroke_under), + (false, false) => (kept.below, kept.stroke_under), + (taken, _) => merged_places(&kept, &shown, taken), + }; + let mut rows = shown; + (rows.below, rows.stroke_under) = places; + let (r, k) = (&mut rows.paint, kept.paint); + if !object { + (r.opacity, r.blend) = (k.opacity, k.blend); + } + if !fill { + (r.fill, r.fill_opacity, r.fill_blend, r.fill_unit_box) = (k.fill, k.fill_opacity, k.fill_blend, k.fill_unit_box); + } + if !stroke { + (r.stroke, r.stroke_width, r.stroke_opacity, r.stroke_blend, r.stroke_unit_box) = + (k.stroke, k.stroke_width, k.stroke_opacity, k.stroke_blend, k.stroke_unit_box); + } + rows + } + } +} + +/// What lines of kind `line` keep (`slot`) after line `n` shows its rows ([`label_rows`]), of which `keep` says what is +/// taken from the line: `None` when that is how the graph draws them with no kept rows. +fn line_rows_after(slot: Option<&vectorcraft_doc::LabelRows>, line: Line, n: &Node, keep: Keep) -> Option<vectorcraft_doc::LabelRows> { + let shown = label_rows(n).unwrap_or_default(); + let rows = keep_rows(slot.cloned().unwrap_or_else(|| line.default_rows()), shown, keep); + (rows != line.default_rows()).then_some(rows) +} + +/// Keep the object rows ([`label_rows`]) of the graph lines among `ids` for every line of their kind (axis lines and tick +/// marks, or a radar graph's rings), the part of them `keep` says, even when a line already showed them. Returns whether +/// kept rows changed. +fn store_line_rows(doc: &mut Document, ids: &[NodeId], keep: Keep) -> bool { + let mut changed = false; + for (id, graph, line) in lines_of(doc, ids) { + let Some(spec) = doc.node(graph).and_then(|n| n.extras().graph.as_deref()) else { continue }; + let Some(n) = doc.node(id) else { continue }; + let kept = line_rows_after(kept_line_rows(&spec.label_styles, line), line, n, keep); + let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue }; + let slot = line_slot(&mut spec.label_styles, line); + changed |= *slot != kept; + *slot = kept; + } + changed +} + +/// Keep the object rows of graph lines `ids` for every line of their kind, as [`capture_label_rows`] keeps a label's, +/// for an edit that wrote their fill or stroke. Lines of a kind that the edit reached differently take the frontmost +/// one's rows. Called inside the same edit, so they undo together. Returns whether kept rows changed. +pub(crate) fn capture_line_rows(doc: &mut Document, ids: &[NodeId]) -> bool { + store_line_rows(doc, ids, Keep::All) +} + +/// [`capture_line_rows`] for an edit that wrote the fill and stroke rows of graph lines `ids` and left their object +/// opacity and blend mode alone: those stay as the kind keeps them, also when a line still shows other ones until the +/// graph is drawn again. +pub(crate) fn capture_line_fill_stroke_rows(doc: &mut Document, ids: &[NodeId]) -> bool { + store_line_rows(doc, ids, Keep::Rows) +} + +/// Keep, for every line of their kind, the attributes of the object rows ([`label_rows`]) that an edit changed on the +/// graph lines among `ids` (`before`: the document before the edit). The attributes the edit left alone stay as the kind +/// keeps them, also when a line still shows other ones until the graph is drawn again. Lines of a kind that the edit +/// changed differently take the frontmost one's attributes. Called inside the same edit, so they undo together. Returns +/// whether kept rows changed. +pub(crate) fn capture_line_changes(before: &Document, doc: &mut Document, ids: &[NodeId]) -> bool { + let mut changed = false; + for (id, graph, line) in lines_of(doc, ids) { + let old = before.node(id).and_then(label_rows).unwrap_or_default(); + let new = doc.node(id).and_then(label_rows).unwrap_or_default(); + if old == new { + continue; + } + let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue }; + let slot = line_slot(&mut spec.label_styles, line); + let mut rows = slot.clone().unwrap_or_else(|| line.default_rows()); + let was_unpainted = stroke_unpainted(&rows); + merge_row_edits(&mut rows, &old, &new); + if old.paint.stroke != new.paint.stroke { + keep_painted_stroke_weight(&mut rows, was_unpainted, &new.paint); + } + let kept = (rows != line.default_rows()).then_some(rows); + changed |= *slot != kept; + *slot = kept; + } + changed +} + +/// Keep, for every line of their kind, the paint an edit wrote to row `at` of graph line `id` for each `(id, at)` in +/// `written` when that row is the line's topmost visible fill or stroke, also when the line already showed that paint: +/// the paint replaces the one its kind keeps from another line. The other attributes stay as the kind keeps them. Lines +/// of a kind take the frontmost one's paint. Called inside the same edit, so they undo together. Returns whether kept +/// rows changed. +pub(crate) fn capture_line_paint_writes(doc: &mut Document, written: &[(NodeId, usize)]) -> bool { + let paint = RowWrites { paint: true, ..RowWrites::NONE }; + capture_line_row_writes(doc, written, paint, paint) +} + +/// Which attributes of a fill or stroke row an edit wrote, for [`capture_line_row_writes`]. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) struct RowWrites { + /// The paint. + pub paint: bool, + /// The weight (a stroke row only). + pub weight: bool, + /// The row's opacity. + pub opacity: bool, + /// The row's blend mode. + pub blend: bool, +} + +impl RowWrites { + /// No attribute. + pub const NONE: RowWrites = RowWrites { paint: false, weight: false, opacity: false, blend: false }; +} + +/// [`capture_line_paint_writes`] for the attributes `fill` says of a written fill row and `stroke` says of a written +/// stroke row: each is kept for every line of the kind as the line shows it, also when the line already showed it, in +/// place of what its kind keeps from another line. +pub(crate) fn capture_line_row_writes(doc: &mut Document, written: &[(NodeId, usize)], fill: RowWrites, stroke: RowWrites) -> bool { + let ids: Vec<NodeId> = written.iter().map(|(id, _)| *id).collect(); + let mut changed = false; + for (id, graph, line) in lines_of(doc, &ids) { + let Some(n) = doc.node(id) else { continue }; + let items = &n.appearance.items; + let wrote = |kind: bool| items.iter().rposition(|it| it.is_fill() == kind && it.visible()).is_some_and(|at| written.contains(&(id, at))); + let on_fill = if wrote(true) { fill } else { RowWrites::NONE }; + let on_stroke = if wrote(false) { stroke } else { RowWrites::NONE }; + if on_fill == RowWrites::NONE && on_stroke == RowWrites::NONE { + continue; + } + let shown = label_rows(n).unwrap_or_default().paint; + let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue }; + let slot = line_slot(&mut spec.label_styles, line); + let mut rows = slot.clone().unwrap_or_else(|| line.default_rows()); + let was_unpainted = stroke_unpainted(&rows); + let k = &mut rows.paint; + if on_fill.paint { + k.fill = shown.fill.clone(); + } + if on_fill.opacity { + k.fill_opacity = shown.fill_opacity; + } + if on_fill.blend { + k.fill_blend = shown.fill_blend; + } + if on_stroke.paint { + k.stroke = shown.stroke.clone(); + } + if on_stroke.weight { + k.stroke_width = shown.stroke_width; + } + if on_stroke.opacity { + k.stroke_opacity = shown.stroke_opacity; + } + if on_stroke.blend { + k.stroke_blend = shown.stroke_blend; + } + if on_stroke.paint { + keep_painted_stroke_weight(&mut rows, was_unpainted, &shown); + } + let kept = (rows != line.default_rows()).then_some(rows); + changed |= *slot != kept; + *slot = kept; + } + changed +} + +/// Give kept line rows whose stroke an edit painted the painted line's stroke weight (`shown`) when the kind kept no +/// stroke paint before the edit (`was_unpainted`) and keeps the zero weight a stroke set to None left. A non-zero kept +/// weight stays, and so do a zero weight kept with a painted stroke and a zero weight the painted line shows. +fn keep_painted_stroke_weight(rows: &mut vectorcraft_doc::LabelRows, was_unpainted: bool, shown: &vectorcraft_doc::SeriesPaint) { + if was_unpainted + && !stroke_unpainted(rows) + && rows.paint.stroke_width.is_some_and(|w| w <= 0.0) + && let Some(w) = shown.stroke_width.filter(|w| *w > 0.0) + { + rows.paint.stroke_width = Some(w); + } +} + +/// Do kept line rows keep no stroke paint? +fn stroke_unpainted(rows: &vectorcraft_doc::LabelRows) -> bool { + rows.paint.stroke.as_ref().is_none_or(Paint::is_none) +} + +/// Is `id` a graph line: a path directly in a graph's Axes group? +pub(crate) fn is_graph_line(doc: &Document, id: NodeId) -> bool { + graph_line(doc, id).is_some() +} + +/// Set each attribute of `rows` that differs between `old` and `new` as `new` has it. +fn merge_row_edits(rows: &mut vectorcraft_doc::LabelRows, old: &vectorcraft_doc::LabelRows, new: &vectorcraft_doc::LabelRows) { + fn take<T: PartialEq + Clone>(kept: &mut T, old: &T, new: &T) { + if old != new { + *kept = new.clone(); + } + } + let (k, o, n) = (&mut rows.paint, &old.paint, &new.paint); + take(&mut k.fill, &o.fill, &n.fill); + take(&mut k.stroke, &o.stroke, &n.stroke); + take(&mut k.stroke_width, &o.stroke_width, &n.stroke_width); + take(&mut k.fill_opacity, &o.fill_opacity, &n.fill_opacity); + take(&mut k.stroke_opacity, &o.stroke_opacity, &n.stroke_opacity); + take(&mut k.fill_blend, &o.fill_blend, &n.fill_blend); + take(&mut k.stroke_blend, &o.stroke_blend, &n.stroke_blend); + take(&mut k.opacity, &o.opacity, &n.opacity); + take(&mut k.blend, &o.blend, &n.blend); + take(&mut rows.below, &old.below, &new.below); + take(&mut rows.stroke_under, &old.stroke_under, &new.stroke_under); +} + +/// Would [`store_line_rows`] with [`Keep::Object`] change what a graph keeps for the lines among `ids`? Reads the +/// document without copying it. +fn line_object_opacity_differs(doc: &Document, ids: &[NodeId]) -> bool { + let mut kept: Vec<(NodeId, Line, Option<vectorcraft_doc::LabelRows>)> = vec![]; + for (id, graph, line) in lines_of(doc, ids) { + let (Some(spec), Some(n)) = (doc.node(graph).and_then(|n| n.extras().graph.as_deref()), doc.node(id)) else { continue }; + let slot = match kept.iter().position(|(g, l, _)| *g == graph && *l == line) { + Some(i) => kept.swap_remove(i).2, + None => kept_line_rows(&spec.label_styles, line).cloned(), + }; + kept.push((graph, line, line_rows_after(slot.as_ref(), line, n, Keep::Object))); + } + kept.into_iter().any(|(graph, line, rows)| { + doc.node(graph).and_then(|n| n.extras().graph.as_deref()).is_some_and(|spec| kept_line_rows(&spec.label_styles, line) != rows.as_ref()) + }) +} + /// Keep the object rows ([`label_rows`]) of graph labels `ids` for every label of their kind, as /// [`capture_label_styles`] keeps a character format, even when a label already showed them: the last label of a kind /// in the order of `ids` sets what that kind keeps. Objects other than type are left out before the graph's labels are -/// looked up. Called inside the same edit, so they undo together. Returns whether kept rows changed. +/// looked up. The graph lines among `ids` keep their rows for every line of their kind too ([`capture_line_rows`]). +/// Called inside the same edit, so they undo together. Returns whether kept rows changed. pub(crate) fn capture_label_rows(doc: &mut Document, ids: &[NodeId]) -> bool { - store_label_rows(doc, ids, false) + store_label_rows(doc, ids, Keep::All) } -/// Keep the object opacity and blend mode of graph labels `ids` for every label of their kind, as [`capture_label_rows`] -/// keeps them, and leave the kept fill and stroke rows as they are. Returns whether what the graph keeps changed. +/// Keep the object opacity and blend mode of graph labels and graph lines `ids` for every label or line of their kind, as +/// [`capture_label_rows`] keeps them, and leave the kept fill and stroke rows as they are. Returns whether what the graph +/// keeps changed. pub(crate) fn capture_label_object_opacity(doc: &mut Document, ids: &[NodeId]) -> bool { - store_label_rows(doc, ids, true) + store_label_rows(doc, ids, Keep::Object) +} + +/// Keep, for every label or line of their kind, the fill row (with `fill`) and the stroke row (with `stroke`) that graph +/// labels and graph lines `ids` show, and with `object` their object opacity and blend mode, as [`capture_label_rows`] +/// keeps them, for an edit that wrote only those: a row of the other kind stays as the kind keeps it, also when a label or +/// line still shows its own one until the graph is drawn again. Returns whether what the graph keeps changed. +pub(crate) fn capture_label_kind_rows(doc: &mut Document, ids: &[NodeId], (fill, stroke): (bool, bool), object: bool) -> bool { + store_label_rows(doc, ids, Keep::Kinds { fill, stroke, object }) +} + +/// [`capture_label_kind_rows`] for the graph lines among `ids` alone. +pub(crate) fn capture_line_kind_rows(doc: &mut Document, ids: &[NodeId], (fill, stroke): (bool, bool), object: bool) -> bool { + store_line_rows(doc, ids, Keep::Kinds { fill, stroke, object }) } /// Would [`capture_label_object_opacity`] change what a graph keeps for labels `ids`? Reads the document without copying /// it. pub(crate) fn label_object_opacity_differs(doc: &Document, ids: &[NodeId]) -> bool { - label_rows_of(doc, ids).into_iter().any(|(graph, role, rows)| { - let Some(spec) = doc.node(graph).and_then(|n| n.extras().graph.as_deref()) else { return false }; - let slot = match role { - Role::Value => &spec.label_styles.values_rows, - Role::Category => &spec.label_styles.categories_rows, - Role::Legend => &spec.label_styles.legend_rows, - }; - *slot != kept_label_rows(slot, rows, true) - }) + line_object_opacity_differs(doc, ids) + || label_rows_of(doc, ids).into_iter().any(|(graph, role, rows)| { + let Some(spec) = doc.node(graph).and_then(|n| n.extras().graph.as_deref()) else { return false }; + let slot = match role { + Role::Value => &spec.label_styles.values_rows, + Role::Category => &spec.label_styles.categories_rows, + Role::Legend => &spec.label_styles.legend_rows, + }; + *slot != kept_label_rows(slot, rows, Keep::Object) + }) } -/// [`capture_label_rows`], or with `object_only` [`capture_label_object_opacity`]. -fn store_label_rows(doc: &mut Document, ids: &[NodeId], object_only: bool) -> bool { - let mut changed = false; +/// [`capture_label_rows`], [`capture_label_object_opacity`] or [`capture_label_kind_rows`], as `keep` says. +fn store_label_rows(doc: &mut Document, ids: &[NodeId], keep: Keep) -> bool { + let mut changed = store_line_rows(doc, ids, keep); for (graph, role, rows) in label_rows_of(doc, ids) { let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue }; let slot = match role { @@ -1252,26 +1699,23 @@ fn store_label_rows(doc: &mut Document, ids: &[NodeId], object_only: bool) -> bo Role::Category => &mut spec.label_styles.categories_rows, Role::Legend => &mut spec.label_styles.legend_rows, }; - let kept = kept_label_rows(slot, rows, object_only); + let kept = kept_label_rows(slot, rows, keep); changed |= *slot != kept; *slot = kept; } changed } -/// What a kind keeps after a label of it shows `rows`: those rows, or with `object_only` what `slot` keeps with the -/// label's object opacity and blend mode. +/// What a kind keeps (`slot`) after a label of it shows `rows`, of which `keep` says what is taken from the label. fn kept_label_rows( slot: &Option<vectorcraft_doc::LabelRows>, rows: Option<vectorcraft_doc::LabelRows>, - object_only: bool, + keep: Keep, ) -> Option<vectorcraft_doc::LabelRows> { - if !object_only { + if keep == Keep::All { return rows; } - let mut kept = slot.clone().unwrap_or_default(); - let shown = rows.unwrap_or_default(); - (kept.paint.opacity, kept.paint.blend) = (shown.paint.opacity, shown.paint.blend); + let kept = keep_rows(slot.clone().unwrap_or_default(), rows.unwrap_or_default(), keep); (kept != vectorcraft_doc::LabelRows::default()).then_some(kept) } @@ -1391,23 +1835,38 @@ pub(super) fn picks_legend_fill(g: &GraphSpec) -> bool { g.picks_legend_fill() } -/// The graph labels among `roots` and inside them, for an edit that reaches graph labels without naming them. +/// The graph labels and graph lines among `roots` and inside them, for an edit that reaches them without naming them. pub(crate) fn labels_in(doc: &Document, roots: &[NodeId]) -> Vec<NodeId> { let mut texts = Vec::new(); + let mut lines = Vec::new(); for id in roots { + // A root that is a line, or the Axes group: found through its parents. + if graph_line(doc, *id).is_some() { + lines.push(*id); + } let Some(root) = doc.node(*id) else { continue }; + if let Some(parent) = doc.parent_of(*id).and_then(|p| doc.node(p)) + && let Some(spec) = parent.extras().graph.as_deref() + { + lines.extend(root.children().into_iter().flatten().filter(|c| line_in(spec, root, c).is_some()).map(|c| c.id)); + } root.walk(&mut |n| { if matches!(n.kind, NodeKind::Text(_)) { texts.push(n.id); } + if let Some(spec) = n.extras().graph.as_deref() { + for axes in n.children().into_iter().flatten() { + lines.extend(axes.children().into_iter().flatten().filter(|c| line_in(spec, axes, c).is_some()).map(|c| c.id)); + } + } }); } // Graph labels are type: without type among `roots`, the graph's labels are not looked up. - if texts.is_empty() { - return texts; + if !texts.is_empty() { + let labels = graph_labels(doc); + texts.retain(|id| labels.contains_key(id)); } - let labels = graph_labels(doc); - texts.retain(|id| labels.contains_key(id)); + texts.extend(lines.into_iter().filter(|id| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. })))); // Nested roots (a graph and one of its labels) reach a label twice. texts.sort_unstable(); texts.dedup(); @@ -1419,10 +1878,14 @@ pub(crate) fn labels_in(doc: &Document, roots: &[NodeId]) -> Vec<NodeId> { /// and stroke attributes ([`RUN_PAINT`]) that changed on all of a label's characters, on the kind's kept style. The /// frontmost label of a kind sets what that kind keeps, whatever order `ids` are in. On a graph that colors its legend /// labels itself ([`picks_legend_fill`]), their fill is kept only when the legend labels among `ids` end up with one -/// fill. Called inside the same edit, so they undo together. Returns whether what a graph keeps changed. -pub(crate) fn capture_label_changes(before: &Document, doc: &mut Document, ids: &[NodeId], rows: bool) -> bool { +/// fill and the edit named them: with `named`, only a legend label among `named` (an edit that reached the others +/// through the graph or a group leaves them the graph's black or white); without it, every label in `ids`. The graph +/// lines among `ids` whose rows changed keep what changed for every line of their kind ([`capture_line_changes`]), with or without +/// `rows`. Called inside the same edit, so they undo together. Returns whether what a graph keeps changed. +pub(crate) fn capture_label_changes(before: &Document, doc: &mut Document, ids: &[NodeId], rows: bool, named: Option<&[NodeId]>) -> bool { + let lines = capture_line_changes(before, doc, ids); if !ids.iter().any(|id| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)))) { - return false; + return lines; } let labels = graph_labels(doc); let mut picked: Vec<NodeId> = ids.iter().copied().filter(|id| labels.contains_key(id)).collect(); @@ -1447,18 +1910,25 @@ pub(crate) fn capture_label_changes(before: &Document, doc: &mut Document, ids: if rows && label_rows(was) != label_rows(now) { changed_rows.push(id); } - let fill = kind.1 != Role::Legend || one_fill(kind.0); + let aimed = !wedge_fills.contains_key(&kind.0) || named.is_none_or(|n| n.contains(&id)); + let fill = kind.1 != Role::Legend || (one_fill(kind.0) && aimed); characters.extend(run_paint_change(was, now, fill).map(|change| (kind, change))); } - let mut changed = capture_label_rows(doc, &changed_rows); + let mut changed = capture_label_rows(doc, &changed_rows) | lines; for ((graph, role), (style, entries)) in &characters { - changed |= store_label_style(doc, *graph, *role, &|st| { - for i in entries { - if let Some(copy) = RUN_PAINT.get(*i) { - copy(style, st); + changed |= store_label_style( + doc, + *graph, + *role, + &|st| { + for i in entries { + if let Some(copy) = RUN_PAINT.get(*i) { + copy(style, st); + } } - } - }); + }, + true, + ); } changed } diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index ca1f1d2c45..b74dd97454 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -454,7 +454,7 @@ fn an_edit_of_a_graph_designs_art_is_lost_when_the_graph_is_drawn_again() { /// it, and edit the other objects they are given. #[test] fn paint_commands_leave_a_graph_designs_art_out() { - let (mut s, _, copy, art, mark) = design_art(); + let (mut s, graph, copy, art, mark) = design_art(); let fill = top_row(&s, art, true); let commands = [ ("stroke.set", json!({"weight": 5})), @@ -466,6 +466,7 @@ fn paint_commands_leave_a_graph_designs_art_out() { ("paint.swap", json!({})), ("paint.default", json!({})), ("paint.invert", json!({"item": fill, "stroke": false})), + ("paint.invert", json!({})), ]; let (copy_was, art_was) = (look(&s, copy), look(&s, art)); for (cmd, p) in &commands { @@ -489,6 +490,11 @@ fn paint_commands_leave_a_graph_designs_art_out() { s.execute("select.set", &json!({"ids": [art.0]})).unwrap(); s.execute("stroke.set", &json!({"weight": 5})).unwrap(); assert_eq!(look(&s, art), art_was); + // Given the whole graph, Invert recolors the marks and leaves the art. + let mark_was = look(&s, mark); + s.execute("paint.invert", &json!({"ids": [graph.0]})).unwrap(); + assert_eq!(look(&s, art), art_was); + assert_ne!(look(&s, mark), mark_was); // A freeform gradient point is refused on the art alone. refused_on_design_art(&mut s, "paint.freeform.addPoint", json!({"ids": [art.0], "at": [0, 0]})); } @@ -517,6 +523,182 @@ fn stroke_edits_of_selected_design_art_leave_the_new_art_stroke() { assert_eq!(s.new_art_stroke().gradient_mode, mode, "paint.editGradient"); } +/// With only the art of a graph design given or selected, the gradient, swap, default and recolor commands leave the +/// paint for new art and the remembered colors as they are. +#[test] +fn paint_edits_of_design_art_alone_leave_the_defaults() { + let (mut s, _, _, art, _) = design_art(); + let fill = top_row(&s, art, true); + s.execute("select.set", &json!({"ids": []})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 3})).unwrap(); + let defaults = |s: &Session| format!("{:?}", (&s.paint, s.last_solid, &s.last_gradient, &s.recent_colors)); + let commands = [ + ("paint.editGradient", json!({"kind": "linear"})), + ("paint.editGradient", json!({"kind": "radial", "stroke": true})), + ("paint.swap", json!({})), + ("paint.default", json!({})), + ("paint.invert", json!({"item": fill, "stroke": false})), + ("paint.complement", json!({"item": fill, "stroke": false})), + ("paint.invert", json!({})), + ("paint.complement", json!({"stroke": true})), + ("stroke.set", json!({"weight": 7})), + ("stroke.weightUp", json!({})), + ]; + for (cmd, p) in &commands { + let was = defaults(&s); + let mut q = p.clone(); + q["ids"] = json!([art.0]); + s.execute(cmd, &q).unwrap(); + assert_eq!(defaults(&s), was, "{cmd}, given"); + // Selecting the art makes the defaults take its paint. + s.execute("select.set", &json!({"ids": [art.0]})).unwrap(); + let was = defaults(&s); + s.execute(cmd, p).unwrap(); + assert_eq!(defaults(&s), was, "{cmd}, selected"); + s.execute("select.set", &json!({"ids": []})).unwrap(); + } + // A bad `item`, `aligned` or `target` is still an error with only design art given. + for bad in [ + json!({"ids": [art.0], "item": "top"}), + json!({"ids": [art.0], "item": fill, "aligned": "yes"}), + json!({"ids": [art.0], "item": fill, "target": "nowhere"}), + json!({"ids": [art.0], "target": "nowhere"}), + ] { + assert!(s.execute("paint.invert", &bad).is_err(), "{bad}"); + assert!(s.execute("paint.complement", &bad).is_err(), "{bad}"); + } + // So is an `item` the art has no row for, in each command that leaves the art out. + let steps = s.doc().unwrap().history.undo.len(); + for (cmd, p) in [ + ("paint.invert", json!({})), + ("stroke.set", json!({"weight": 2})), + ("stroke.weightUp", json!({})), + ("stroke.setAdvanced", json!({"swapArrows": true})), + ("paint.editGradient", json!({"kind": "linear"})), + ("paint.setGradientGeom", json!({"start": [0, 0], "end": [50, 50]})), + ("object.setOverprint", json!({"fill": true})), + ] { + let mut q = p.clone(); + q["ids"] = json!([art.0]); + q["item"] = json!(99); + assert!(s.execute(cmd, &q).is_err(), "{cmd}"); + } + // The art's stroke row named without `stroke` is a stroke row: the gradient commands succeed and change nothing. + let stroke_row = top_row(&s, art, false); + for p in [json!({"kind": "linear"}), json!({"start": [0, 0], "end": [50, 50]})] { + let cmd = if p.get("kind").is_some() { "paint.editGradient" } else { "paint.setGradientGeom" }; + let mut q = p.clone(); + q["ids"] = json!([art.0]); + q["item"] = json!(stroke_row); + s.execute(cmd, &q).unwrap(); + } + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + // With nothing selected, the swap still swaps the defaults. + let was = defaults(&s); + s.execute("paint.swap", &json!({})).unwrap(); + assert_ne!(defaults(&s), was); +} + +/// A spread or a negative aspect for the art of a graph design alone changes nothing, whatever kind of gradient the +/// default fill is; a bad value is still an error. +#[test] +fn gradient_edits_of_design_art_alone_skip_the_default_kind_checks() { + let (mut s, _, _, art, _) = design_art(); + for (default, p) in [("freeform", json!({"spread": "repeat"})), ("linear", json!({"aspect": -50}))] { + s.execute("select.set", &json!({"ids": []})).unwrap(); + s.execute("paint.editGradient", &json!({"kind": default})).unwrap(); + let (was, art_was, steps) = (format!("{:?}", s.paint), look(&s, art), s.doc().unwrap().history.undo.len()); + let mut q = p.clone(); + q["ids"] = json!([art.0]); + s.execute("paint.editGradient", &q).unwrap_or_else(|e| panic!("{q}: {e}")); + assert_eq!(format!("{:?}", s.paint), was, "{default}"); + assert_eq!(look(&s, art), art_was, "{default}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{default}"); + } + assert!(s.execute("paint.editGradient", &json!({"ids": [art.0], "spread": "sideways"})).is_err()); +} + +/// Invert given a group around a graph recolors the group's own fill and the series marks, and leaves the art of a +/// graph design as it is. With `target: "contents"` the group's own fill stays as it is. +#[test] +fn invert_of_a_group_recolors_its_own_fill_and_leaves_design_art() { + let (mut s, graph, _, art, mark) = design_art(); + s.execute("select.set", &json!({"ids": [graph.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("appearance.addFill", &json!({"ids": [group.0]})).unwrap(); + let row = top_row(&s, group, true); + s.execute("paint.setFill", &json!({"ids": [group.0], "item": row, "color": "#ff0000"})).unwrap(); + let own = |s: &Session| format!("{:?}", s.doc().unwrap().doc.node(group).unwrap().appearance.items); + let (own_was, art_was, mark_was) = (own(&s), look(&s, art), look(&s, mark)); + s.execute("paint.invert", &json!({"ids": [group.0]})).unwrap(); + assert_ne!(own(&s), own_was, "the group's own fill"); + assert_ne!(look(&s, mark), mark_was); + assert_eq!(look(&s, art), art_was); + // The color remembered is the group's own new fill, which the Fill proxy shows. + let Some(Paint::Solid { color, .. }) = s.doc().unwrap().doc.node(group).unwrap().proxy_paint_only(false, None).cloned() else { + panic!("the group's fill is not a solid color") + }; + assert_eq!((s.last_solid, s.recent_colors.first().copied()), (color, Some(color))); + let (own_was, mark_was) = (own(&s), look(&s, mark)); + s.execute("paint.invert", &json!({"ids": [group.0], "target": "contents"})).unwrap(); + assert_eq!(own(&s), own_was, "target: contents"); + assert_ne!(look(&s, mark), mark_was); + assert_eq!(look(&s, art), art_was); +} + +/// Invert and Complement given a series group that holds only a graph design's art recolor the group's own fill and +/// remember that color, as the last color and the newest recent color. With several such groups the color remembered +/// is that of the first group whose fill changed. +#[test] +fn recoloring_a_group_of_design_art_alone_remembers_its_own_fill() { + // A fill of its own for `group`, painted `hex` (the color of a rectangle painted with it). + let paint_own = |s: &mut Session, group: NodeId, hex: &str| { + s.execute("appearance.addFill", &json!({"ids": [group.0]})).unwrap(); + let t = NodeId(s.execute("shape.rectangle", &json!({"x": 700, "y": 700, "width": 5, "height": 5})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [t.0], "color": hex})).unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let paint = d.node(t).unwrap().proxy_paint_only(false, None).unwrap().clone(); + d.node_mut(group).unwrap().appearance.fill_at_mut(None).unwrap().paint = paint; + }; + // Series 0's group with its own fill painted `hex`. + let painted_series = |hex: &str| { + let (mut s, graph, _, art, _) = design_art(); + let group = series(s.doc().unwrap().doc.node(graph).unwrap(), 0).id; + paint_own(&mut s, group, hex); + (s, group, art) + }; + for cmd in ["paint.invert", "paint.complement"] { + let (mut s, group, art) = painted_series("#ff0000"); + let fill = |s: &Session| s.doc().unwrap().doc.node(group).unwrap().proxy_paint_only(false, None).unwrap().clone(); + let (art_was, fill_was) = (look(&s, art), fill(&s)); + s.execute(cmd, &json!({"ids": [group.0]})).unwrap(); + assert_eq!(look(&s, art), art_was, "{cmd}"); + assert_ne!(fill(&s), fill_was, "{cmd}: the group's fill is recolored"); + let Paint::Solid { color, .. } = fill(&s) else { panic!("{cmd}: the group's fill is not a solid color") }; + assert_eq!((s.last_solid, s.recent_colors.first().copied()), (color, Some(color)), "{cmd}"); + } + // A gray fill is its own complement: nothing changes, and the remembered colors stay as they were. + let (mut s, group, _) = painted_series("#808080"); + s.execute("select.set", &json!({"ids": []})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + let remembered = |s: &Session| format!("{:?}", (s.last_solid, &s.recent_colors)); + let was = remembered(&s); + assert_eq!(s.execute("paint.complement", &json!({"ids": [group.0]})).unwrap()["changed"], json!(0)); + assert_eq!(remembered(&s), was); + // Both series groups hold only the design's art: a gray one first and a red one, given together. + let (mut s, graph, _, _, _) = design_art(); + s.execute("graph.column", &json!({"id": graph.0, "seriesIndexes": [1], "design": "Square"})).unwrap(); + let groups = [0, 1].map(|i| series(s.doc().unwrap().doc.node(graph).unwrap(), i).id); + paint_own(&mut s, groups[0], "#808080"); + paint_own(&mut s, groups[1], "#ff0000"); + s.execute("paint.complement", &json!({"ids": [groups[0].0, groups[1].0]})).unwrap(); + let Some(Paint::Solid { color, .. }) = s.doc().unwrap().doc.node(groups[1]).unwrap().proxy_paint_only(false, None).cloned() else { + panic!("the red group's fill is not a solid color") + }; + assert_eq!((s.last_solid, s.recent_colors.first().copied()), (color, Some(color))); +} + /// `transparency.set` without `item` refuses the art of a graph design in a series, and given it with other objects /// sets only theirs. #[test] @@ -596,6 +778,81 @@ fn expand_appearance_leaves_a_graph_designs_art() { assert!(s.doc().unwrap().doc.node(NodeId(other)).is_none_or(|m| m.appearance.effects.is_empty())); } +/// `effect` with `params`, as `effect.apply` gives it to an object. +fn an_effect(s: &mut Session, effect: &str, params: serde_json::Value) -> vectorcraft_doc::Effect { + let r = s.execute("shape.rectangle", &json!({"x": 700, "y": 20, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("effect.apply", &json!({"effect": effect, "ids": [r], "params": params})).unwrap(); + s.doc().unwrap().doc.node(NodeId(r)).unwrap().appearance.effects[0].clone() +} + +/// Expand Appearance of a graph neither lists the art of a design in a series whose own effect it leaves, nor adds an +/// image of that effect to the document. +#[test] +fn expand_appearance_lists_no_design_art_and_rasterizes_none() { + let (mut s, id, copy, _, mark) = design_art(); + let shadow = an_effect(&mut s, "stylize.dropShadow", json!({})); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(copy).unwrap().appearance.effects.push(shadow); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [mark.0]})).unwrap(); + let copy_was = look(&s, copy); + let images = |s: &Session| s.doc().unwrap().doc.images.len(); + let before = images(&s); + s.execute("select.set", &json!({"ids": [mark.0]})).unwrap(); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + let per_mark = images(&s) - before; + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let expanded = s.execute("effect.expandAppearance", &json!({})).unwrap(); + assert_eq!(expanded["ids"], json!([mark.0])); + assert_eq!(look(&s, copy), copy_was); + assert_eq!(images(&s) - before, per_mark, "only the mark's shadow becomes an image"); +} + +/// A geometry effect of a series group that Expand Appearance bakes moves the art of a design in that series with the +/// marks. +#[test] +fn expand_appearance_moves_design_art_with_its_series_groups_effect() { + let (mut s, id, copy, _, _) = design_art(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let group = series(&n, 0).id; + let shift = an_effect(&mut s, "distort.transform", json!({"moveH": 50})); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(group).unwrap().appearance.effects.push(shift); + let left = |s: &Session| { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + series(&n, 0).children().unwrap()[0].geometric_bounds().unwrap().x0 + }; + let was = left(&s); + assert_eq!(series(&n, 0).children().unwrap()[0].id, copy); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + assert!((left(&s) - was - 50.0).abs() < 1e-6, "{} then {}", was, left(&s)); +} + +/// The copies that a Transform effect of a series group makes of a design's art keep their own effects when Expand +/// Appearance bakes the series group's effect, as the art they copy does. +#[test] +fn expand_appearance_leaves_the_effects_of_design_art_copies() { + let (mut s, id, copy, _, _) = design_art(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let group = series(&n, 0).id; + let shadow = an_effect(&mut s, "stylize.dropShadow", json!({})); + let copies = an_effect(&mut s, "distort.transform", json!({"moveH": 50, "copies": 2})); + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + doc.node_mut(copy).unwrap().appearance.effects.push(shadow); + doc.node_mut(group).unwrap().appearance.effects.push(copies); + let shadows = |s: &Session| { + let mut count = 0; + s.doc().unwrap().doc.node(id).unwrap().walk(&mut |m| count += m.appearance.effects.iter().filter(|e| e.id == "stylize.dropShadow").count()); + count + }; + let images = |s: &Session| s.doc().unwrap().doc.images.len(); + let before = images(&s); + assert_eq!(shadows(&s), 1); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + assert_eq!(shadows(&s), 3, "the art and its two copies keep their shadows"); + assert_eq!(images(&s), before, "no shadow becomes an image"); +} + /// The commands that give rows, effects or graphic styles refuse the art of a graph design inside a series, given by /// id (the design's copy or a path inside it) or selected: the graph draws that art again from the design. #[test] @@ -1109,6 +1366,42 @@ fn aligned_effect_indices_past_the_end_of_a_graph_designs_art_are_refused() { assert!(rows(&s, mark).effects.is_empty()); } +/// With a graph design's art given first and `aligned: true`, `effect.remove` and `effect.duplicate` with `indices` are an +/// error and change nothing when one of the art's effects is one no other object has, as with that index given alone. +#[test] +fn aligned_effect_indices_of_a_graph_designs_art_that_no_object_has_are_refused() { + let rows = |s: &Session, id: NodeId| (*s.doc().unwrap().doc.node(id).unwrap().appearance).clone(); + let (mut s, _, art, mark) = aligned_design_art(); + // The art has a shadow and a roughen, the mark the shadow only. + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [mark.0], "item": null})).unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.roughen", "ids": [mark.0], "item": null})).unwrap(); + s.edit("Effects", |d, _| { + let effects = d.node(mark).unwrap().appearance.effects.clone(); + d.node_mut(art).unwrap().appearance.effects = effects; + d.node_mut(mark).unwrap().appearance.effects.pop(); + Ok(()) + }) + .unwrap(); + let (art_was, mark_was) = (rows(&s, art), rows(&s, mark)); + let steps = s.doc().unwrap().history.undo.len(); + for cmd in ["effect.remove", "effect.duplicate"] { + assert!(s.execute(cmd, &json!({"ids": [art.0, mark.0], "item": null, "index": 1, "aligned": true})).is_err(), "{cmd}"); + let e = s.execute(cmd, &json!({"ids": [art.0, mark.0], "item": null, "indices": [0, 1], "aligned": true})).unwrap_err(); + assert!(e.to_string().contains("no effects at indices 0, 1"), "{cmd}: {e}"); + assert_eq!((rows(&s, art), rows(&s, mark)), (art_was.clone(), mark_was.clone()), "{cmd}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{cmd}"); + } + // With the roughen on the mark too, both of its effects are removed. + s.edit("Roughen", |d, _| { + let roughen = d.node(art).unwrap().appearance.effects[1].clone(); + d.node_mut(mark).unwrap().appearance.effects.push(roughen); + Ok(()) + }) + .unwrap(); + s.execute("effect.remove", &json!({"ids": [art.0, mark.0], "item": null, "indices": [0, 1], "aligned": true})).unwrap(); + assert!(rows(&s, mark).effects.is_empty()); +} + /// A blur on a series group makes the whole group an image, which draws the design's art with the series' other art: /// Expand Appearance does not put the art back beside the image. #[test] @@ -6407,6 +6700,54 @@ fn filled_lines_keep_the_line_colour_and_fall_back_to_thin_lines() { assert!(series_parts(&s, big, 0)[0].appearance.fill_paint().is_none()); } +/// Line Width sets how wide Draw Filled Lines draws the bands and is kept through save and open. A width outside 0.01 +/// to 1000 pt is refused, the same width again records no undo step, and the default 3 pt is stored as no width. +#[test] +fn filled_lines_take_a_line_width() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = make(&mut s, "line", ",a\nQ1,2\nQ2,2\nQ3,2"); + s.execute("graph.setType", &json!({"id": id.0, "filledLines": true})).unwrap(); + let height = |s: &Session| series_parts(s, id, 0)[0].geometric_bounds().unwrap().height(); + assert!((height(&s) - 3.0).abs() < 1e-6, "3 pt by default: {}", height(&s)); + assert_eq!(s.execute("graph.setType", &json!({"id": id.0})).unwrap()["lineWidth"], json!(3.0)); + s.execute("graph.setType", &json!({"id": id.0, "lineWidth": 8})).unwrap(); + assert!((height(&s) - 8.0).abs() < 1e-6, "{}", height(&s)); + assert_eq!(s.execute("graph.setType", &json!({"id": id.0})).unwrap()["lineWidth"], json!(8.0)); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let before = steps(&s); + for p in [json!({"id": id.0, "lineWidth": 8}), json!({"id": id.0, "lineWidth": 8.0, "filledLines": true}), json!({"id": id.0, "lineWidth": null})] + { + s.execute("graph.setType", &p).unwrap(); + assert_eq!(steps(&s), before, "nothing changed: {p}"); + } + for w in [json!(0), json!(-2), json!(0.005), json!(1000.5)] { + let e = s.execute("graph.setType", &json!({"id": id.0, "lineWidth": w})).unwrap_err().to_string(); + assert!(e.contains(&format!("`lineWidth` must be from 0.01 to 1000 pt, not {}", w.as_f64().unwrap())), "{e}"); + assert_eq!((steps(&s), spec(&s, id).line_width), (before, Some(8.0)), "{w}"); + } + s.execute("graph.setType", &json!({"id": id.0, "lineWidth": 0.01})).unwrap(); + assert_eq!(spec(&s, id).line_width, Some(0.01)); + s.execute("graph.setType", &json!({"id": id.0, "lineWidth": 1000})).unwrap(); + assert_eq!(spec(&s, id).line_width, Some(1000.0)); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(spec(&s, id).line_width, Some(8.0)); + // Kept through save and open. + let dir = vectorcraft_testkit::TempDir::new("graph-line-width"); + let path = dir.join("width.vectorcraft"); + s.execute("document.save", &json!({"path": path})).unwrap(); + s.execute("document.open", &json!({"path": path})).unwrap(); + assert_eq!(spec(&s, id).line_width, Some(8.0)); + assert!((height(&s) - 8.0).abs() < 1e-6, "{}", height(&s)); + // The default width is stored as no width, so the file keeps no `lineWidth`. + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.setType", &json!({"id": id.0, "lineWidth": 3})).unwrap(); + assert_eq!(spec(&s, id).line_width, None); + assert!(serde_json::to_value(spec(&s, id)).unwrap().get("lineWidth").is_none()); + assert!((height(&s) - 3.0).abs() < 1e-6, "{}", height(&s)); +} + #[test] fn overlapping_columns_keep_clear_of_the_legend_and_options_follow_the_graph_type() { let mut s = Session::new(); @@ -7469,6 +7810,1008 @@ fn a_recolor_leaves_wedge_legend_labels_their_contrast() { assert_eq!(kept.and_then(|f| f.color()).map(|c| c.to_hex()).as_deref(), Some("#ffffff")); } +/// A recolor of the whole graph that turns every wedge legend label the same color (one series) still leaves them to +/// the graph's black or white, so a label stays readable when its wedge is painted light again. +#[test] +fn a_recolor_of_a_one_series_pie_leaves_its_wedge_label_its_contrast() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = make(&mut s, "pie", ",a\nP1,1"); + s.execute("graph.setType", &json!({"id": id.0, "pieLegend": "wedges"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [series_0_group(&s, id).0.0], "color": "#ffffff"})).unwrap(); + // The white wedge turns black and its black label white. + s.execute("edit.colors.invert", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(spec(&s, id).label_styles.legend, None); + s.execute("paint.setFill", &json!({"ids": [series_0_group(&s, id).0.0], "color": "#ffffff"})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "rows": [[1]]})).unwrap(); + let NodeKind::Text(t) = label_node(&s, id, "Legend", "a").kind else { panic!("a is not type") }; + assert_eq!(t.runs[0].style.fill.color().map(|c| c.to_hex()).as_deref(), Some("#000000")); +} + +/// The lines in graph `id`'s Axes group (axis lines, tick marks and a radar graph's rings), in paint order. +fn line_nodes(s: &Session, id: NodeId) -> Vec<vectorcraft_doc::Node> { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + group(&n, "Axes").children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Text(_))).map(|c| (**c).clone()).collect() +} + +/// How line `n` looks: its stroke color (empty without one), stroke weight and object opacity. +fn line_look(n: &vectorcraft_doc::Node) -> (String, f64, f32) { + let stroke = n.appearance.stroke_paint().color().map(|c| c.to_hex()).unwrap_or_default(); + (stroke, n.appearance.stroke_width(), n.opacity) +} + +/// The looks of graph `id`'s lines after it is drawn again. +fn redrawn_line_looks(s: &mut Session, id: NodeId) -> Vec<(String, f64, f32)> { + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + line_nodes(s, id).iter().map(line_look).collect() +} + +/// A stroke, a weight, no stroke or an opacity given to one axis line is kept for every axis line and tick mark when the +/// graph is drawn again, and undo takes it back with its edit. +#[test] +fn paint_set_on_one_axis_line_is_kept_for_every_line() { + let cases = [ + ("paint.setStroke", json!({"color": "#ff0000"}), ("#ff0000", 0.5, 1.0)), + ("stroke.set", json!({"weight": 2}), ("#000000", 2.0, 1.0)), + ("paint.setStroke", json!({"none": true}), ("", 0.0, 1.0)), + ("appearance.clear", json!({}), ("", 0.0, 1.0)), + ("transparency.set", json!({"opacity": 40}), ("#000000", 0.5, 0.4)), + ]; + every_case(cases, |(cmd, params, (hex, width, opacity))| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + assert!(lines.len() > 2, "{lines:?}"); + let mut p = params.clone(); + p["ids"] = json!([lines[0].id.0]); + s.execute(cmd, &p).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + let want = (hex.to_string(), *width, *opacity); + assert!(looks.iter().all(|l| (&l.0, (l.1 - want.1).abs() < 1e-9, (l.2 - want.2).abs() < 1e-6) == (&want.0, true, true)), "{cmd}: {looks:?}"); + // Undo takes back the redraw, then the edit and what the graph keeps. + for _ in 0..2 { + s.execute("edit.undo", &json!({})).unwrap(); + } + assert_eq!(spec(&s, id).label_styles.axis_rows, None, "{cmd}"); + }); +} + +/// A recolor of the whole graph, or Swap Fill and Stroke on its axis lines, is kept for its axis lines, and the labels' +/// paint stays its own. +#[test] +fn recoloring_a_graph_keeps_its_axis_lines_paint() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + s.execute("edit.colors.invert", &json!({"ids": [id.0]})).unwrap(); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0 == "#ffffff"), "inverted black lines are white"); + let ids: Vec<u64> = line_nodes(&s, id).iter().map(|n| n.id.0).collect(); + s.execute("paint.swap", &json!({"ids": ids})).unwrap(); + let kept = spec(&s, id).label_styles.axis_rows.unwrap(); + assert_eq!((kept.paint.fill.and_then(|p| p.color()).map(|c| c.to_hex()), kept.paint.stroke), (Some("#ffffff".into()), Some(Paint::None))); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0.is_empty()), "the lines have no stroke after the swap"); + // The value labels keep their inverted fill, not the lines' swapped paint. + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let label_paint: Vec<(String, bool)> = group(&n, "Axes") + .children() + .unwrap() + .iter() + .filter_map(|c| match &c.kind { + NodeKind::Text(t) => Some((t.runs[0].style.fill.color().map(|c| c.to_hex()).unwrap_or_default(), t.runs[0].style.stroke.is_none())), + _ => None, + }) + .collect(); + assert!(!label_paint.is_empty() && label_paint.iter().all(|l| *l == ("#ffffff".to_string(), true)), "{label_paint:?}"); +} + +/// Swap Fill and Stroke on an axis line keeps the swapped paint for every axis line and leaves the fill opacity the axis +/// lines keep from another line, though the line swapped still shows 100%. +#[test] +fn swapping_an_axis_lines_paint_keeps_the_fill_opacity_its_kind_keeps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + let (first, second) = (lines[0].id, lines[1].id); + s.execute("paint.setFill", &json!({"ids": [first.0], "color": "#00ff00"})).unwrap(); + s.execute("transparency.set", &json!({"ids": [first.0], "item": top_row(&s, first, true), "opacity": 40})).unwrap(); + let shown = s.doc().unwrap().doc.node(second).unwrap().appearance.fill().map(|f| f.opacity); + assert!(shown.is_none_or(|o| o == 1.0), "the other lines show 100% until the graph is drawn again: {shown:?}"); + s.execute("paint.swap", &json!({"ids": [second.0]})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + for n in line_nodes(&s, id) { + let fill = n.appearance.fill().map(|f| (f.paint.color().map(|c| c.to_hex()), f.opacity)); + assert!(fill.as_ref().is_some_and(|(c, o)| c.as_deref() == Some("#000000") && (*o - 0.4).abs() < 1e-6), "{fill:?}"); + assert!(n.appearance.stroke_paint().is_none(), "the swapped line had no fill, so the lines have no stroke"); + } +} + +/// A stroke given the whole graph, or its Axes group, is kept for its axis lines. +#[test] +fn a_stroke_given_the_whole_graph_or_its_axes_group_is_kept_for_its_axis_lines() { + for axes in [false, true] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let target = if axes { group(s.doc().unwrap().doc.node(id).unwrap(), "Axes").id } else { id }; + s.execute("paint.setStroke", &json!({"ids": [target.0], "color": "#ff0000"})).unwrap(); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0 == "#ff0000"), "axes: {axes}"); + } +} + +/// A radar graph's rings keep what is set on one of them, apart from its spokes. +#[test] +fn a_radar_graphs_rings_keep_their_paint_apart_from_its_spokes() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "radar"); + let lines = line_nodes(&s, id); + // Three categories: three spokes, then the rings. + assert_eq!(line_look(&lines[3]), ("#999999".into(), 0.25, 1.0)); + s.execute("paint.setStroke", &json!({"ids": [lines[3].id.0], "color": "#00ff00"})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks[..3].iter().all(|l| l.0 == "#000000" && l.1 == 0.5), "{looks:?}"); + assert!(looks[3..].iter().all(|l| l.0 == "#00ff00" && l.1 == 0.25), "{looks:?}"); + s.execute("paint.setStroke", &json!({"ids": [line_nodes(&s, id)[0].id.0], "color": "#0000ff"})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks[..3].iter().all(|l| l.0 == "#0000ff") && looks[3..].iter().all(|l| l.0 == "#00ff00"), "{looks:?}"); +} + +/// When an edit gives axis lines different paint, the frontmost one sets what they keep, whatever order `ids` are in. +#[test] +fn the_frontmost_axis_line_sets_what_its_recolor_keeps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + let (back, front) = (lines[0].id, lines[lines.len() - 1].id); + s.execute("paint.setStroke", &json!({"ids": [front.0], "color": "#ff0000"})).unwrap(); + s.execute("edit.colors.invert", &json!({"ids": [front.0, back.0]})).unwrap(); + let kept = spec(&s, id).label_styles.axis_rows.unwrap().paint.stroke.and_then(|p| p.color()).map(|c| c.to_hex()); + assert_eq!(kept.as_deref(), Some("#00ffff"), "the inverted red of the frontmost line"); +} + +/// An appearance moved from an axis line to one behind it is kept for every axis line, not the cleared source's. +#[test] +fn an_appearance_moved_to_an_axis_line_behind_is_kept() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + let (back, front) = (lines[0].id, lines[lines.len() - 1].id); + s.execute("paint.setStroke", &json!({"ids": [front.0], "color": "#ff0000"})).unwrap(); + s.execute("appearance.transfer", &json!({"source": front.0, "target": back.0})).unwrap(); + let kept = spec(&s, id).label_styles.axis_rows.unwrap().paint.stroke.and_then(|p| p.color()).map(|c| c.to_hex()); + assert_eq!(kept.as_deref(), Some("#ff0000"), "the moved red, not the cleared source"); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0 == "#ff0000")); +} + +/// A radar graph's spoke brought in front of its rings is still a spoke: what is set on it is kept for the spokes. +#[test] +fn a_radar_spoke_moved_in_front_of_the_rings_keeps_its_kind() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "radar"); + let spoke = line_nodes(&s, id)[0].id; + s.execute("object.arrange.bringToFront", &json!({"ids": [spoke.0]})).unwrap(); + assert_eq!(line_nodes(&s, id).last().map(|n| n.id), Some(spoke), "the spoke is in front of the rings"); + s.execute("paint.setStroke", &json!({"ids": [spoke.0], "color": "#0000ff"})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks[..3].iter().all(|l| l.0 == "#0000ff") && looks[3..].iter().all(|l| l.0 == "#999999"), "{looks:?}"); +} + +/// A graphic style linked to an axis line passes a redefinition on to every axis line. +#[test] +fn a_redefined_graphic_style_on_an_axis_line_is_kept() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#ff0000"})).unwrap(); + s.execute("graphicStyle.new", &json!({"id": rect.0, "name": "Axis"})).unwrap(); + let line = line_nodes(&s, id)[0].id; + s.execute("graphicStyle.apply", &json!({"name": "Axis", "ids": [line.0]})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#00ff00"})).unwrap(); + s.execute("graphicStyle.redefine", &json!({"name": "Axis", "id": rect.0})).unwrap(); + let kept = spec(&s, id).label_styles.axis_rows.unwrap().paint.stroke.and_then(|p| p.color()).map(|c| c.to_hex()); + assert_eq!(kept.as_deref(), Some("#00ff00")); +} + +/// An Eyedropper pick and Apply Stroke to Fill on an axis line are kept for every axis line. +#[test] +fn an_eyedropper_pick_and_stroke_to_fill_on_an_axis_line_are_kept() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [rect.0], "none": true})).unwrap(); + let line = line_nodes(&s, id)[0].id; + s.execute("appearance.copyFrom", &json!({"source": rect.0, "ids": [line.0]})).unwrap(); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0 == "#ff0000" && l.1 == 1.0), "the picked 1 pt red stroke"); + let line = line_nodes(&s, id)[1].id; + s.execute("addon.color.strokeToFill", &json!({"ids": [line.0]})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + let fills: Vec<String> = line_nodes(&s, id).iter().map(|n| n.appearance.fill_paint().color().map(|c| c.to_hex()).unwrap_or_default()).collect(); + assert!(fills.iter().all(|f| f == "#ff0000"), "{fills:?}"); +} + +/// Setting a line to the paint it is drawn with by default keeps nothing, and is no edit. +#[test] +fn axis_lines_given_their_default_paint_keep_nothing() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let line = line_nodes(&s, id)[0].id; + let undo = s.doc().unwrap().history.undo.len(); + s.execute("paint.setStroke", &json!({"ids": [line.0], "color": "#000000"})).unwrap(); + assert_eq!(spec(&s, id).label_styles.axis_rows, None); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changed"); +} + +/// `object.setProps` and `transparency.set` without an `item` keep only a line's object opacity: the stroke its kind +/// keeps from another line stays, though the line they are given still shows the default stroke. +#[test] +fn an_object_opacity_on_an_axis_line_keeps_the_stroke_its_kind_keeps() { + for (cmd, params) in [("object.setProps", json!({"opacity": 50})), ("transparency.set", json!({"opacity": 50}))] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + assert_eq!(line_look(&line_nodes(&s, id)[1]).0, "#000000", "the other lines show black until the graph is drawn again"); + let mut p = params.clone(); + p["ids"] = json!([lines[1].id.0]); + s.execute(cmd, &p).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#ff0000" && (l.2 - 0.5).abs() < 1e-6), "{cmd}: {looks:?}"); + } +} + +/// A stroke painted on an axis line after another axis line's stroke was set to None is kept for every axis line with +/// the painted line's weight, not the zero weight the unpainted stroke left on its kind. +#[test] +fn a_stroke_painted_after_an_axis_line_lost_its_stroke_keeps_a_weight() { + let cases = ["paint.setStroke", "addon.color.fillToStroke", "appearance.setItem"]; + every_case(cases, |cmd| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + let weight = line_look(&lines[1]).1; + assert!(weight > 0.0, "{cmd}: the line has a stroke weight: {weight}"); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "none": true})).unwrap(); + let b = lines[1].id.0; + match *cmd { + "paint.setStroke" => s.execute(cmd, &json!({"ids": [b], "color": "#ff0000"})).unwrap(), + "addon.color.fillToStroke" => { + s.execute("paint.setFill", &json!({"ids": [b], "color": "#ff0000"})).unwrap(); + s.execute(cmd, &json!({"ids": [b]})).unwrap() + } + _ => s.execute(cmd, &json!({"ids": [b], "index": top_row(&s, lines[1].id, false), "color": "#ff0000"})).unwrap(), + }; + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#ff0000" && (l.1 - weight).abs() < 1e-9), "{cmd}: {looks:?}"); + }); +} + +/// A zero stroke weight set together with a stroke color on an axis line is kept for every axis line as set, also when +/// a stroke is painted on another axis line before the graph is drawn again. +#[test] +fn a_zero_weight_set_with_a_stroke_color_on_an_axis_line_is_kept() { + every_case([false, true], |repaint| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "none": true})).unwrap(); + let at = top_row(&s, lines[1].id, false); + s.execute("appearance.setItem", &json!({"ids": [lines[1].id.0], "index": at, "color": "#ff0000", "weight": 0})).unwrap(); + let color = if *repaint { + s.execute("paint.setStroke", &json!({"ids": [lines[2].id.0], "color": "#0000ff"})).unwrap(); + "#0000ff" + } else { + "#ff0000" + }; + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == color && l.1 == 0.0), "repaint {repaint}: {looks:?}"); + }); +} + +/// A reorder that leaves an axis line's rows as they were keeps what its kind keeps from another line and is no edit. +#[test] +fn a_reorder_that_changes_nothing_on_an_axis_line_keeps_the_stroke_its_kind_keeps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + assert_eq!(line_look(&line_nodes(&s, id)[1]).0, "#000000", "the other lines show black until the graph is drawn again"); + let stroke = top_row(&s, lines[1].id, false); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("appearance.moveItem", &json!({"ids": [lines[1].id.0], "from": stroke, "to": stroke})).unwrap(); + s.execute("appearance.moveItem", &json!({"ids": [lines[1].id.0], "indices": [stroke], "to": stroke})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changed"); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#ff0000"), "{looks:?}"); +} + +/// An Eyedropper pick that applies only the object's transparency to an axis line keeps the stroke its kind keeps, though +/// the line it is applied to still shows the default stroke. +#[test] +fn a_transparency_only_pick_on_an_axis_line_keeps_the_stroke_its_kind_keeps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("transparency.set", &json!({"ids": [rect.0], "opacity": 50})).unwrap(); + let lines = line_nodes(&s, id); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + assert_eq!(line_look(&line_nodes(&s, id)[1]).0, "#000000", "the other lines show black until the graph is drawn again"); + let fill = json!({"color": false, "transparency": false, "overprint": false}); + let stroke = json!({"color": false, "transparency": false, "overprint": false, "weight": false, "cap": false, "join": false, "miter": false, "dash": false}); + let apply = json!({"appearance": {"transparency": true, "fill": fill, "stroke": stroke}, "character": false, "paragraph": false}); + s.execute("appearance.copyFrom", &json!({"source": rect.0, "ids": [lines[1].id.0], "apply": apply})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#ff0000" && (l.2 - 0.5).abs() < 1e-6), "{looks:?}"); +} + +/// The Eyedropper Options that apply every fill and stroke attribute but not the object's transparency. +fn every_row_attribute_without_transparency() -> serde_json::Value { + let fill = json!({"color": true, "transparency": true, "overprint": true}); + let stroke = + json!({"color": true, "transparency": true, "overprint": true, "weight": true, "cap": true, "join": true, "miter": true, "dash": true}); + json!({"appearance": {"transparency": false, "fill": fill, "stroke": stroke}, "character": false, "paragraph": false}) +} + +/// An Eyedropper pick of every fill and stroke attribute without the object's transparency, with or without `append`, +/// keeps the object opacity the axis lines keep from another line, though the line it is applied to still shows 100%. +#[test] +fn a_pick_without_transparency_on_an_axis_line_keeps_the_opacity_its_kind_keeps() { + for append in [false, true] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [rect.0], "none": true})).unwrap(); + let lines = line_nodes(&s, id); + s.execute("transparency.set", &json!({"ids": [lines[0].id.0], "opacity": 40})).unwrap(); + assert_eq!(line_look(&line_nodes(&s, id)[1]).2, 1.0, "append {append}: the other lines show 100% until the graph is drawn again"); + let pick = json!({"source": rect.0, "ids": [lines[1].id.0], "apply": every_row_attribute_without_transparency(), "append": append}); + s.execute("appearance.copyFrom", &pick).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#ff0000" && (l.2 - 0.4).abs() < 1e-6), "append {append}: {looks:?}"); + } +} + +/// A graphic style added on top of a graph label's or axis line's appearance keeps the object opacity its kind keeps +/// from another label or line, though the one it is added to still shows 100%. +#[test] +fn a_graphic_style_added_to_a_label_or_axis_line_keeps_the_opacity_its_kind_keeps() { + for label in [false, true] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [rect.0], "none": true})).unwrap(); + s.execute("graphicStyle.new", &json!({"id": rect.0, "name": "Red"})).unwrap(); + let (first, second) = if label { + (text_id(&s, id, "Axes", "Q1"), text_id(&s, id, "Axes", "Q2")) + } else { + let lines = line_nodes(&s, id); + (lines[0].id, lines[1].id) + }; + s.execute("transparency.set", &json!({"ids": [first.0], "opacity": 40})).unwrap(); + assert_eq!(s.doc().unwrap().doc.node(second).unwrap().opacity, 1.0, "label {label}: 100% until the graph is drawn again"); + s.execute("graphicStyle.apply", &json!({"name": "Red", "ids": [second.0], "add": true})).unwrap(); + if label { + let looks = redrawn_label_rows(&mut s, id); + for q in ["Q1", "Q2", "Q3"] { + let (rows, opacity) = rows_of(&looks, q); + assert!((opacity - 0.4).abs() < 1e-6 && rows.iter().any(|r| !r.0 && r.1 == "#ff0000"), "{q}: {rows:?} {opacity}"); + } + } else { + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#ff0000" && (l.2 - 0.4).abs() < 1e-6), "{looks:?}"); + } + } +} + +/// A fill-only graphic style added on top of a graph label or axis line, or a fill-only source appended to one with the +/// Eyedropper, keeps the stroke its kind keeps from another label or line, though the one it is added to still shows its +/// own. +#[test] +fn a_fill_added_to_a_label_or_axis_line_keeps_the_stroke_its_kind_keeps() { + let cases = [(false, false), (false, true), (true, false), (true, true)]; + every_case(cases, |&(label, append)| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let (rect, _) = blue_style(&mut s, "Blue", false); + let (first, second) = if label { + (text_id(&s, id, "Axes", "Q1"), text_id(&s, id, "Axes", "Q2")) + } else { + let lines = line_nodes(&s, id); + (lines[0].id, lines[1].id) + }; + if label { + s.execute("appearance.addStroke", &json!({"ids": [first.0]})).unwrap(); + s.execute("appearance.setItem", &json!({"ids": [first.0], "index": top_row(&s, first, false), "color": "#ff0000"})).unwrap(); + } else { + s.execute("paint.setStroke", &json!({"ids": [first.0], "color": "#ff0000"})).unwrap(); + } + if append { + let pick = json!({"source": rect.0, "ids": [second.0], "apply": every_row_attribute_without_transparency(), "append": true}); + s.execute("appearance.copyFrom", &pick).unwrap(); + } else { + s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [second.0], "add": true})).unwrap(); + } + if label { + let looks = redrawn_label_rows(&mut s, id); + for q in ["Q1", "Q2", "Q3"] { + let (rows, _) = rows_of(&looks, q); + let shows = |fill: bool, hex: &str| rows.iter().any(|r| r.0 == fill && r.1 == hex); + assert!(shows(false, "#ff0000") && shows(true, "#0000ff"), "{q}: {rows:?}"); + } + } else { + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#ff0000"), "{looks:?}"); + } + }); +} + +/// A stroke a label's kind keeps below the characters stays below them when a fill-only graphic style is added on top of +/// another label of the kind, or a fill-only source appended to it, and the new fill paints above the characters. +#[test] +fn a_fill_added_to_a_label_keeps_the_kept_stroke_below_the_characters() { + every_case([false, true], |&append| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let (rect, _) = blue_style(&mut s, "Blue", false); + let (q1, q2) = (text_id(&s, id, "Axes", "Q1"), text_id(&s, id, "Axes", "Q2")); + s.execute("appearance.addStroke", &json!({"ids": [q1.0]})).unwrap(); + s.execute("appearance.moveItem", &json!({"ids": [q1.0], "from": "contents", "to": 1})).unwrap(); + if append { + let pick = json!({"source": rect.0, "ids": [q2.0], "apply": every_row_attribute_without_transparency(), "append": true}); + s.execute("appearance.copyFrom", &pick).unwrap(); + } else { + s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [q2.0], "add": true})).unwrap(); + } + redrawn_label_rows(&mut s, id); + let look = |ap: &vectorcraft_doc::Appearance| (ap.contents_at(), ap.items.iter().map(|it| it.is_fill()).collect::<Vec<_>>()); + for q in ["Q1", "Q2", "Q3"] { + assert_eq!(look(&label_node(&s, id, "Axes", q).appearance), (1, vec![false, true]), "append {append}: {q}"); + } + }); +} + +/// A Contents (Characters) row move that leaves a graph label as it was keeps the rows its kind keeps from another label +/// and is no edit. +#[test] +fn a_contents_move_that_changes_nothing_on_a_label_keeps_the_rows_its_kind_keeps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let (q1, q2) = (text_id(&s, id, "Axes", "Q1"), text_id(&s, id, "Axes", "Q2")); + s.execute("appearance.addStroke", &json!({"ids": [q1.0]})).unwrap(); + s.execute("appearance.setItem", &json!({"ids": [q1.0], "index": top_row(&s, q1, false), "color": "#ff0000"})).unwrap(); + let at = s.doc().unwrap().doc.node(q2).unwrap().appearance.contents_at(); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("appearance.moveItem", &json!({"ids": [q2.0], "from": "contents", "to": at})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changed"); + let looks = redrawn_label_rows(&mut s, id); + for q in ["Q1", "Q2", "Q3"] { + let (rows, _) = rows_of(&looks, q); + assert!(rows.iter().any(|r| !r.0 && r.1 == "#ff0000"), "{q}: {rows:?}"); + } +} + +/// An Eyedropper pick with `append` and without the object's transparency on a graph label keeps the object opacity its +/// kind keeps from another label, though the label it is applied to still shows 100%. +#[test] +fn an_appended_pick_without_transparency_on_a_label_keeps_the_opacity_its_kind_keeps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [rect.0], "none": true})).unwrap(); + s.execute("transparency.set", &json!({"ids": [text_id(&s, id, "Axes", "Q1").0], "opacity": 40})).unwrap(); + let q2 = text_id(&s, id, "Axes", "Q2"); + assert_eq!(s.doc().unwrap().doc.node(q2).unwrap().opacity, 1.0, "Q2 shows 100% until the graph is drawn again"); + let pick = json!({"source": rect.0, "ids": [q2.0], "apply": every_row_attribute_without_transparency(), "append": true}); + s.execute("appearance.copyFrom", &pick).unwrap(); + let looks = redrawn_label_rows(&mut s, id); + for q in ["Q1", "Q2", "Q3"] { + let (rows, opacity) = rows_of(&looks, q); + assert!((opacity - 0.4).abs() < 1e-6, "{q}: {opacity}"); + assert!(rows.iter().any(|r| !r.0 && r.1 == "#ff0000"), "{q}: {rows:?}"); + } +} + +/// An edit of some attributes on an axis line that still shows the default stroke keeps what it changes, and the stroke +/// its kind keeps from another line stays: a cap is not kept, so it changes nothing the kind keeps. +#[test] +fn an_edit_of_some_attributes_on_an_axis_line_keeps_the_rest_its_kind_keeps() { + let cases = [ + ("stroke.set", json!({"cap": "round"}), ""), + ("paint.setFill", json!({"color": "#0000ff"}), "#0000ff"), + ("appearance.setItem", json!({"index": 0, "color": "#00ff00"}), "#00ff00"), + ]; + for (cmd, params, fill) in cases { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + assert_eq!(line_look(&line_nodes(&s, id)[1]).0, "#000000", "{cmd}: the other lines show black until the graph is drawn again"); + let mut p = params.clone(); + p["ids"] = json!([lines[1].id.0]); + s.execute(cmd, &p).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| *l == ("#ff0000".into(), 0.5, 1.0)), "{cmd}: {looks:?}"); + let fills: Vec<String> = + line_nodes(&s, id).iter().map(|n| n.appearance.fill_paint().color().map(|c| c.to_hex()).unwrap_or_default()).collect(); + assert!(fills.iter().all(|f| f == fill), "{cmd}: {fills:?}"); + } +} + +/// An opacity and a stroke weight given to a radar graph's ring are kept for its rings, and its spokes keep their own. +#[test] +fn transparency_and_stroke_weight_on_a_radar_ring_are_kept_for_its_rings() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "radar"); + let ring = line_nodes(&s, id)[3].id; + s.execute("transparency.set", &json!({"ids": [ring.0], "opacity": 40})).unwrap(); + s.execute("stroke.set", &json!({"ids": [ring.0], "weight": 1})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks[..3].iter().all(|l| *l == ("#000000".into(), 0.5, 1.0)), "{looks:?}"); + assert!(looks[3..].iter().all(|l| l.0 == "#999999" && l.1 == 1.0 && (l.2 - 0.4).abs() < 1e-6), "{looks:?}"); +} + +/// A placed gradient on an axis line's stroke is kept for every axis line without its placement. +#[test] +fn a_gradient_on_an_axis_line_is_kept_without_its_placement() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let line = line_nodes(&s, id)[0].id; + s.execute("paint.editGradient", &json!({"ids": [line.0], "kind": "linear", "stroke": true})).unwrap(); + let placement = json!({"ids": [line.0], "stroke": true, "start": [100, 100], "end": [200, 100], "aspect": 50}); + s.execute("paint.setGradientGeom", &placement).unwrap(); + let shown = line_nodes(&s, id)[0].appearance.stroke_paint().clone(); + assert!(matches!(&shown, Paint::Gradient(g) if g.geom.is_some()), "the line's gradient is placed: {shown:?}"); + let kept = spec(&s, id).label_styles.axis_rows.unwrap().paint.stroke; + assert!(matches!(&kept, Some(Paint::Gradient(g)) if g.geom.is_none() && g.freeform.is_none()), "{kept:?}"); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + assert!(line_nodes(&s, id).iter().all(|n| matches!(n.appearance.stroke_paint(), Paint::Gradient(_)))); +} + +/// Default Fill and Stroke and Apply Fill to Stroke on an axis line are kept for every axis line. +#[test] +fn default_fill_and_stroke_and_fill_to_stroke_on_an_axis_line_are_kept() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let line = line_nodes(&s, id)[0].id; + s.execute("paint.setStroke", &json!({"ids": [line.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.default", &json!({"ids": [line.0]})).unwrap(); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| *l == ("#000000".into(), 1.0, 1.0)), "the 1 pt black default stroke"); + let fills: Vec<String> = line_nodes(&s, id).iter().map(|n| n.appearance.fill_paint().color().map(|c| c.to_hex()).unwrap_or_default()).collect(); + assert!(fills.iter().all(|f| f == "#ffffff"), "{fills:?}"); + let line = line_nodes(&s, id)[1].id; + s.execute("paint.setFill", &json!({"ids": [line.0], "color": "#0000ff"})).unwrap(); + s.execute("addon.color.fillToStroke", &json!({"ids": [line.0]})).unwrap(); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0 == "#0000ff"), "the blue fill on the stroke"); +} + +/// The Appearance commands and `graphicStyle.apply` given a graph's Axes group or Legend group edit the lines and labels +/// directly in it, as given a series group they edit its paths: every line and label of each kind keeps what they set +/// when the graph is drawn again, and the groups keep no rows of their own. +#[test] +fn appearance_commands_given_the_axes_or_legend_group_edit_its_lines_and_labels() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let part = |s: &Session, name: &str| group(s.doc().unwrap().doc.node(id).unwrap(), name).clone(); + s.execute("appearance.clear", &json!({"ids": [part(&s, "Axes").id.0]})).unwrap(); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0.is_empty()), "the cleared lines have no stroke"); + let (_, blue) = blue_style(&mut s, "Blue", false); + for name in ["Axes", "Legend"] { + s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [part(&s, name).id.0]})).unwrap(); + } + let kept = spec(&s, id).label_styles; + let fill = |rows: Option<vectorcraft_doc::LabelRows>| rows.and_then(|r| r.paint.fill); + assert_eq!(fill(kept.axis_rows), Some(blue.clone()), "axis lines"); + assert_eq!(fill(kept.values_rows), Some(blue.clone()), "value labels"); + assert_eq!(fill(kept.legend_rows), Some(blue.clone()), "legend labels"); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + for name in ["Axes", "Legend"] { + let g = part(&s, name); + assert!(g.appearance.items.is_empty(), "{name} keeps no rows of its own"); + let members: Vec<Paint> = g.children().unwrap().iter().map(|c| c.appearance.fill_paint()).collect(); + assert!(!members.is_empty() && members.iter().all(|p| *p == blue), "{name}: {members:?}"); + } +} + +/// A row index given the Axes group, whose lines and labels have different rows, is refused unless it is `aligned`, a row +/// of the backmost member's stack: then the members that share that row change, the labels keep theirs, and the graph +/// keeps the change when it is drawn again. +#[test] +fn a_row_index_given_the_axes_group_is_a_row_of_its_backmost_member_with_aligned() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let axes = group(s.doc().unwrap().doc.node(id).unwrap(), "Axes").clone(); + let back = axes.children().unwrap()[0].id; + assert!(line_nodes(&s, id).iter().any(|l| l.id == back), "the backmost member is a line"); + let stroke = top_row(&s, back, false); + for (cmd, p) in [ + ("appearance.setItem", json!({"ids": [axes.id.0], "index": stroke, "color": "#ff0000"})), + ("appearance.removeItem", json!({"ids": [axes.id.0], "index": stroke})), + ("appearance.duplicateItem", json!({"ids": [axes.id.0], "index": stroke})), + ("appearance.moveItem", json!({"ids": [axes.id.0], "from": stroke, "to": 0})), + ("transparency.set", json!({"ids": [axes.id.0], "item": stroke, "opacity": 40})), + ] { + let err = s.execute(cmd, &p).unwrap_err().to_string(); + assert!(err.contains("aligned"), "{cmd}: {err}"); + } + let labels = |s: &Session| -> Vec<vectorcraft_doc::Appearance> { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + group(&n, "Axes").children().unwrap().iter().filter(|c| matches!(c.kind, NodeKind::Text(_))).map(|c| (*c.appearance).clone()).collect() + }; + let was = labels(&s); + s.execute("appearance.setItem", &json!({"ids": [axes.id.0], "index": stroke, "color": "#ff0000", "aligned": true})).unwrap(); + s.execute("transparency.set", &json!({"ids": [axes.id.0], "item": stroke, "opacity": 40, "aligned": true})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#ff0000"), "{looks:?}"); + let rows = spec(&s, id).label_styles.axis_rows.unwrap(); + assert_eq!(rows.paint.stroke.and_then(|p| p.color()).map(|c| c.to_hex()).as_deref(), Some("#ff0000")); + let now = labels(&s); + assert!(!now.is_empty() && now.iter().all(|a| *a == was[0]), "the labels keep their rows"); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let l = &group(&n, "Axes").children().unwrap()[0]; + assert!((l.appearance.items[top_row(&s, l.id, false)].opacity() - 0.4).abs() < 1e-6, "the stroke row's opacity is kept"); +} + +/// An aligned row edit given the Axes group leaves alone what a kind of label keeps from a label without that row: the +/// category labels keep the orange fill row of one of them through an edit of the lines' stroke rows. +#[test] +fn an_aligned_row_edit_given_the_axes_group_keeps_the_rows_of_labels_it_did_not_reach() { + let cases = [("appearance.setItem", json!({"color": "#0000ff"})), ("appearance.duplicateItem", json!({})), ("appearance.removeItem", json!({}))]; + every_case(cases, |(cmd, params)| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let c = text_id(&s, id, "Axes", "Q2"); + s.execute("appearance.addFill", &json!({"ids": [c.0]})).unwrap(); + s.execute("appearance.setItem", &json!({"ids": [c.0], "index": 0, "color": "#ff8000"})).unwrap(); + let kept = spec(&s, id).label_styles.categories_rows; + assert!(kept.is_some(), "the category labels keep the orange row"); + let axes = group(s.doc().unwrap().doc.node(id).unwrap(), "Axes").clone(); + let back = axes.children().unwrap()[0].id; + let mut p = params.clone(); + p["ids"] = json!([axes.id.0]); + p["index"] = json!(top_row(&s, back, false)); + p["aligned"] = json!(true); + s.execute(cmd, &p).unwrap(); + assert_eq!(spec(&s, id).label_styles.categories_rows, kept, "{cmd}"); + }); +} + +/// An edit of a hidden row of an axis line leaves what its kind keeps from another line: the line's visible rows did not +/// change. +#[test] +fn an_edit_of_a_hidden_row_of_an_axis_line_keeps_what_its_kind_keeps() { + let cases = [ + ("appearance.setItem", json!({"color": "#0000ff"})), + ("appearance.duplicateItem", json!({})), + ("appearance.removeItem", json!({})), + ("transparency.set", json!({"opacity": 40})), + ("paint.setStroke", json!({"color": "#0000ff"})), + ]; + every_case(cases, |(cmd, params)| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + let line = lines[1].id; + s.execute("appearance.addStroke", &json!({"ids": [line.0]})).unwrap(); + let hidden = top_row(&s, line, false); + s.execute("appearance.setItem", &json!({"ids": [line.0], "index": hidden, "visible": false})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + let kept = spec(&s, id).label_styles.axis_rows; + let mut p = params.clone(); + p["ids"] = json!([line.0]); + p[if cmd.starts_with("appearance.") { "index" } else { "item" }] = json!(hidden); + s.execute(cmd, &p).unwrap(); + assert_eq!(spec(&s, id).label_styles.axis_rows, kept, "{cmd}"); + }); +} + +/// An Eyedropper pick of only the object's opacity, or of only stroke options the graph does not keep, on an axis line +/// keeps the stroke its kind keeps from another line, though the line it is given still shows the default stroke. +#[test] +fn an_eyedropper_pick_of_only_the_opacity_keeps_the_stroke_its_kind_keeps() { + let fill = json!({"color": false, "transparency": false, "overprint": false}); + let stroke = |dash: bool| json!({"color": false, "transparency": false, "overprint": false, "weight": false, "cap": false, "join": false, "miter": false, "dash": dash}); + let cases = [ + (json!({"appearance": {"transparency": true, "fill": fill, "stroke": stroke(false)}}), 0.5), + (json!({"appearance": {"transparency": false, "fill": fill, "stroke": stroke(true)}}), 1.0), + ]; + every_case(cases, |(pick, opacity)| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.setProps", &json!({"ids": [rect.0], "opacity": 50})).unwrap(); + s.execute("stroke.set", &json!({"ids": [rect.0], "dash": [4, 2]})).unwrap(); + let lines = line_nodes(&s, id); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": rect.0, "ids": [lines[1].id.0], "pickUp": pick})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#ff0000" && (l.2 - *opacity).abs() < 1e-6), "{pick}: {looks:?}"); + }); +} + +/// Default Fill and Stroke on a label or an axis line that already shows the default paint is kept for its kind, in +/// place of the paint the kind keeps from another label or line. +#[test] +fn default_fill_and_stroke_on_a_label_or_line_that_shows_it_is_kept_for_its_kind() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + s.execute("paint.setFill", &json!({"ids": [text_id(&s, id, "Axes", "4").0], "color": "#ff0000"})).unwrap(); + let hex = |st: &CharStyle| st.fill.color().map(|c| c.to_hex()); + assert_eq!(hex(&label_run_style(&s, id, "Axes", "0")).as_deref(), Some("#000000"), "the other labels show black until the graph is drawn again"); + s.execute("paint.default", &json!({"ids": [text_id(&s, id, "Axes", "0").0]})).unwrap(); + label_looks(&mut s, id); + let st = label_run_style(&s, id, "Axes", "4"); + assert_eq!((hex(&st).as_deref(), st.stroke.is_none()), (Some("#000000"), true)); + let lines = line_nodes(&s, id); + s.execute("paint.default", &json!({"ids": [lines[0].id.0]})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [lines[1].id.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.default", &json!({"ids": [lines[0].id.0]})).unwrap(); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| *l == ("#000000".into(), 1.0, 1.0)), "the 1 pt black default stroke"); +} + +/// Default Fill and Stroke on a label of a kind that keeps no style, which already shows the default paint, is no edit. +#[test] +fn default_fill_and_stroke_on_a_label_that_shows_it_is_no_edit() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("paint.default", &json!({"ids": [text_id(&s, id, "Axes", "4").0]})).unwrap(); + assert_eq!(spec(&s, id).label_styles.values, None); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changed"); +} + +/// Redefine Graphic Style on an Axes group linked to the style with rows of its own (as a file can hold it) restyles and +/// links the lines and labels in it, and clears and unlinks the group; Break Link given the group unlinks them. A style +/// applied through the group links its lines and labels, and the graph keeps their look, not the link, when it is drawn +/// again. +#[test] +fn graphic_style_links_given_the_axes_group() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let axes = group(s.doc().unwrap().doc.node(id).unwrap(), "Axes").id; + let (rect, _) = blue_style(&mut s, "Blue", false); + let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().clone(); + s.edit("Link", |d, _| { + let g = d.node_mut(axes).unwrap(); + g.appearance = style.appearance.clone().into(); + g.extras_mut().graphic_style = Some(style.id); + Ok(()) + }) + .unwrap(); + s.execute("appearance.setItem", &json!({"ids": [rect.0], "index": top_row(&s, rect, true), "color": "#00ff00", "opacity": 100})).unwrap(); + let green = s.doc().unwrap().doc.node(rect).unwrap().appearance.fill_paint(); + s.execute("graphicStyle.redefine", &json!({"name": "Blue", "id": rect.0})).unwrap(); + let axes_now = |s: &Session| group(s.doc().unwrap().doc.node(id).unwrap(), "Axes").clone(); + let members = |s: &Session| -> Vec<(Paint, Option<u32>)> { + axes_now(s).children().unwrap().iter().map(|c| (c.appearance.fill_paint(), c.extras().graphic_style)).collect() + }; + let g = axes_now(&s); + assert!(g.appearance.items.is_empty() && g.extras().graphic_style.is_none(), "the group is cleared and unlinked"); + assert!(members(&s).iter().all(|m| *m == (green.clone(), Some(style.id))), "{:?}", members(&s)); + s.execute("graphicStyle.breakLink", &json!({"ids": [axes_now(&s).id.0]})).unwrap(); + assert!(members(&s).iter().all(|m| m.1.is_none()), "unlinked"); + s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [axes_now(&s).id.0]})).unwrap(); + assert!(members(&s).iter().all(|m| m.1 == Some(style.id)), "linked"); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + assert!(members(&s).iter().all(|m| *m == (green.clone(), None)), "{:?}", members(&s)); +} + +/// The Appearance commands given a radar graph's Axes group reach its spokes and rings, which keep the edit apart. +#[test] +fn a_style_given_a_radar_graphs_axes_group_is_kept_for_spokes_and_rings() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "radar"); + let axes = group(s.doc().unwrap().doc.node(id).unwrap(), "Axes").id; + let (_, blue) = blue_style(&mut s, "Blue", false); + s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [axes.0]})).unwrap(); + let kept = spec(&s, id).label_styles; + let fill = |rows: Option<vectorcraft_doc::LabelRows>| rows.and_then(|r| r.paint.fill); + assert_eq!(fill(kept.axis_rows), Some(blue.clone()), "spokes"); + assert_eq!(fill(kept.ring_rows), Some(blue.clone()), "rings"); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0.is_empty()), "the style has no stroke: {looks:?}"); +} + +/// Default Fill and Stroke on an axis line that already shows the default paint is kept for every axis line, in place of +/// the stroke the kind keeps from another line, and leaves the object opacity the kind keeps from another line. +#[test] +fn default_fill_and_stroke_on_an_axis_line_that_shows_it_is_kept() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + s.execute("paint.default", &json!({"ids": [lines[0].id.0]})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [lines[1].id.0], "color": "#ff0000"})).unwrap(); + s.execute("object.setProps", &json!({"ids": [lines[1].id.0], "opacity": 50})).unwrap(); + s.execute("paint.default", &json!({"ids": [lines[0].id.0]})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| (l.0.as_str(), l.1) == ("#000000", 1.0)), "the 1 pt black default stroke: {looks:?}"); + assert!(looks.iter().all(|l| (l.2 - 0.5).abs() < 1e-6), "the kind keeps its 50% opacity: {looks:?}"); +} + +/// A stroke paint written to an axis line that already shows it is kept for every axis line, in place of the stroke the +/// kind keeps from another line. +#[test] +fn a_stroke_written_to_an_axis_line_that_shows_it_is_kept() { + let cases = [("paint.setStroke", json!({"color": "#000000"})), ("addon.color.fillToStroke", json!({}))]; + every_case(cases, |(cmd, params)| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + s.execute("paint.setFill", &json!({"ids": [lines[1].id.0], "color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + assert_eq!(line_look(&line_nodes(&s, id)[1]).0, "#000000", "{cmd}: the other lines show black until the graph is drawn again"); + let mut p = params.clone(); + p["ids"] = json!([lines[1].id.0]); + s.execute(cmd, &p).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#000000"), "{cmd}: {looks:?}"); + }); +} + +/// A stroke added to an axis line whose stroke shows the paint the new one takes is kept for every axis line, in place of +/// the stroke the kind keeps from another line. +#[test] +fn a_stroke_added_to_an_axis_line_is_kept() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + assert_eq!(line_look(&line_nodes(&s, id)[1]).0, "#000000", "the other lines show black until the graph is drawn again"); + s.execute("appearance.addStroke", &json!({"ids": [lines[1].id.0]})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| (l.0.as_str(), l.1) == ("#000000", 1.0)), "the added 1 pt black stroke: {looks:?}"); +} + +/// An Eyedropper pick of the stroke color, weight or transparency alone onto an axis line that already shows what it +/// writes is kept for every axis line, in place of what the kind keeps from another line. +#[test] +fn an_eyedropper_pick_an_axis_line_already_shows_is_kept() { + let stroke_row = |n: &vectorcraft_doc::Node| n.appearance.items.iter().rposition(|it| !it.is_fill()).unwrap(); + let cases = [("color", json!({"color": "#ff0000"})), ("weight", json!({"weight": 2})), ("transparency", json!({"opacity": 40}))]; + every_case(cases, |(attr, edit)| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [rect.0], "weight": 0.5})).unwrap(); + let lines = line_nodes(&s, id); + let mut p = edit.clone(); + p["ids"] = json!([lines[0].id.0]); + match *attr { + "color" => s.execute("paint.setStroke", &p), + "weight" => s.execute("stroke.set", &p), + _ => { + p["index"] = json!(stroke_row(&lines[0])); + s.execute("appearance.setItem", &p) + } + } + .unwrap(); + let shown = line_nodes(&s, id)[1].clone(); + assert_eq!(line_look(&shown), ("#000000".into(), 0.5, 1.0), "{attr}: the other lines show the default until the graph is drawn again"); + let fill = json!({"color": false, "transparency": false, "overprint": false}); + let mut stroke = json!({"color": false, "transparency": false, "overprint": false, "weight": false, "cap": false, "join": false, "miter": false, "dash": false}); + stroke[*attr] = json!(true); + let apply = json!({"appearance": {"transparency": false, "fill": fill, "stroke": stroke}, "character": false, "paragraph": false}); + s.execute("appearance.copyFrom", &json!({"source": rect.0, "ids": [lines[1].id.0], "apply": apply})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| *l == ("#000000".into(), 0.5, 1.0)), "{attr}: {looks:?}"); + let opacities: Vec<f32> = line_nodes(&s, id).iter().map(|n| n.appearance.items[stroke_row(n)].opacity()).collect(); + assert!(opacities.iter().all(|o| *o == 1.0), "{attr}: {opacities:?}"); + }); +} + +/// A stroke color, weight or opacity set with `appearance.setItem`, or a weight set with `stroke.set`, on an axis line +/// that already shows it is kept for every axis line, in place of what the kind keeps from another line. +#[test] +fn a_row_attribute_set_on_an_axis_line_that_shows_it_is_kept() { + let stroke_row = |n: &vectorcraft_doc::Node| n.appearance.items.iter().rposition(|it| !it.is_fill()).unwrap(); + let cases = [ + ("appearance.setItem", json!({"color": "#ff0000"}), json!({"color": "#000000"})), + ("appearance.setItem", json!({"weight": 2}), json!({"weight": 0.5})), + ("appearance.setItem", json!({"opacity": 40}), json!({"opacity": 100})), + ("stroke.set", json!({"weight": 2}), json!({"weight": 0.5})), + ]; + every_case(cases, |(cmd, kept, shown)| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + for (line, values) in [(&lines[0], kept), (&lines[1], shown)] { + let mut p = values.clone(); + p["ids"] = json!([line.id.0]); + if *cmd == "appearance.setItem" { + p["index"] = json!(stroke_row(line)); + } + s.execute(cmd, &p).unwrap(); + } + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| *l == ("#000000".into(), 0.5, 1.0)), "{cmd} {shown}: {looks:?}"); + let opacities: Vec<f32> = line_nodes(&s, id).iter().map(|n| n.appearance.items[stroke_row(n)].opacity()).collect(); + assert!(opacities.iter().all(|o| *o == 1.0), "{cmd} {shown}: {opacities:?}"); + }); +} + +/// `appearance.setItem` of a row's opacity alone on an axis line keeps the blend mode the kind keeps from another line, +/// and of its blend mode alone the opacity; a null weight or opacity writes nothing and adds no undo step. +#[test] +fn a_row_attribute_set_on_an_axis_line_keeps_the_others_its_kind_keeps() { + let stroke_row = |n: &vectorcraft_doc::Node| n.appearance.items.iter().rposition(|it| !it.is_fill()).unwrap(); + let row = |n: &vectorcraft_doc::Node| { + let it = &n.appearance.items[stroke_row(n)]; + (it.opacity(), it.blend()) + }; + let cases = [ + (json!({"blend": "multiply"}), json!({"opacity": 100}), (1.0, BlendMode::Multiply)), + (json!({"opacity": 40}), json!({"blend": "normal"}), (0.4, BlendMode::Normal)), + ]; + every_case(cases, |(kept, shown, want)| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + for (line, values) in [(&lines[0], kept), (&lines[1], shown)] { + let mut p = values.clone(); + p["ids"] = json!([line.id.0]); + p["index"] = json!(stroke_row(line)); + s.execute("appearance.setItem", &p).unwrap(); + } + redrawn_line_looks(&mut s, id); + let rows: Vec<(f32, BlendMode)> = line_nodes(&s, id).iter().map(row).collect(); + assert!(rows.iter().all(|r| *r == *want), "{shown}: {rows:?}"); + }); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + for key in ["weight", "opacity"] { + let mut p = json!({"ids": [lines[1].id.0], "index": stroke_row(&lines[1])}); + p[key] = serde_json::Value::Null; + s.execute("appearance.setItem", &p).unwrap(); + } + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "a null value adds no undo step"); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0 == "#ff0000")); +} + #[test] fn pie_names_and_wedge_labels_keep_their_style() { let mut s = Session::new(); @@ -7993,6 +9336,7 @@ fn graph_commands_refuse_params_of_the_wrong_type() { ("firstRowInFront", json!("yes"), "`firstRowInFront` must be true or false"), ("firstColumnInFront", json!(0), "`firstColumnInFront` must be true or false"), ("filledLines", json!("on"), "`filledLines` must be true or false"), + ("lineWidth", json!("4"), "`lineWidth` must be a number, not \"4\""), ("dropShadow", json!(1), "`dropShadow` must be true or false"), ("legendAcrossTop", json!("x"), "`legendAcrossTop` must be true or false"), ("type", json!(5), "`type` must be a string"), @@ -8156,7 +9500,154 @@ fn a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns() { } } } - assert!(live.contains(&"column v7.ai".to_string()) && live.contains(&"column pdf.ai".to_string()), "{live:?}"); + for ty in ["column", "stackedColumn", "area"] { + assert!(live.contains(&format!("{ty} v7.ai")) && live.contains(&format!("{ty} pdf.ai")), "{ty}: {live:?}"); + } +} + +/// A line graph the graph tools draw with Draw Filled Lines, saved as `.ai` in either form, opens again as the same graph +/// with its filled lines and Line Width, the default 3 pt included, and without a warning about graphs. A Line Width past +/// the records' 100 pt is saved as the graph's art, with the warning. +#[test] +fn a_drawn_graph_with_filled_lines_saved_as_ai_opens_with_them() { + let dir = vectorcraft_testkit::temp_dir("graph-ai-filled"); + for (width, live) in [(None, true), (Some(8.0), true), (Some(150.0), false)] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,1,6"; + let id = s.execute("graph.create", &json!({"type": "line", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"] + .as_u64() + .unwrap(); + let mut options = json!({"id": id, "filledLines": true}); + if let Some(w) = width { + options["lineWidth"] = json!(w); + } + s.execute("graph.setType", &options).unwrap(); + let written = spec(&s, NodeId(id)); + assert_eq!((written.filled_lines, written.line_width), (true, width)); + for (name, version) in [("v7.ai", Some("7")), ("pdf.ai", None)] { + let path = dir.join(format!("{width:?}-{name}")); + let mut p = json!({"path": path, "format": "ai"}); + if let Some(v) = version { + p["aiVersion"] = json!(v); + } + let r = s.execute("file.saveAs", &p).unwrap(); + let notes = r["warnings"].as_array().cloned().unwrap_or_default(); + let warned = notes.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("graphs are written as their art"))); + assert_eq!(warned, !live, "{width:?} {name}: {r}"); + let mut again = Session::new(); + again.execute("document.open", &json!({"path": path})).unwrap(); + let mut graphs = vec![]; + again.doc().unwrap().doc.walk(|n| graphs.extend(n.extras().graph.as_deref().map(|g| (n.id, g.clone())))); + assert_eq!(graphs.len(), usize::from(live), "{width:?} {name}"); + if let Some((gid, g)) = graphs.first() { + assert_eq!((g.kind, g.cells(), g.filled_lines, g.line_width), (written.kind, written.cells(), true, width), "{width:?} {name}"); + assert_eq!(g.filled_line_width(), written.filled_line_width(), "{width:?} {name}"); + // With Draw Filled Lines turned off, each series draws its thin 1 pt line again. + again.execute("select.set", &json!({"ids": [gid.0]})).unwrap(); + again.execute("graph.setType", &json!({"id": gid.0, "filledLines": false})).unwrap(); + for series in 0..2 { + let line = series_parts(&again, *gid, series) + .into_iter() + .any(|p| p.appearance.fill_paint().is_none() && !p.appearance.stroke_paint().is_none() && p.appearance.stroke_width() == 1.0); + assert!(line, "{width:?} {name}: series {series} draws no thin line"); + } + } + } + } +} + +/// A default legend swatch has the stroke paint and weight of its series' marks, beside the plot or across the top: the +/// thin white line of stacked columns and bars, areas and pie wedges, and none on columns and bars. A stroke color kept +/// on the series, with or without a weight of its own, is on the swatch too. +#[test] +fn a_legend_swatch_has_the_stroke_of_its_series_marks() { + let white = |w: f64| (Paint::solid(vectorcraft_color::Color::WHITE), w); + let cases = [ + ("stackedColumn", white(0.25)), + ("stackedBar", white(0.25)), + ("area", white(0.25)), + ("pie", white(0.5)), + ("column", (Paint::None, 0.0)), + ("bar", (Paint::None, 0.0)), + ]; + for (ty, stroke) in cases { + for across_top in [false, true] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,1,6"; + let id = NodeId( + s.execute("graph.create", &json!({"type": ty, "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("graph.setType", &json!({"id": id.0, "legendAcrossTop": across_top})).unwrap(); + for i in 0..2 { + let marks = marks_of(&s, id, i); + assert!(marks.len() > 1, "{ty} {i}: marks and a swatch"); + assert!(marks.iter().all(|m| (m.1.clone(), m.2) == stroke), "{ty} across top {across_top}, series {i}: {marks:?}"); + } + // A stroke color kept on series 0 without a weight keeps the default weight, then with one. + let bar = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].clone(); + let row = bar.appearance.items.iter().rposition(|it| !it.is_fill()); + let Some(row) = row else { continue }; + s.execute("appearance.setItem", &json!({"ids": [bar.id.0], "index": row, "color": "#ff0000"})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + let marks = marks_of(&s, id, 0); + assert!(marks.iter().all(|m| *m == marks[0]) && marks[0].1 != stroke.0, "{ty} across top {across_top}, red: {marks:?}"); + let bar = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id; + s.execute("appearance.setItem", &json!({"ids": [bar.0], "index": row, "weight": 3})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + let marks = marks_of(&s, id, 0); + assert!(marks.iter().all(|m| *m == marks[0]) && marks[0].2 == 3.0, "{ty} across top {across_top}, 3 pt: {marks:?}"); + } + } +} + +/// A stacked column graph the graph tools draw, saved as `.ai` in either form, opens again as the same graph without a +/// warning, and its data can be edited there. +#[test] +fn a_drawn_stacked_column_graph_saved_as_ai_opens_as_a_graph_that_takes_new_data() { + let dir = vectorcraft_testkit::temp_dir("graph-ai-stacked"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,1,6"; + let id = s.execute("graph.create", &json!({"type": "stackedColumn", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"] + .as_u64() + .unwrap(); + let written = spec(&s, NodeId(id)); + for (name, version) in [("v7.ai", Some("7")), ("pdf.ai", None)] { + let path = dir.join(name); + let mut p = json!({"path": path, "format": "ai"}); + if let Some(v) = version { + p["aiVersion"] = json!(v); + } + let r = s.execute("file.saveAs", &p).unwrap(); + let notes = r["warnings"].as_array().cloned().unwrap_or_default(); + assert!(!notes.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("graphs are written as their art"))), "{name}: {r}"); + let mut again = Session::new(); + again.execute("document.open", &json!({"path": path})).unwrap(); + let mut found = vec![]; + again.doc().unwrap().doc.walk(|n| { + if n.extras().graph.is_some() { + found.push(n.id); + } + }); + assert_eq!(found.len(), 1, "{name}"); + let g = spec(&again, found[0]); + assert_eq!((g.kind, g.cells()), (written.kind, written.cells()), "{name}"); + assert_eq!((g.series.as_slice(), g.categories.as_slice()), (&written.series[..], &written.categories[..]), "{name}"); + again.execute("select.set", &json!({"ids": [found[0].0]})).unwrap(); + again.execute("graph.setData", &json!({"id": found[0].0, "csv": ",2024,2025\nQ1,8,1\nQ2,2,7"})).unwrap(); + let after = spec(&again, found[0]); + assert_eq!((after.kind, after.rows.as_slice()), (written.kind, &[vec![8.0, 1.0], vec![2.0, 7.0]][..]), "{name}"); + // Each series keeps one fill and the thin white stroke on its marks and its swatch. + for i in 0..2 { + let marks = marks_of(&again, found[0], i); + let white = Paint::solid(vectorcraft_color::Color::WHITE); + assert!(marks.len() > 1 && marks.iter().all(|m| *m == marks[0] && (&m.1, m.2) == (&white, 0.25)), "{name} series {i}: {marks:?}"); + } + } } /// A graph opened from a `.ai` keeps the bounds of its art without type, so moving one of its labels on its own diff --git a/crates/engine/src/cmd/inline.rs b/crates/engine/src/cmd/inline.rs index db3e929952..d2df2ada51 100644 --- a/crates/engine/src/cmd/inline.rs +++ b/crates/engine/src/cmd/inline.rs @@ -6,6 +6,7 @@ use vectorcraft_doc::text::INLINE_MAX_SCALE; use vectorcraft_doc::{Document, InlineArt, NodeId, NodeKind, TextRun}; use vectorcraft_text::edit; +use super::brushsym::current_symbol; use super::typecmd::refresh_bounds; use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_doc, id_param, str_param}; @@ -97,13 +98,3 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result<Value> { } Ok(json!({"id": id.0, "caret": caret})) } - -/// The Symbols panel's current symbol, else the first one. -fn current_symbol(d: &Document) -> Option<String> { - d.unknown - .get("currentSymbol") - .and_then(Value::as_str) - .filter(|n| d.symbols.iter().any(|s| s.name == *n)) - .map(str::to_string) - .or_else(|| d.symbols.first().map(|s| s.name.clone())) -} diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index b3fc65e8fc..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 @@ -698,6 +698,20 @@ fn clip_shape((frame, room): Clip) -> PathData { shapes::rectangle(Rect::new(0.0, 0.0, room.0, room.1)).transformed(frame) } +/// The clipping path an image's file draws it through, with the fill rule its clip group takes: +/// a DCS file's (nonzero) or a PSD or PSB file's (even-odd). +type FileClip = (PathData, FillRule); + +/// The clipping path the file of image content `blob` draws it through, in its pixel space, as it +/// was kept when the file was read: a DCS file's ([`ImageBlob::separated_clip`]) or a PSD or PSB +/// file's ([`fileio::png_clip`]). +fn file_clip(blob: &ImageBlob) -> Option<FileClip> { + if let Some(path) = blob.separated_clip() { + return Some((path, FillRule::NonZero)); + } + (blob.mime == "image/png").then(|| fileio::png_clip(&blob.bytes)).flatten().map(|path| (path, FillRule::EvenOdd)) +} + /// What happens to the clip of an object a link update remakes. enum ClipTo { /// It stays as it is. @@ -705,25 +719,25 @@ enum ClipTo { /// It is clipped to this path (Placement Options' clip): the clipping path of the clip group /// holding just it changes, else it goes into a new clip group. Path(PathData), - /// It is clipped to this path, the clipping path its DCS file draws it through: as [`ClipTo::Path`], - /// except that a plain group holding just it (as [`ClipTo::Off`] leaves one) becomes a clip group - /// again. - File(PathData), + /// It is clipped to this path, the clipping path its file draws it through, under its fill + /// rule: as [`ClipTo::Path`], except that a plain group holding just it (as [`ClipTo::Off`] + /// leaves one) becomes a clip group again. + File(FileClip), /// It goes into a new clip group of this path, inside the clip group that holds it. - Nest(PathData), - /// Placement Options clip it to `placement` while its DCS file draws it through `file`: it is + Nest(FileClip), + /// Placement Options clip it to `placement` while its file draws it through `file`: it is /// clipped to `file` as [`ClipTo::File`] clips it, and the clip group holding it is clipped to /// `placement` as [`ClipTo::Path`] clips an object. With no `file` (the new file lacks the /// clipping path of the clip group holding it), that group stays as [`ClipTo::Off`] leaves it, /// clipped to `placement`. - Both { file: Option<PathData>, placement: PathData }, - /// Placement Options clip it to `placement` while its DCS file draws it through `file`, and the + Both { file: Option<FileClip>, placement: PathData }, + /// Placement Options clip it to `placement` while its file draws it through `file`, and the /// clip group holding just it is not its old file's: that clip group's clipping path becomes /// `placement`, and it goes into a new clip group of `file` inside it. - BothInside { file: PathData, placement: PathData }, - /// The clipping path of the clip group holding just it goes (a DCS file's clipping path that - /// its new file lacks): the group stays as a plain group of it, with its id, name, visibility - /// and transparency. + BothInside { file: FileClip, placement: PathData }, + /// The clipping path of the clip group holding just it goes (its old file's clipping path, + /// which its new file lacks): the group stays as a plain group of it, with its id, name, + /// visibility and transparency. Off, } @@ -756,25 +770,25 @@ fn same_path(a: &PathData, b: &PathData) -> bool { } /// The clip an image placed with `old_xf` takes when it shows `img`, read from a file, placed with -/// `new_xf`: Placement Options' clip `clip` when they clip it, and the clipping path a DCS file -/// draws `img` through, the file's clip group inside the placement's. When neither clips it, a clip -/// group holding just it whose clipping path `held` is its old DCS file's (`old_clip`, in the old -/// pixels, under the nonzero rule its clip groups get) goes. +/// `new_xf`: Placement Options' clip `clip` when they clip it, and the clipping path the file +/// (DCS, PSD or PSB) draws `img` through, the file's clip group inside the placement's. When +/// neither clips it, a clip group holding just it whose clipping path `held` is its old file's +/// (`old_clip`, in the old pixels, under the fill rule its clip groups get) goes. fn clip_to( old_xf: Affine, - old_clip: Option<&PathData>, + old_clip: Option<&FileClip>, clip: Option<Clip>, img: &RasterImage, new_xf: Affine, held: Option<(&PathData, FillRule)>, ) -> ClipTo { - // Whether the clip group holding just the image is the old DCS file's: a clipping path whose - // fill rule was changed in the document is not. + // Whether the clip group holding just the image is the old file's: a clipping path whose fill + // rule was changed in the document is not. let file_held = match (old_clip, held) { - (Some(old), Some((held, rule))) => rule == FillRule::NonZero && same_path(&old.transformed(old_xf), held), + (Some((old, old_rule)), Some((held, rule))) => rule == *old_rule && same_path(&old.transformed(old_xf), held), _ => false, }; - let file = img.clip.as_ref().map(|path| path.transformed(new_xf)); + let file = img.clip.as_ref().map(|(path, rule)| (path.transformed(new_xf), *rule)); if let Some(clip) = clip { let placement = clip_shape(clip); return match file { @@ -831,7 +845,7 @@ impl Nested<'_> { fn root(&mut self, n: &mut Arc<Node>) { if !(self.pick)(n) { if let Some(placement) = self.update(n, true) { - *n = Arc::new(self.clip_group(Arc::clone(n), placement)); + *n = Arc::new(self.clip_group(Arc::clone(n), (placement, FillRule::NonZero))); } return; } @@ -839,7 +853,8 @@ impl Nested<'_> { let mut new = Arc::new(new); let _ = self.update(&mut new, true); *n = match clip { - ClipTo::Path(path) | ClipTo::File(path) | ClipTo::Nest(path) => Arc::new(self.clip_group(new, path)), + ClipTo::Path(path) => Arc::new(self.clip_group(new, (path, FillRule::NonZero))), + ClipTo::File(file) | ClipTo::Nest(file) => Arc::new(self.clip_group(new, file)), ClipTo::Both { file, placement } => self.clip_both(new, file, placement), ClipTo::BothInside { file, placement } => self.clip_both(new, Some(file), placement), ClipTo::Keep | ClipTo::Off => new, @@ -848,8 +863,8 @@ impl Nested<'_> { /// `n` (outside the layer tree when `nested`) with the picked objects under it remade; it stays /// the same node when none is there, and only the nodes on the way to one are copied. The - /// result is Placement Options' clip that `n` itself, now the clip group of a DCS file's - /// clipping path holding a picked object (or the plain group [`ClipTo::Off`] leaves), takes: + /// result is Placement Options' clip that `n` itself, now the clip group of a file's clipping + /// path holding a picked object (or the plain group [`ClipTo::Off`] leaves), takes: /// the clipping path of the clip group holding just `n` becomes it, else `n` goes into a new /// clip group of it. #[must_use] @@ -880,8 +895,8 @@ impl Nested<'_> { match (self.update(&mut new, nested), clip_path) { (None, _) if Arc::ptr_eq(&new, c) => {} (None, _) => slots.push((i, new)), - (Some(placement), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, placement)), (1, new)]), - (Some(placement), _) => slots.push((i, Arc::new(self.clip_group(new, placement)))), + (Some(placement), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, placement, None)), (1, new)]), + (Some(placement), _) => slots.push((i, Arc::new(self.clip_group(new, (placement, FillRule::NonZero))))), } continue; } @@ -894,17 +909,22 @@ impl Nested<'_> { let _ = self.update(&mut new, true); match (clip, clip_path) { (ClipTo::Keep, _) => slots.push((i, new)), - (ClipTo::Path(clip) | ClipTo::File(clip), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, clip)), (1, new)]), + (ClipTo::Path(clip), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, clip, None)), (1, new)]), + (ClipTo::File((clip, rule)), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, clip, Some(rule))), (1, new)]), (ClipTo::File(clip), None) if plain => reclipped = Some((clip, new)), - (ClipTo::Path(clip) | ClipTo::File(clip) | ClipTo::Nest(clip), _) => { + (ClipTo::Path(clip), _) => { + let group = self.clip_group(new, (clip, FillRule::NonZero)); + slots.push((i, Arc::new(group))); + } + (ClipTo::File(clip) | ClipTo::Nest(clip), _) => { let group = self.clip_group(new, clip); slots.push((i, Arc::new(group))); } (ClipTo::Off, Some(_)) if i == 1 => declipped = Some(new), (ClipTo::Off, _) => slots.push((i, new)), // The file's clip group stays `n`, and the placement's clip goes around it. - (ClipTo::Both { file: Some(file), placement }, Some(path)) if i == 1 => { - slots.extend([(0, with_clip(path, file)), (1, new)]); + (ClipTo::Both { file: Some((file, rule)), placement }, Some(path)) if i == 1 => { + slots.extend([(0, with_clip(path, file, Some(rule))), (1, new)]); around = Some(placement); } (ClipTo::Both { file: Some(file), placement }, None) if plain => { @@ -917,7 +937,7 @@ impl Nested<'_> { } (ClipTo::BothInside { file, placement }, Some(path)) if i == 1 => { let group = self.clip_group(new, file); - slots.extend([(0, with_clip(path, placement)), (1, Arc::new(group))]); + slots.extend([(0, with_clip(path, placement, None)), (1, Arc::new(group))]); } (ClipTo::Both { file, placement }, _) => slots.push((i, self.clip_both(new, file, placement))), (ClipTo::BothInside { file, placement }, _) => slots.push((i, self.clip_both(new, Some(file), placement))), @@ -958,27 +978,28 @@ impl Nested<'_> { /// A clip group of `placement` holding `object`, inside a clip group of `file` when there is a /// `file` ([`ClipTo::Both`] for an object no clip group holds yet). - fn clip_both(&mut self, object: Arc<Node>, file: Option<PathData>, placement: PathData) -> Arc<Node> { + fn clip_both(&mut self, object: Arc<Node>, file: Option<FileClip>, placement: PathData) -> Arc<Node> { let object = match file { Some(file) => Arc::new(self.clip_group(object, file)), None => object, }; - Arc::new(self.clip_group(object, placement)) + Arc::new(self.clip_group(object, (placement, FillRule::NonZero))) } - /// A clip group of `object` clipped to `clip`, as [`clip_image_to`] makes one in the layers. - fn clip_group(&mut self, object: Arc<Node>, clip: PathData) -> Node { + /// A clip group of `object` clipped to `clip` under its fill rule, as [`new_clip_group`] makes + /// one in the layers. + fn clip_group(&mut self, object: Arc<Node>, clip: FileClip) -> Node { let path = self.clipping_path(clip); let group_id = NodeId(self.next); self.next += 1; Node::new(group_id, NodeKind::Group { children: vec![Arc::new(path), object], clip: true }) } - /// A clipping path of `clip`, with the next node id. - fn clipping_path(&mut self, clip: PathData) -> Node { + /// A clipping path of `clip` under its fill rule, with the next node id. + fn clipping_path(&mut self, (clip, rule): FileClip) -> Node { let id = NodeId(self.next); self.next += 1; - clipping_path(id, clip) + clipping_path(id, clip, rule) } } @@ -1082,9 +1103,9 @@ fn placed_xf(xf: Affine, old: (f64, f64), old_pt: (f64, f64), new: (f64, f64), n (frame * at * Affine::scale_non_uniform(size.0 / nw, size.1 / nh), (o.clip && over).then_some((frame, room))) } -/// The clipping path of the clip group of `d` holding just object `id` becomes `path`; false when -/// no such clip group holds it. -fn set_clip_path(d: &mut Document, id: NodeId, path: PathData) -> bool { +/// The clipping path of the clip group of `d` holding just object `id` becomes `path`, under fill +/// rule `rule` when one is given; false when no such clip group holds it. +fn set_clip_path(d: &mut Document, id: NodeId, path: PathData, rule: Option<FillRule>) -> bool { let clip_path = d.parent_of(id).and_then(|p| match &d.node(p)?.kind { NodeKind::Group { children, clip: true } => match &children[..] { [c, im] if im.id == id && matches!(c.kind, NodeKind::Path { clipping: true, .. }) => Some(c.id), @@ -1093,8 +1114,9 @@ fn set_clip_path(d: &mut Document, id: NodeId, path: PathData) -> bool { _ => None, }); let Some(c) = clip_path else { return false }; - if let Some(Node { kind: NodeKind::Path { path: p, .. }, .. }) = d.node_mut(c) { + if let Some(Node { kind: NodeKind::Path { path: p, rule: r, .. }, .. }) = d.node_mut(c) { *p = path; + *r = rule.unwrap_or(*r); } true } @@ -1108,25 +1130,25 @@ fn clip_image(d: &mut Document, id: NodeId, clip: Clip) -> Result<()> { /// Clip object `id` of `d` to `path`: the clipping path of the clip group holding just it changes, /// else it goes into a new clip group. fn clip_image_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> { - if set_clip_path(d, id, path.clone()) { + if set_clip_path(d, id, path.clone(), None) { return Ok(()); } - new_clip_group(d, id, path) + new_clip_group(d, id, (path, FillRule::NonZero)) } -/// Clip object `id` of `d` to `path`, the clipping path its DCS file draws it through: the clipping -/// path of the clip group holding just it changes, a plain group holding just it (as [`unclip`] -/// leaves one) becomes a clip group again, else it goes into a new clip group. -fn clip_file_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> { - if set_clip_path(d, id, path.clone()) { +/// Clip object `id` of `d` to `path`, the clipping path its file draws it through, under its fill +/// rule: the clipping path of the clip group holding just it changes, a plain group holding just it +/// (as [`unclip`] leaves one) becomes a clip group again, else it goes into a new clip group. +fn clip_file_to(d: &mut Document, id: NodeId, (path, rule): FileClip) -> Result<()> { + if set_clip_path(d, id, path.clone(), Some(rule)) { return Ok(()); } let plain = d.parent_of(id).filter(|g| match d.node(*g).map(|n| &n.kind) { Some(NodeKind::Group { children, clip: false }) => matches!(&children[..], [o] if o.id == id), _ => false, }); - let Some(g) = plain else { return new_clip_group(d, id, path) }; - let clip = clipping_path(d.alloc_id(), path); + let Some(g) = plain else { return new_clip_group(d, id, (path, rule)) }; + let clip = clipping_path(d.alloc_id(), path, rule); d.insert(Some(g), 0, clip)?; if let Some(Node { kind: NodeKind::Group { clip, .. }, .. }) = d.node_mut(g) { *clip = true; @@ -1134,30 +1156,33 @@ fn clip_file_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> { Ok(()) } -/// Clipping path `path` (a node) with its path changed to `clip`. -fn with_clip(path: &Node, clip: PathData) -> Arc<Node> { +/// Clipping path `path` (a node) with its path changed to `clip`, and its fill rule to `rule` when +/// one is given. +fn with_clip(path: &Node, clip: PathData, rule: Option<FillRule>) -> Arc<Node> { let mut path = Node::clone(path); - if let NodeKind::Path { path: p, .. } = &mut path.kind { + if let NodeKind::Path { path: p, rule: r, .. } = &mut path.kind { *p = clip; + *r = rule.unwrap_or(*r); } Arc::new(path) } -/// A clipping path `id` of `path`, unpainted. -fn clipping_path(id: NodeId, path: PathData) -> Node { +/// A clipping path `id` of `path` under fill rule `rule`, unpainted. +fn clipping_path(id: NodeId, path: PathData, rule: FillRule) -> Node { let none = vectorcraft_color::Paint::None; let mut clip = Node::path(id, path, Appearance::basic(none.clone(), none, 0.0)); - if let NodeKind::Path { clipping, .. } = &mut clip.kind { + if let NodeKind::Path { clipping, rule: r, .. } = &mut clip.kind { *clipping = true; + *r = rule; } clip } -/// Put object `id` of `d` into a new clip group of `path`, where it is. -fn new_clip_group(d: &mut Document, id: NodeId, path: PathData) -> Result<()> { +/// Put object `id` of `d` into a new clip group of `path`, under its fill rule, where it is. +fn new_clip_group(d: &mut Document, id: NodeId, (path, rule): FileClip) -> Result<()> { let (par, index, _) = d.position(id).ok_or(EngineError::NoNode(id))?; let image = d.remove(id)?; - let clip = clipping_path(d.alloc_id(), path); + let clip = clipping_path(d.alloc_id(), path, rule); let group = Node::new(d.alloc_id(), NodeKind::Group { children: vec![std::sync::Arc::new(clip), image], clip: true }); d.insert(par, index, group)?; Ok(()) @@ -1186,15 +1211,15 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio let nested = nested_ids(d, ids); if also.is_some() || !nested.is_empty() { let pick = |n: &Node| matches!(n.kind, NodeKind::Image(_)) && (nested.contains(&n.id) || also.is_some_and(|also| shows(n, also, false))); - // The resolution of each content the images picked show, and the clipping path its DCS file + // The resolution of each content the images picked show, and the clipping path its file // drew it through, looked up once each. - let mut old: BTreeMap<String, ((f64, f64), Option<PathData>)> = BTreeMap::new(); + let mut old: BTreeMap<String, ((f64, f64), Option<FileClip>)> = BTreeMap::new(); d.visit_stored(|n, _| { if let NodeKind::Image(im) = &n.kind && pick(n) && !old.contains_key(&im.key) { - old.insert(im.key.clone(), (file_pt(d, &im.key), d.images.get(&im.key).and_then(ImageBlob::separated_clip))); + old.insert(im.key.clone(), (file_pt(d, &im.key), d.images.get(&im.key).and_then(file_clip))); } }); let mut make = |n: &Node, held: Option<(&PathData, FillRule)>| { @@ -1220,8 +1245,9 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement }; let size = |w: u32, h: u32| (w as f64, h as f64); let (xf, clip) = placed_xf(im.xf, size(im.width, im.height), file_pt(d, &im.key), size(img.width, img.height), new_pt, o); - // Placement Options' clip, else a DCS file's clipping path, read again with its plates. - let old_clip = d.images.get(&im.key).and_then(ImageBlob::separated_clip); + // Placement Options' clip, else the clipping path of a DCS file (read again with its + // plates) or of a PSD or PSB file. + let old_clip = d.images.get(&im.key).and_then(file_clip); clips.push((*id, clip_to(im.xf, old_clip.as_ref(), clip, &img, xf, clip_path_of(d, *id)))); if let Some(n) = d.node_mut(*id) && let NodeKind::Image(im) = &mut n.kind @@ -1235,8 +1261,8 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio clips.into_iter().try_for_each(|(id, clip)| match clip { ClipTo::Keep => Ok(()), ClipTo::Path(path) => clip_image_to(d, id, path), - ClipTo::File(path) => clip_file_to(d, id, path), - ClipTo::Nest(path) => new_clip_group(d, id, path), + ClipTo::File(file) => clip_file_to(d, id, file), + ClipTo::Nest(file) => new_clip_group(d, id, file), ClipTo::Off => unclip(d, id), ClipTo::Both { file, placement } => { match file { @@ -1314,27 +1340,54 @@ pub(crate) fn file_hidden(path: &str, doc_path: Option<&str>) -> bool { /// gray or missing names none: the SVG writes gray pixels colorized and leaves out an image /// without pixels. The images of the art the SVG writes (opacity masks included) and of the /// symbols, patterns and brushes that art uses, as Copy follows them, are checked: the SVG writes -/// no other resource. Hidden layers and objects are written only with -/// SVG Options › hidden layers kept (`hidden`), and template layers never ([`svg_written`]). -/// Always `false` without read roots in force. -pub(crate) fn svg_names_hidden_image(d: &Document, base: LinkBase, link: bool, hidden: bool) -> bool { - if crate::file_access::current().is_none() || !names_hidden_image(d, base, link) { +/// no other resource. A placed document's images are those of the art the SVG draws for it. Hidden +/// layers and objects are written only with SVG Options › hidden layers kept (`hidden`), in the +/// layers and in the symbols, patterns and graph designs alike, and template layers never. SVG Tiny +/// 1.2 (`tiny`) writes no opacity masks ([`svg_written`]). Always `false` without read roots in +/// force. +pub(crate) fn svg_names_hidden_image(d: &Document, base: LinkBase, link: bool, hidden: bool, tiny: bool) -> bool { + if crate::file_access::current().is_none() { return false; } - let art = d.layers.iter().filter_map(|l| svg_written(l, hidden)).collect(); - names_hidden_image(&super::clipboard::Clipboard::gather(d, art).to_document(), base, link) + if !d.has_placed() && !names_hidden_image(d, base, link) { + return false; + } + // The writer draws placed documents' art with the pixels their files hold. + let placed = d.with_placed_art(); + let d = &*placed; + let art = d.layers.iter().filter_map(|l| svg_written(d, l, hidden, tiny)).collect(); + let mut out = super::clipboard::Clipboard::gather(d, art).to_document(); + let written = |n: &std::sync::Arc<Node>| { + let empty = || Node::new(n.id, NodeKind::Group { children: vec![], clip: false }); + std::sync::Arc::new(svg_written(d, n, hidden, tiny).unwrap_or_else(empty)) + }; + for s in &mut out.symbols { + s.art = written(&s.art); + } + for g in &mut out.graph_designs { + g.art = written(&g.art); + } + for p in &mut out.patterns { + p.art = p.art.iter().filter_map(|n| svg_written(d, n, hidden, tiny)).map(std::sync::Arc::new).collect(); + } + names_hidden_image(&out, base, link) } -/// `n` as the SVG writer writes it, or `None` when it writes none of it: a hidden layer or object -/// is left out unless `hidden`, a template layer's art always, and a disabled opacity mask's art. -/// Only layers and groups lose members; other objects keep theirs as they are. -fn svg_written(n: &Node, hidden: bool) -> Option<Node> { +/// `n` (an object of `d`) as the SVG writer writes it, or `None` when it writes none of it: a +/// hidden layer or object is left out unless `hidden`, a template layer's art always, a disabled +/// opacity mask's art, and with SVG Tiny 1.2 (`tiny`) every opacity mask's art. A placed document +/// is the art the writer draws for it. Only layers and groups lose members; other objects keep +/// theirs as they are. +fn svg_written(d: &Document, n: &Node, hidden: bool, tiny: bool) -> Option<Node> { if !(n.visible || hidden) { return None; } + if matches!(n.kind, NodeKind::PlacedDocument(_)) { + return svg_written(d, &vectorcraft_render::effects::expand_live_deep(Some(d), n), hidden, tiny); + } let mut n = n.clone(); - let mask = n.extras().mask.as_deref().filter(|m| !m.disabled).and_then(|m| { - let art = svg_written(&m.art, hidden)?; + let mask = n.extras().mask.as_deref().filter(|m| !m.disabled && !tiny).and_then(|m| { + let art = svg_written(d, &m.art, hidden, tiny)?; Some(Box::new(vectorcraft_doc::OpacityMask { art: std::sync::Arc::new(art), ..m.clone() })) }); if n.extras().mask.is_some() { @@ -1343,7 +1396,7 @@ fn svg_written(n: &Node, hidden: bool) -> Option<Node> { match &mut n.kind { NodeKind::Layer { template: true, children, .. } => children.clear(), NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => { - *children = children.iter().filter_map(|c| svg_written(c, hidden)).map(std::sync::Arc::new).collect(); + *children = children.iter().filter_map(|c| svg_written(d, c, hidden, tiny)).map(std::sync::Arc::new).collect(); } _ => {} } @@ -2586,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<Vec<u8>, 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<u8> = 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<Value> { diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 1ab0e0b670..2a073ab62a 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -133,7 +133,7 @@ pub fn specs() -> Vec<CommandSpec> { "Crop Image", ["Object"], None, - "{rect?: [x, y, width, height] | trim?: true (to the pixels that aren't fully transparent, pixel for pixel; an image with none to cut is left as it is, trimmed: false)} crop the selected image (default: to the artboard it sits on) → {id, width, height, trimmed? (with trim), warning? (without trim: the image couldn't be decoded, as object.rasterize says)}", + "{rect?: [x, y, width, height] | trim?: true (to the pixels that aren't fully transparent, pixel for pixel; an image with none to cut is left as it is, trimmed: false), ppi?: number (without trim: the cropped image's resolution in pixels per inch, resampled from the cut pixels; 1 to 2400, at most the image's own, or 300 for a linked image; default the image's own; a rect over the whole image with a new ppi only resamples it)} crop the selected image (default: to the artboard it sits on) → {id, width, height, trimmed? (with trim), warning? (without trim: the image couldn't be decoded, as object.rasterize says)}", has_image, crop_image ), @@ -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))) } @@ -967,10 +973,10 @@ fn polygon_path(pts: &[Point]) -> PathData { PathData::single(vectorcraft_geom::SubPath::new(pts.iter().map(|p| Anchor::corner(*p)).collect(), true)) } -/// The part of an image under `r` (in document space) copied out of its pixels, as PNG bytes, with its size and -/// placement. `None` when the image can't be cut that way (turned or skewed, CMYK, pixels that can't be read, or -/// `r` not on the pixel grid), so the caller draws it instead. -fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Option<(Vec<u8>, u32, u32, Affine)> { +/// The part of an image under `r` (in document space) copied out of its pixels, with its placement. `None` when +/// the image can't be cut that way (turned or skewed, CMYK, pixels that can't be read, or `r` not on the pixel +/// grid), so the caller draws it instead. +fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Option<(image::RgbaImage, Affine)> { let blob = doc.images.get(&im.key)?; let [a, b, c, d, _, _] = im.xf.as_coeffs(); if blob.is_cmyk() || b.abs() > 1e-9 || c.abs() > 1e-9 || a.abs() < 1e-9 || d.abs() < 1e-9 { @@ -996,9 +1002,92 @@ fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Op return None; } 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).ok()?; - Some((png, x1 - x0, y1 - y0, im.xf * Affine::translate((f64::from(x0), f64::from(y0))))) + Some((cut, im.xf * Affine::translate((f64::from(x0), f64::from(y0))))) +} + +/// Crop Image's `ppi`: the resolution asked for, in pixels per point, and whether it keeps the image's pixels as +/// they are (its own, with square pixels); `None` for the image's own. Refuses a resolution that isn't a positive +/// number or is above what the image allows: its own, or 300 ppi for a linked image, within 1 to 2400 ppi as +/// Rasterize's. +fn crop_resolution(p: &Value, im: &ImageObject) -> Result<Option<(f64, bool)>> { + const C: &str = "object.cropImage"; + let Some(ppi) = p.get("ppi").filter(|v| !v.is_null()) else { return Ok(None) }; + let ppi = ppi.as_f64().filter(|v| v.is_finite() && *v > 0.0).ok_or_else(|| bad(C, format!("ppi must be a positive number, not {ppi}")))?; + if !(1.0..=2400.0).contains(&ppi) { + return Err(bad(C, "ppi must be between 1 and 2400")); + } + let (_, max) = vectorcraft_tools::cropimage::image_ppi(im); + if ppi > max + 1e-6 { + let max = (max * 100.0 + 1e-6).floor() / 100.0; + return Err(bad(C, format!("ppi can't be more than {max} for this image"))); + } + // An image whose pixels are not square is resampled on both sides, even at its denser side's resolution. + Ok(Some((ppi / 72.0, vectorcraft_tools::cropimage::keeps_resolution(im, ppi, 1e-6)))) +} + +/// A `w` × `h` image resampled at a resolution asked for, held to the size a drawing may have ([`MAX_PIXELS`], and +/// no side past the renderer's). +fn check_crop_size(w: f64, h: f64) -> Result<()> { + let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE); + if w * h > MAX_PIXELS || w > side || h > side { + let (w, h) = (w as u64, h as u64); + return Err(bad("object.cropImage", format!("an image of {w} × {h} pixels is too large to draw"))); + } + Ok(()) +} + +/// `img` resampled to `w` × `h` with its colors weighted by their alpha, so the color of a fully +/// transparent pixel does not show at the edges of what is opaque. The weighted colors are held in +/// 16 bits a channel until the end, so a nearly transparent pixel keeps its color. An error when +/// the working copies would not fit ([`check_resample_size`]). +fn resize_premultiplied(img: &image::RgbaImage, w: u32, h: u32) -> Result<image::RgbaImage> { + check_resample_size(img.width(), img.height(), w, h)?; + let mut pre = image::ImageBuffer::<image::Rgba<u16>, Vec<u16>>::new(img.width(), img.height()); + for (d, s) in pre.pixels_mut().zip(img.pixels()) { + let a = u32::from(s[3]); + for (dc, sc) in d.0[..3].iter_mut().zip(&s.0[..3]) { + // c × 257 × a / 255, rounded: the color scaled to 16 bits and weighted. + *dc = ((u32::from(*sc) * 257 * a + 127) / 255) as u16; + } + d.0[3] = (a * 257) as u16; + } + let out = image::imageops::resize(&pre, w, h, image::imageops::FilterType::Lanczos3); + let mut res = image::RgbaImage::new(out.width(), out.height()); + for (d, s) in res.pixels_mut().zip(out.pixels()) { + let a = u64::from(s[3]); + for (dc, sc) in d.0[..3].iter_mut().zip(&s.0[..3]) { + // c × 65535 / a back to 8 bits (÷ 257), rounded: c × 255 / a. + *dc = (u64::from(*sc) * 255 + a / 2).checked_div(a).unwrap_or(0).min(255) as u8; + } + d.0[3] = ((a + 128) / 257).min(255) as u8; + } + Ok(res) +} + +/// Whether resampling a `sw` × `sh` image to `w` × `h` fits in [`MAX_RASTER_ALLOC`]: the source and +/// its weighted 16-bit copy (12 bytes a pixel), the resampler's float rows between its two passes +/// (16 bytes a pixel, `sw` × `h`) and the 16-bit and 8-bit results (12 bytes a pixel of `w` × `h`). +pub(crate) fn check_resample_size(sw: u32, sh: u32, w: u32, h: u32) -> Result<()> { + let (sw, sh, w, h) = (u64::from(sw), u64::from(sh), u64::from(w), u64::from(h)); + let bytes = (sw * sh).saturating_mul(12).saturating_add((sw * h).saturating_mul(16)).saturating_add((w * h).saturating_mul(12)); + if bytes > crate::cmd::fileio::MAX_RASTER_ALLOC { + return Err(bad("object.cropImage", format!("an image of {sw} × {sh} pixels is too large to resample"))); + } + Ok(()) +} + +/// `img` as PNG bytes. +fn encode_png(img: &image::RgbaImage) -> Result<Vec<u8>> { + 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<Value> { @@ -1014,9 +1103,15 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> { let node = st.doc.node(id).cloned().ok_or(EngineError::NoNode(id))?; let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) }; if switch_or(p, "trim", false, C)? { + if p.get("ppi").is_some_and(|v| !v.is_null()) { + return Err(bad(C, "trim keeps the image's pixels as they are: leave out ppi")); + } return trim_image(s, id, (**im).clone()); } let ib = node.geometric_bounds().ok_or_else(|| bad(C, "image has no bounds"))?; + let asked = crop_resolution(p, im)?; + // The resolution the image's pixels are resampled to when they are cut straight. + let target = asked.and_then(|(t, keeps)| (!keeps).then_some(t)); let rect = match p.get("rect").filter(|v| !v.is_null()) { Some(Value::Array(a)) if a.len() == 4 => { let v: Vec<f64> = a.iter().filter_map(Value::as_f64).collect(); @@ -1038,16 +1133,49 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> { if r.width() <= 0.0 || r.height() <= 0.0 { return Err(bad(C, "crop rectangle doesn't overlap the image")); } - if (r.x0 - ib.x0).abs() < 1e-6 && (r.y0 - ib.y0).abs() < 1e-6 && (r.x1 - ib.x1).abs() < 1e-6 && (r.y1 - ib.y1).abs() < 1e-6 { + // A box over the whole image still resamples it to a new resolution. + let whole = (r.x0 - ib.x0).abs() < 1e-6 && (r.y0 - ib.y0).abs() < 1e-6 && (r.x1 - ib.x1).abs() < 1e-6 && (r.y1 - ib.y1).abs() < 1e-6; + // A turned or skewed image is drawn, so a resolution asked for, even its own, still makes a new image. + let [_, xb, xc, _, _, _] = im.xf.as_coeffs(); + let turned = xb.abs() > 1e-9 || xc.abs() > 1e-9; + if whole && target.is_none() && (asked.is_none() || !turned) { return Err(bad(C, "nothing to crop")); } - // A plain, axis-aligned raster is cut straight from its pixels, so nothing is resampled. - if let Some((png, cw, ch, xf)) = crop_pixels(&st.doc, im, r) { - put_pixels(s, id, png, cw, ch, xf)?; + if let Some(t) = target { + check_crop_size((r.width() * t).round().max(1.0), (r.height() * t).round().max(1.0))?; + } + // A plain, axis-aligned raster is cut straight from its pixels, so nothing is resampled unless a + // resolution is asked for. + if let Some((cut, xf)) = crop_pixels(&st.doc, im, r) { + let (cut, xf) = match target { + Some(t) => { + let (cw, ch) = cut.dimensions(); + let (w, h) = ((r.width() * t).round().max(1.0) as u32, (r.height() * t).round().max(1.0) as u32); + let resized = resize_premultiplied(&cut, w, h)?; + (resized, xf * Affine::scale_non_uniform(f64::from(cw) / f64::from(w), f64::from(ch) / f64::from(h))) + } + None => (cut, xf), + }; + let (cw, ch) = cut.dimensions(); + put_pixels(s, id, encode_png(&cut)?, cw, ch, xf)?; return Ok(json!({ "id": id.0, "width": cw, "height": ch })); } - // Keep the image's pixel density. - let scale = (im.width as f64 / ib.width().max(1e-9)).max(im.height as f64 / ib.height().max(1e-9)); + // A drawn crop is made at a resolution asked for even when it is the image's own: the box of a + // turned or skewed image holds fewer of its pixels a point than the image does. + let target = asked.map(|(t, _)| t); + if let Some(t) = target { + check_crop_size((r.width() * t).round().max(1.0), (r.height() * t).round().max(1.0))?; + } + // Drawn at the image's pixel density, or for a resolution asked for at up to twice that (no more + // than the image's own, measured on its pixel grid however it is turned, nor past the size a + // drawing may have), and resampled to it. + let native = (im.width as f64 / ib.width().max(1e-9)).max(im.height as f64 / ib.height().max(1e-9)); + let scale = target.map_or(native, |t| { + let own = native.max(vectorcraft_tools::cropimage::image_ppi(im).0 / 72.0); + let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE); + let budget = (MAX_PIXELS / (r.width() * r.height()).max(1e-9)).sqrt().min(side / r.width().max(1e-9)).min(side / r.height().max(1e-9)); + (2.0 * t).min(own).min(budget).max(t.min(own)) + }); let mut bare = node.clone(); bare.opacity = 1.0; bare.blend = Default::default(); @@ -1058,23 +1186,41 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> { if let Some(e) = bare.extras_if_any() { e.color_mask = None; } + let (dw, dh) = ((r.width() * scale).round().max(1.0), (r.height() * scale).round().max(1.0)); + let region = Rect::new(r.x0, r.y0, r.x0 + dw / scale, r.y0 + dh / scale); + // At a resolution asked for, the drawing is fitted to the box below: the image is stretched + // about the box's corner so the box fills the whole pixels drawn, and nothing past it is drawn. + if target.is_some() + && let NodeKind::Image(bi) = &mut bare.kind + { + let o = r.origin().to_vec2(); + bi.xf = Affine::translate(o) + * Affine::scale_non_uniform(region.width() / r.width(), region.height() / r.height()) + * Affine::translate(-o) + * bi.xf; + } let tmp = isolated_doc(&st.doc, vec![bare]); - let region = Rect::new(r.x0, r.y0, r.x0 + (r.width() * scale).round().max(1.0) / scale, r.y0 + (r.height() * scale).round().max(1.0) / scale); let (png, w, h, warning) = render_png(&tmp, region, scale, &RasterExportOptions::default().render_options(RasterFormat::Png), RasterColorModel::Document)?; + // At a resolution asked for, the drawing is resampled to the box's size at that resolution and + // fitted to the box, so the image keeps its size. + let (png, w, h, xf) = match target { + Some(t) => { + let drawn = image::load_from_memory(&png).map_err(|e| bad(C, e.to_string()))?.into_rgba8(); + // Only the decoded pixels are held while they are resampled. + drop(png); + let (tw, th) = ((r.width() * t).round().max(1.0) as u32, (r.height() * t).round().max(1.0) as u32); + let resized = resize_premultiplied(&drawn, tw, th)?; + let xf = Affine::translate(r.origin().to_vec2()) * Affine::scale_non_uniform(r.width() / f64::from(tw), r.height() / f64::from(th)); + (encode_png(&resized)?, tw, th, xf) + } + None => (png, w, h, Affine::translate(region.origin().to_vec2()) * Affine::scale(1.0 / scale)), + }; s.edit("Crop Image", |d, _| { let key = unique_key(d, "crop"); d.images.insert(key.clone(), vectorcraft_doc::ImageBlob::new("image/png", png)); if let Some(n) = d.node_mut(id) { - n.kind = NodeKind::Image(Box::new(ImageObject { - key, - width: w, - height: h, - xf: Affine::translate(region.origin().to_vec2()) * Affine::scale(1.0 / scale), - link: None, - placement: Default::default(), - pixels: None, - })); + n.kind = NodeKind::Image(Box::new(ImageObject { key, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None })); } Ok(()) })?; @@ -1088,22 +1234,24 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> { /// The image's pixels as RGBA, held to the allowance opening a raster has. fn decode_rgba(c: &str, blob: &vectorcraft_doc::ImageBlob) -> Result<image::RgbaImage> { // 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 @@ -1132,9 +1280,12 @@ fn trim_image(s: &mut Session, id: NodeId, im: ImageObject) -> Result<Value> { 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/object.rs b/crates/engine/src/cmd/object.rs index 5eee2d3fce..a58f206c84 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -38,7 +38,7 @@ pub use commands::specs; pub(super) use compound::{as_clipping_path, make_clipping_path, release_clip}; pub(crate) use pixelgrid::{ align_new_object, can_align, keep_aligned_in, keep_compound_aligned, keep_pixel_aligned, refresh as refresh_pixel_aligned, resnap, - snap_if_aligned, + snap_if_aligned, snap_symbol_art, }; pub(super) use shape::recut; pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects}; diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 3ea501c775..b0d313fbf5 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -251,7 +251,7 @@ pub fn specs() -> Vec<CommandSpec> { "Object Properties", [], None, - "{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode, and on a series group the group's opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, the graph stores the label's opacity and blend mode for every label of its kind", + "{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode, and on a series group the group's opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's opacity and blend mode for every label or line of its kind", has_doc, set_props ), @@ -260,7 +260,7 @@ pub fn specs() -> Vec<CommandSpec> { "Align", ["Window", "Align"], None, - "{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\" (default: the key object when the selection has one, select.key, else the selection; a key guide, select.key {guide}, stays put and the objects line up on its line: a vertical guide sets where left, center and right go and vertical alignment leaves them, a horizontal one the other way round; aligning to the key, the other selected ruler guides move too: a vertical guide to the key's left edge, center or right edge, a horizontal one to its top, center or bottom; aligning to the artboard moves selected guides to its edges too (#3463), and with only guides selected aligning to the selection moves them to their collective bounds), artboard?: index (0-based; with to: \"artboard\", the artboard to align to; the app passes the active one; default: the artboard under the center of the selection, else the first), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} With anchor points selected (Direct Selection), the points align instead: to their own bounds, to the artboard (#1180), or, aligning to the key with a key anchor (select.key {id, anchor}, the last point a Shift-click added), to the key anchor, which stays put", + "{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\" (default: the key object when the selection has one, select.key, else the selection; a key guide, select.key {guide}, stays put and the objects line up on its line: a vertical guide sets where left, center and right go and vertical alignment leaves them, a horizontal one the other way round; aligning to the key, the other selected ruler guides move too: a vertical guide to the key's left edge, center or right edge, a horizontal one to its top, center or bottom; aligning to the artboard moves selected guides to its edges too (#3463), and with only guides selected aligning to the selection moves them to their collective bounds), artboard?: index (0-based; with to: \"artboard\", the artboard to align to; the app passes the active one; default: the artboard under the center of the selection, else the first), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} With anchor points selected (Direct Selection), the points align instead: to their own bounds, to the artboard (#1180), or, aligning to the key with a key anchor (select.key {id, anchor}), to the key anchor, which stays put", has_selection_or_guides, align ), diff --git a/crates/engine/src/cmd/object/pixelgrid.rs b/crates/engine/src/cmd/object/pixelgrid.rs index 64d47ca0a9..8d2a344ffe 100644 --- a/crates/engine/src/cmd/object/pixelgrid.rs +++ b/crates/engine/src/cmd/object/pixelgrid.rs @@ -1,6 +1,9 @@ //! Transform panel › Align to Pixel Grid: an object's pixel-aligned property, and the snapping that //! keeps the horizontal and vertical segments of a pixel-aligned object on the pixel grid -//! (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html>). +//! (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html>), +//! and Symbol Options › Align to Pixel Grid, which keeps a symbol's instances on the pixel grid. + +use std::collections::HashMap; use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign}; @@ -150,10 +153,250 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) { keep_pixel_aligned(n, Scaling::default()); } } + refresh_symbols(before, doc); +} + +/// How far the linear part of an instance's transform may be from its symbol's natural size, as a +/// fraction of that size, for the instance to count as placed at actual size. +const ACTUAL_SIZE_TOLERANCE: f64 = 1e-9; + +/// After any edit: Symbol Options › Align to Pixel Grid. The art of a pixel-aligned symbol snaps to +/// the pixel grid at the symbol's natural size ([`snap_symbol_art`]) when the symbol becomes +/// pixel-aligned, when its art or natural size changes, and when symbol editing mode for it ends +/// (while it is edited, the art snaps as the editing layer is written back to it). Every instance +/// of such a symbol then goes to whole points ([`snap_instance`]), and so does each instance of a +/// pixel-aligned symbol in an object the edit changed or added, the art of opacity masks included. +/// An instance in another symbol's art, the art on the symbol editing layer included, is placed by +/// that symbol's instances and is left as it is. A document without pixel-aligned symbols is not walked. +fn refresh_symbols(before: &Document, doc: &mut Document) { + let aligned = doc.pixel_aligned_symbols(); + if aligned.is_empty() { + return; + } + let was = before.pixel_aligned_symbols(); + // The symbol whose editing mode this edit ended, if any. + let edited_before = before.symbol_edit.as_ref().map(|e| e.symbol.as_str()); + let edited_now = doc.symbol_edit.as_ref().map(|e| e.symbol.as_str()); + let edit_ended = edited_before.filter(|b| edited_now != Some(*b)).map(str::to_owned); + let mut every = false; + for name in &aligned { + let art_before = before.symbols.iter().find(|s| &s.name == name).map(|s| &s.art); + let art_now = doc.symbols.iter().find(|s| &s.name == name).map(|s| &s.art); + let art_changed = match (art_before, art_now) { + (Some(b), Some(a)) => !Arc::ptr_eq(b, a), + _ => true, + }; + let size_changed = before.symbol_natural_xf(name) != doc.symbol_natural_xf(name); + if !was.contains(name) || edit_ended.as_deref() == Some(name.as_str()) || art_changed || size_changed { + snap_symbol_art(doc, name); + every = true; + } + } + let natural: HashMap<String, Affine> = aligned.iter().map(|name| (name.clone(), doc.symbol_natural_xf(name))).collect(); + // The symbol editing layer holds another symbol's art. + let editing = doc.symbol_edit.as_ref().map(|e| e.layer); + if every { + for layer in doc.layers.iter_mut() { + if Some(layer.id) != editing && holds_instance(layer, &natural) { + snap_instances_in(Arc::make_mut(layer), &natural); + } + } + return; + } + let (mut ids, mut masked) = (vec![], vec![]); + if let Some(layer) = editing { + let outside = |layers: &[Arc<Node>]| layers.iter().filter(|l| l.id != layer).cloned().collect::<Vec<_>>(); + changed_instances(&outside(&before.layers), &outside(&doc.layers), &natural, &mut ids, &mut masked); + } else { + changed_instances(&before.layers, &doc.layers, &natural, &mut ids, &mut masked); + } + for id in ids { + if let Some(n) = doc.node_mut(id) { + snap_instance(n, &natural); + } + } + for id in masked { + if let Some(m) = doc.node_mut(id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_mut()) { + snap_instances_in(Arc::make_mut(&mut m.art), &natural); + } + } +} + +/// Among the objects of `after` that differ from their counterparts in `before` (or are new), in +/// groups too: the instances of the symbols in `natural` (`ids`), and the objects whose opacity +/// mask art holds such instances (`masked`). +fn changed_instances(before: &[Arc<Node>], after: &[Arc<Node>], natural: &HashMap<String, Affine>, ids: &mut Vec<NodeId>, masked: &mut Vec<NodeId>) { + let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None; + for (i, a) in after.iter().enumerate() { + let b = match before.get(i) { + Some(b) if b.id == a.id => Some(b), + _ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(), + }; + if b.is_some_and(|b| Arc::ptr_eq(b, a)) { + continue; + } + if a.extras().mask.as_ref().is_some_and(|m| holds_instance(&m.art, natural)) { + masked.push(a.id); + } + if let NodeKind::SymbolInstance { symbol, .. } = &a.kind { + if natural.contains_key(symbol) { + ids.push(a.id); + } + } else if let Some(children) = a.children() { + changed_instances(b.and_then(|b| b.children()).map_or(&[], Vec::as_slice), children, natural, ids, masked); + } + } +} + +/// Whether `n`, an object in it or the art of an opacity mask in it is an instance of a symbol in +/// `natural`. +fn holds_instance(n: &Node, natural: &HashMap<String, Affine>) -> bool { + matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if natural.contains_key(symbol)) + || n.extras().mask.as_ref().is_some_and(|m| holds_instance(&m.art, natural)) + || n.children().is_some_and(|ch| ch.iter().any(|c| holds_instance(c, natural))) +} + +/// [`snap_instance`] on every instance of a symbol in `natural` in `n`, the art of its opacity +/// masks included. Only what holds such an instance is copied for editing. +fn snap_instances_in(n: &mut Node, natural: &HashMap<String, Affine>) { + snap_instance(n, natural); + if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) + && holds_instance(&m.art, natural) + { + snap_instances_in(Arc::make_mut(&mut m.art), natural); + } + if let Some(children) = n.children_mut() { + for c in children.iter_mut() { + if holds_instance(c, natural) { + snap_instances_in(Arc::make_mut(c), natural); + } + } + } +} + +/// Snap the art of pixel-aligned symbol `name` to the pixel grid as it is drawn at the symbol's +/// natural size: each path and compound path in it snaps as a pixel-aligned object does +/// ([`snap_object`]), measured from the symbol's origin. The art is stored again only when +/// something in it moved, and the answer says whether it did. +pub(crate) fn snap_symbol_art(doc: &mut Document, name: &str) -> bool { + let natural = doc.symbol_natural_xf(name); + let det = natural.determinant(); + if !det.is_finite() || det.abs() < 1e-18 { + return false; + } + let Some(sym) = doc.symbols.iter_mut().find(|s| s.name == name) else { return false }; + // Instances draw the art's strokes at their stored width, and the art of unlinked opacity + // masks, which `Node::transform` leaves alone, at the natural size too. + let mut art = (*sym.art).clone(); + art.transform(natural, false); + transform_unlinked_masks(&mut art, natural); + if !snap_art(&mut art) { + return false; + } + let inverse = natural.inverse(); + art.transform(inverse, false); + transform_unlinked_masks(&mut art, inverse); + sym.art = Arc::new(art); + true +} + +/// Transform the art of every unlinked opacity mask in `n` by `xf`, in the art of other masks +/// too. Only what holds such a mask is copied for editing. +fn transform_unlinked_masks(n: &mut Node, xf: Affine) { + if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) + && holds_unlinked_mask(&m.art, !m.linked) + { + let linked = m.linked; + let art = Arc::make_mut(&mut m.art); + if !linked { + art.transform(xf, false); + } + transform_unlinked_masks(art, xf); + } + if let Some(children) = n.children_mut() { + for c in children.iter_mut() { + if holds_unlinked_mask(c, false) { + transform_unlinked_masks(Arc::make_mut(c), xf); + } + } + } +} + +/// Whether `n` is the art of an unlinked mask (`unlinked`), or it or an object in it, in the art of +/// its masks too, has an unlinked opacity mask. +fn holds_unlinked_mask(n: &Node, unlinked: bool) -> bool { + unlinked + || n.extras().mask.as_ref().is_some_and(|m| holds_unlinked_mask(&m.art, !m.linked)) + || n.children().is_some_and(|ch| ch.iter().any(|c| holds_unlinked_mask(c, false))) +} + +/// Snap every path and compound path in `n` ([`can_align`]) with [`snap_object`], the art of +/// opacity masks included (those of a compound path's paths too). Returns whether anything +/// changed. +fn snap_art(n: &mut Node) -> bool { + let mut moved = false; + if can_align(n) { + let was = n.clone(); + snap_object(n, Scaling::default()); + moved = *n != was; + if let Some(children) = n.children_mut() { + for c in children.iter_mut() { + if c.extras().mask.is_some() { + moved |= snap_mask(Arc::make_mut(c)); + } + } + } + } else if let Some(children) = n.children_mut() { + for c in children.iter_mut() { + moved |= snap_art(Arc::make_mut(c)); + } + } + // After the object itself, which a linked mask follows. + snap_mask(n) || moved +} + +/// [`snap_art`] on the art of `n`'s opacity mask. Returns whether anything changed. +fn snap_mask(n: &mut Node) -> bool { + let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) else { return false }; + let mut art = (*m.art).clone(); + if !snap_art(&mut art) { + return false; + } + m.art = Arc::new(art); + true +} + +/// Move symbol instance `n` to whole points when its transform places its symbol's art at the +/// symbol's natural size (`natural`, by symbol name), reflected across one axis or not. A scaled, +/// rotated (a half turn included) or sheared instance stays where it is. The instance moves as any +/// move moves it ([`Node::transform`]), so the art of a linked opacity mask moves with it. +fn snap_instance(n: &mut Node, natural: &HashMap<String, Affine>) { + let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return }; + let Some(nat) = natural.get(symbol.as_str()) else { return }; + let [a, b, c, d, e, f] = xf.as_coeffs(); + let [na, _, _, nd, _, _] = nat.as_coeffs(); + let near = |v: f64, to: f64| (v.abs() - to.abs()).abs() <= ACTUAL_SIZE_TOLERANCE * to.abs().max(1.0); + let actual = + near(a, na) && near(d, nd) && b.abs() <= ACTUAL_SIZE_TOLERANCE * na.abs().max(1.0) && c.abs() <= ACTUAL_SIZE_TOLERANCE * nd.abs().max(1.0); + // Flipped along both axes is a half turn, which counts as rotated. + let half_turn = a * na < 0.0 && d * nd < 0.0; + if !actual || half_turn || !e.is_finite() || !f.is_finite() { + return; + } + let (x, y) = (e.round(), f.round()); + if x == e && y == f { + return; + } + n.transform(Affine::translate((x - e, y - f)), Scaling::default()); + // Whole points exactly, which adding the offset to the old position need not give. + if let NodeKind::SymbolInstance { xf, .. } = &mut n.kind { + *xf = Affine::new([a, b, c, d, x, y]); + } } /// After a pass that moved what objects `ids` hold (Objects on Path placing its members): snap the -/// pixel-aligned objects in them to the pixel grid again. +/// pixel-aligned objects and the instances of pixel-aligned symbols in them to the pixel grid +/// again. pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) { for id in ids { if doc.node(*id).is_some_and(holds_aligned) @@ -162,6 +405,18 @@ pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) { keep_pixel_aligned(n, Scaling::default()); } } + let aligned = doc.pixel_aligned_symbols(); + if aligned.is_empty() { + return; + } + let natural: HashMap<String, Affine> = aligned.iter().map(|name| (name.clone(), doc.symbol_natural_xf(name))).collect(); + for id in ids { + if doc.node(*id).is_some_and(|n| holds_instance(n, &natural)) + && let Some(n) = doc.node_mut(*id) + { + snap_instances_in(n, &natural); + } + } } /// The objects of `after` that differ from their counterparts in `before` (or are new) and are diff --git a/crates/engine/src/cmd/overprint.rs b/crates/engine/src/cmd/overprint.rs index 8149701334..e8957691ec 100644 --- a/crates/engine/src/cmd/overprint.rs +++ b/crates/engine/src/cmd/overprint.rs @@ -126,14 +126,18 @@ fn kinds(p: &Value, cmd: &str, keys: [&str; 2]) -> Result<Vec<(bool, bool)>> { .collect() } -/// Each kind's item target and objects: (fill?, item, ids). -fn aims(s: &Session, p: &Value, cmd: &str, kinds: impl IntoIterator<Item = bool>) -> Result<Vec<(bool, ItemTarget, Vec<NodeId>)>> { +/// Each kind's item target and objects: (fill?, item, ids). With `edit`, the art of graph designs drawn in graph series +/// is left out, and an explicit item that the art left out has no row of that kind for is an error, as when the edit +/// resolves it on the other objects. Without it, the art is read with the other objects. +fn aims(s: &Session, p: &Value, cmd: &str, kinds: impl IntoIterator<Item = bool>, edit: bool) -> Result<Vec<(bool, ItemTarget, Vec<NodeId>)>> { let item = item_target(s, p, cmd)?; kinds .into_iter() .map(|fill| { let it = item.of_kind(s, fill); - Ok((fill, it, it.targets(s, p)?)) + let ids = it.targets(s, p)?; + let ids = if edit { super::appearance::drop_design_art_rows(s, ids, it, fill, cmd)? } else { ids }; + Ok((fill, it, ids)) }) .collect() } @@ -159,12 +163,7 @@ pub(super) type OverprintJob = ((bool, ItemTarget, Vec<NodeId>), bool); /// `object.setOverprint` aims, leaving out the art of graph designs drawn in graph series. pub(super) fn overprint_jobs(s: &Session, p: &Value, cmd: &str, keys: [&str; 2]) -> Result<Vec<OverprintJob>> { let kinds = kinds(p, cmd, keys)?; - let d = &s.doc()?.doc; - Ok(aims(s, p, cmd, kinds.iter().map(|k| k.0))? - .into_iter() - .map(|(fill, it, ids)| (fill, it, super::appearance::drop_design_art(d, ids))) - .zip(kinds.iter().map(|k| k.1)) - .collect()) + Ok(aims(s, p, cmd, kinds.iter().map(|k| k.0), true)?.into_iter().zip(kinds.iter().map(|k| k.1)).collect()) } /// Apply `jobs` to `d`, adding the objects changed to `changed`. @@ -203,7 +202,7 @@ fn attributes(s: &Session, p: &Value) -> Result<AttributesInfo> { let d = &s.doc()?.doc; let mut info = AttributesInfo { ids: targets(s, p)?, recent_urls: s.recent_urls.clone(), ..Default::default() }; super::attributes::fill_info(d, &mut info); - for (fill, item, ids) in aims(s, p, C, [true, false])? { + for (fill, item, ids) in aims(s, p, C, [true, false], false)? { let mut all = ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| Some(flags(n, fill, item.resolve(&n.appearance, fill, C).ok()?))).flatten(); let same = all.next().and_then(|first| all.all(|b| b == first).then_some(first)); diff --git a/crates/engine/src/cmd/package.rs b/crates/engine/src/cmd/package.rs index 315a737c59..c00f714515 100644 --- a/crates/engine/src/cmd/package.rs +++ b/crates/engine/src/cmd/package.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> { "Package", [], None, - "{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder. The warnings and the report name a file outside the automation read roots by its file name", + "{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked)", has_doc, package )] @@ -113,6 +113,30 @@ thread_local! { pub(crate) static PARTS_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; } +/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of +/// a PDF, `.ai` or EPS file; `None` for other files and for data that can't be read. +fn carried_document(name: &str, bytes: &[u8]) -> Option<Document> { + if super::place::document::is_native(name, bytes) { + return vectorcraft_format::load_file(bytes).ok().map(|f| f.doc); + } + let data = + if super::place::document::is_pdf(name, bytes) { vectorcraft_pdf::editing(bytes).map(|e| e.data) } else { vectorcraft_eps::native(bytes) }; + vectorcraft_format::load(&data?).ok() +} + +/// Under read roots, the linked file `name` (`bytes`, found at `path`) is copied only when the +/// native document it is or carries ([`carried_document`]) links no JavaScript file outside them (a +/// relative path taken from the file's folder): the copy would name it. +fn check_carried_scripts(name: &str, bytes: &[u8], path: &str) -> Result<()> { + if crate::file_access::current().is_none() { + return Ok(()); + } + match carried_document(name, bytes) { + Some(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true), + None => Ok(()), + } +} + /// The fonts of the type on `pages` of the PDF or `.ai` file `name` (`bytes`, found at `path`); /// none for other files. fn page_fonts(name: &str, bytes: &[u8], path: &str, pages: &PlacedPages) -> BTreeSet<super::fonts::UsedFont> { @@ -291,6 +315,7 @@ impl<'a> Collector<'a> { // read from its editing data links are copied beside it. let pages = placed.get(&file.path); let placed_file = pages.is_some(); + check_carried_scripts(&file.name, &bytes, found_path)?; if placed_file && let Some(mut art) = super::place::document::editing_data(&file.name, &bytes) { if depth >= vectorcraft_doc::placed_document::MAX_DEPTH { self.warn(&mut lines, format!("{shown}: nesting limit reached; copied unchanged without collecting its own links")); @@ -471,6 +496,8 @@ fn prepare(s: &mut Session, p: &Value) -> Result<Package> { let given_name = text_param(p, "name", C)?; let folder = text_param(p, "folder", C)?; let doc_path = s.doc()?.path.clone().ok_or_else(|| bad(C, "save the document first: Package collects a saved document"))?; + // Before anything is collected or written, here where the request's read roots are in force. + super::fileio::check_linked_scripts(C, "vectorcraft", s.doc()?, &Value::Null)?; let stem = Path::new(&doc_path).file_stem().map_or_else(|| "Untitled".into(), |s| s.to_string_lossy().into_owned()); let name = given_name.map_or_else(|| format!("{stem} Folder"), str::to_string); if name.trim().is_empty() || name == "." || name == ".." || name.contains(['/', '\\', ':', '*', '?', '"', '<', '>', '|']) { diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 6370f8dbf9..2421b71d77 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> { "Fill", [], None, - "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", + "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", has_doc, |s, p| set_paint(s, p, true) ), @@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> { "Swap Fill and Stroke", [], Some("Shift+X"), - "{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind (exceptions: docs/mcp.md)", + "{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring what the swap changes on its rows for every line of its kind (exceptions: docs/mcp.md)", has_doc, swap ), @@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> { "Default Fill and Stroke", [], Some("D"), - "{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults; type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind (exceptions: docs/mcp.md)", + "{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults; type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md)", has_doc, default_paint ), @@ -81,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> { "Transparency", ["Window", "Transparency"], None, - "{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; when every target is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso, those points take the opacity themselves). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series (for a fill or stroke item, a series group's id stands for those paths), the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke, and on a series group without an item, the group's own opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, the graph stores the label's object opacity and blend mode for every label of its kind, and with `item` its topmost visible fill and stroke rows too", + "{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; when every target is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso, those points take the opacity themselves). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series (for a fill or stroke item, a series group's id stands for those paths), the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke, and on a series group without an item, the group's own opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (for a fill or stroke item, a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; when their rows differ, `item` needs `aligned` and is a row of the backmost one), the graph stores that object's opacity and blend mode for every label or line of its kind, and with `item` its topmost visible fill and stroke rows too", has_doc, transparency ), @@ -96,7 +96,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> { "Invert", [], None, - "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind (docs/mcp.md); no undo step when no color changes → {changed}", + "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md); no undo step when no color changes → {changed}", has_doc, |s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert) ), @@ -555,9 +555,15 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) let ids = super::graph::paint_targets(&s.doc()?.doc, &selected); let of = super::appearance::reference_of(s, p, item, cmd)?; let paint = if span { - // With a design's art, the gradient spans only the objects with a row equal to the art's, which take it. - let spanned: Vec<NodeId> = ids.iter().zip(item.per_target_of(s, of, &ids)).filter_map(|(id, it)| it.map(|_| *id)).collect(); - placed_across(&s.doc()?.doc, &spanned, paint, p, fill) + // With a design's art, the gradient spans only the objects with a row equal to the art's, which take it. Each + // object's box is that of the row it edits. + let d = &s.doc()?.doc; + let mut spanned = Vec::with_capacity(ids.len()); + for (id, it) in ids.iter().zip(item.per_target_of(s, of, &ids)) { + let (Some(it), Some(n)) = (it, d.node(*id)) else { continue }; + spanned.push((*id, it.resolve(&n.appearance, fill, cmd)?)); + } + placed_across(d, &spanned, paint, p, fill) } else { paint }; @@ -649,6 +655,8 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) }, |before, d, changed| { let series = super::appearance::capture_series_paint_writes(before, d, changed, &written.borrow()); + // A graph line keeps the paint written to it, also when it already showed it. + let lines = super::graph::capture_line_paint_writes(d, &written.borrow()); let labels = super::graph::capture_label_styles(d, &characters.borrow(), &|st| { if fill { st.fill = unplaced(&paint); @@ -659,7 +667,7 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) st.stroke = unplaced(&paint); } }); - Ok(series || labels) + Ok(series || lines || labels) }, )?; // Rejected edits leave the next shape's appearance and active proxy untouched. @@ -730,14 +738,15 @@ fn spans_targets(p: &Value, paint: &Paint) -> std::result::Result<bool, String> Ok(true) } -/// `paint` placed once on the union of the bounds of `ids` (each one's fill box, or the box its -/// stroke paints), at the gradient's angle and aspect: every target gets the same vector in -/// document coordinates, so the ramp runs on across them (#2127). -fn placed_across(d: &Document, ids: &[NodeId], paint: Paint, p: &Value, fill: bool) -> Paint { +/// `paint` placed once on the union of the bounds of `ids` (each one's fill box, or the box the +/// stroke it edits paints: the row given with it, `None` for the topmost), at the gradient's angle +/// and aspect: every target gets the same vector in document coordinates, so the ramp runs on +/// across them (#2127). +fn placed_across(d: &Document, ids: &[(NodeId, Option<usize>)], paint: Paint, p: &Value, fill: bool) -> Paint { let union = ids .iter() - .filter_map(|id| d.node(*id)) - .filter_map(|n| item_paint_bounds(n, None, fill).or_else(|| n.geometric_bounds())) + .filter_map(|(id, index)| Some((d.node(*id)?, *index))) + .filter_map(|(n, index)| item_paint_bounds(n, index, fill).or_else(|| n.geometric_bounds())) .filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) .reduce(|a, b| a.union(b)); let (Some(union), Paint::Gradient(g)) = (union, &paint) else { return paint }; @@ -975,7 +984,13 @@ pub(super) fn restore_unpainted_stroke(ap: &mut Appearance, index: Option<usize> } fn swap(s: &mut Session, p: &Value) -> Result<Value> { - let ids = super::appearance::drop_design_art(&s.doc()?.doc, paint_targets(s, p)?); + let targets = paint_targets(s, p)?; + let given = !targets.is_empty(); + let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets); + // Only design art was given or selected: nothing changes, the defaults included. + if given && ids.is_empty() { + return ok(); + } if !ids.is_empty() { // When every object comes out as it was, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); @@ -998,7 +1013,7 @@ fn swap(s: &mut Session, p: &Value) -> Result<Value> { } // The swap writes the paint of the topmost fill and stroke, not their opacity. let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (false, false), true, false); - let labels = super::graph::capture_label_changes(&before, d, &ids, false); + let labels = super::graph::capture_label_changes(&before, d, &ids, false, None); Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels)) })?; } @@ -1010,7 +1025,13 @@ fn swap(s: &mut Session, p: &Value) -> Result<Value> { } fn default_paint(s: &mut Session, p: &Value) -> Result<Value> { - let ids = super::appearance::drop_design_art(&s.doc()?.doc, paint_targets(s, p)?); + let targets = paint_targets(s, p)?; + let given = !targets.is_empty(); + let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets); + // Only design art was given or selected: nothing changes, the defaults included. + if given && ids.is_empty() { + return ok(); + } if !ids.is_empty() { // When every object comes out as it was, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); @@ -1028,8 +1049,15 @@ fn default_paint(s: &mut Session, p: &Value) -> Result<Value> { } } let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, false); - let labels = super::graph::capture_label_changes(&before, d, &ids, false); - Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels)) + // The graph keeps the default paint for every label of a kind it reached, and the default fill and stroke rows + // for every line of a kind it reached, also when one already showed them; the object opacity a line kind keeps + // stays. + let labels = super::graph::capture_label_styles(d, &ids, &|st| { + st.fill = Paint::solid(Color::BLACK); + st.stroke = Paint::None; + }); + let lines = super::graph::capture_line_fill_stroke_rows(d, &ids); + Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels || lines)) })?; } super::newart::reset(s); @@ -1079,10 +1107,26 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn( return Ok(json!({ "changed": changed as usize })); } let item = item_target(s, p, cmd)?.of_kind(s, !stroke); + // Read before the check below, so that a bad param (such as `target` or `aligned`, or an explicit `item` the art has + // no row for) is still an error. + let targets = super::appearance::drop_design_art_rows(s, item.targets(s, p)?, item, !stroke, cmd)?; + let of = match item { + ItemTarget::Item { .. } => super::appearance::reference_of(s, p, item, cmd)?, + ItemTarget::Top => None, + }; + // Read before the check below too: `targets` reads no `target` for the topmost fill or stroke. + let contents = super::appearance::targets_contents(p)?; + let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids); + // Only design art was given or selected: nothing changes, the defaults and remembered colors included. + if ids.is_empty() { + return Ok(json!({ "changed": 0 })); + } let (r, shown_at) = match item { ItemTarget::Item { .. } => { - let targets = super::appearance::drop_design_art(&s.doc()?.doc, item.targets(s, p)?); - let of = super::appearance::reference_of(s, p, item, cmd)?; + // Only design art was given or selected: nothing changes, the remembered colors included. + if targets.is_empty() { + return Ok(json!({ "changed": 0 })); + } // The row shown is the one edited in the first object that has it: an aligned row maps to each object's equal row. let shown_at = super::appearance::first_edited(s, item, of, &targets).and_then(|(id, it)| match it { ItemTarget::Item { index, .. } => Some((id, Some(index))), @@ -1098,9 +1142,56 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn( (json!({ "changed": changed }), shown_at) } // The proxy recolors its paints, including a colorized image's fill, without changing image pixels or pattern tiles. + // A given group's own fills and strokes change with the objects inside it, except with `target: "contents"`; other + // objects change as their paint targets do (a compound path's member stands for the compound path). Design art + // inside a given graph or series group is left out. ItemTarget::Top => { - let q = json!({"fill": !stroke, "stroke": stroke, "includeImages": false, "includePatterns": false, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}); - (super::colorcmds::recolor(s, &q, cmd, label, f)?, leaf_targets(s, &ids)?.first().map(|id| (*id, None))) + let mut roots = vec![]; + for id in &ids { + let n = s.doc()?.doc.node(*id); + let group = + !contents && n.is_some_and(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !n.is_compound_shape()); + if group { + roots.push(*id); + } else { + roots.extend(leaf_targets(s, &[*id])?); + } + } + let d = &s.doc()?.doc; + let mut seen = std::collections::HashSet::new(); + roots.retain(|id| seen.insert(*id)); + let roots = super::appearance::drop_design_art(d, roots); + if roots.is_empty() { + return Ok(json!({ "changed": 0 })); + } + let art = super::appearance::design_art_in(d, &roots).into_iter().collect(); + // The fill or stroke the proxy shows of each group among the roots, before the edit. + let own = |d: &Document, id: NodeId| { + d.node(id) + .filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })) + .and_then(|n| n.proxy_paint_only(stroke, None)) + .cloned() + }; + let own_before: std::collections::HashMap<NodeId, Paint> = roots.iter().filter_map(|id| Some((*id, own(d, *id)?))).collect(); + let q = json!({"fill": !stroke, "stroke": stroke, "includeImages": false, "includePatterns": false, "ids": roots.iter().map(|i| i.0).collect::<Vec<_>>()}); + let r = super::colorcmds::recolor_except(s, &q, cmd, label, f, art)?; + // As the proxy shows a group: its own fill or stroke when the edit changed it, else the first object inside it + // that is not design art (which keeps its paint). The first object given that has either shows it. + let d = &s.doc()?.doc; + let mut shown_at = None; + for id in &ids { + if let Some(was) = own_before.get(id) + && own(d, *id).as_ref() != Some(was) + { + shown_at = Some((*id, None)); + break; + } + if let Some(leaf) = super::appearance::drop_design_art(d, leaf_targets(s, &[*id])?).first() { + shown_at = Some((*leaf, None)); + break; + } + } + (r, shown_at) } }; // The paint remembered is one the edit recolored: a graph design's art that the item edit leaves out gives none. @@ -1187,6 +1278,9 @@ fn transparency(s: &mut Session, p: &Value) -> Result<Value> { }; // Opacity and blend belong to the targeted fill/stroke; isolate/knockout/knockoutShape stay object-level. let item_ids = if editing_mask { ids } else { row_targets(s, p, C)? }; + if !editing_mask { + super::appearance::check_part_rows(s, p, aligned || !explicit, C)?; + } // The art of a graph design whose stack an explicit aligned item is a row of goes first: appearance.setItem leaves // it as it is and matches the other objects' rows against it. let of = if editing_mask || !explicit { None } else { super::appearance::design_reference(s, p, C)? }; diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 20905ffdae..a155245fbc 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away in horizontal type), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options, as text.setRangeStyle: the characters drawn in one OpenType form of the font, or its default glyphs; a form other than \"default\" takes away their glyph choice), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\"|\"standardSingleLine\"|\"standardEveryLine\" (line breaking, Every-line by default; singleLine and everyLine are the Middle Eastern & South Asian composers, which shape Indic, Arabic and Hebrew type; the standard ones set it glyph by glyph as the font maps its characters, for legacy fonts that keep a script on Latin character codes), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), kurikaeshiMojiShori?: bool (Paragraph panel menu › Kurikaeshi Moji Shori: a repeat mark 々, ゝ, ゞ, ヽ or ヾ that starts a line is drawn as the character before it, the voiced marks ゞ and ヾ as its voiced form when it has one, and the text keeps the mark; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away, down the column for an upright character in vertical type), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options, as text.setRangeStyle: the mark glyphs among the characters move right or up relative to their letters), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options, as text.setRangeStyle: the characters drawn in one OpenType form of the font, or its default glyphs; a form other than \"default\" takes away their glyph choice), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\"|\"standardSingleLine\"|\"standardEveryLine\" (line breaking, Every-line by default; singleLine and everyLine are the Middle Eastern & South Asian composers, which shape Indic, Arabic and Hebrew type; the standard ones set it glyph by glyph as the font maps its characters, for legacy fonts that keep a script on Latin character codes), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", has_doc, set_format ), @@ -522,6 +522,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { "romanHangingPunctuation", "koreanLineBreakAnywhere", "bunriKinshi", + "kurikaeshiMojiShori", ], C, )?; @@ -597,6 +598,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { "kinsoku", "kinsokuType", "bunriKinshi", + "kurikaeshiMojiShori", "direction", "leadingModel", "charAlign", @@ -614,6 +616,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { "akiLeft", "akiRight", "tsume", + "diacriticHorizontal", + "diacriticVertical", "standardVerticalRoman", "noBreak", "digits", @@ -663,6 +667,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { let aki_left = super::textedit::aki_param(p, "akiLeft", C)?; let aki_right = super::textedit::aki_param(p, "akiRight", C)?; let tsume = super::textedit::tsume_param(p, C)?; + let diacritic_horizontal = super::textedit::diacritic_param(p, "diacriticHorizontal", C)?; + let diacritic_vertical = super::textedit::diacritic_param(p, "diacriticVertical", C)?; let warichu_lines = super::textedit::warichu_lines_param(p, C)?; let warichu_gap = super::textedit::warichu_number_param(p, "warichuGap", C)?; let warichu_scale = super::textedit::warichu_number_param(p, "warichuScale", C)?; @@ -853,6 +859,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { if let Some(v) = tsume { st.tsume = v; } + st.diacritic_horizontal = diacritic_horizontal.unwrap_or(st.diacritic_horizontal); + st.diacritic_vertical = diacritic_vertical.unwrap_or(st.diacritic_vertical); if let Some(v) = flag("standardVerticalRoman") { st.standard_vertical_roman = v; } @@ -989,6 +997,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { if let Some(v) = flag("bunriKinshi") { para.bunri_kinshi = v; } + // An omitted or null value keeps the paragraph's own. + para.kurikaeshi_moji_shori = flag("kurikaeshiMojiShori").unwrap_or(para.kurikaeshi_moji_shori); if let Some(v) = direction { para.direction = v; } diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 4d160c7c49..8ae3b46426 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -149,7 +149,7 @@ pub fn specs() -> Vec<CommandSpec> { "Cut Path at Selected Anchor Points", [], None, - "{} cut the paths at their direct-selected anchors (one undo step): a closed path opens there, an open one becomes one path per piece; one of each cut's two coincident anchors stays selected → {ids}", + "{} cut the paths at their direct-selected anchors (one undo step): a closed path opens there, an open one becomes one path per piece; one of each cut's two coincident anchors stays selected; the paths keep the source's fill and stroke settings except that every stroke's alignment becomes Center (in a path of several subpaths, the other subpaths' strokes too) → {ids}", has_anchors, cut_at_anchors ), @@ -1858,6 +1858,8 @@ fn cut_at_anchors(s: &mut Session, _: &Value) -> Result<Value> { let (mut all, mut picked) = (vec![], vec![]); let mut cut = Beside::replacing(d, &cuts.iter().map(|(id, ..)| *id).collect::<Vec<_>>()); for (id, subs, starts) in cuts { + // The paths a cut makes keep the source's appearance with every stroke centered. + super::draw2::center_strokes(d, id); // A path of one subpath becomes one path per piece (the first keeps the id); the // pieces of a compound shape stay subpaths of it. if d.node(id).and_then(|n| n.path_data()).is_some_and(|pd| pd.subpaths.len() == 1) { diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index b5267fa990..5b7f22abd9 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -318,7 +318,7 @@ pub(crate) fn style_of(n: &Node) -> Style { /// Leaf shapes (paths, compound paths, text) of a subtree in paint order; guides and clipping /// paths are skipped. -fn leaves(n: &Node, out: &mut Vec<Node>) { +pub(crate) fn leaves(n: &Node, out: &mut Vec<Node>) { each_leaf(n, &mut |l| out.push(l.clone())); } diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 83216b2f43..4463cf5885 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -71,6 +71,8 @@ const MAX_QUEUE: usize = 100; const MAX_THUMBNAIL: f64 = 512.0; /// A text file's natural box (`file.place.info`, the place cursor): a letter page less 1 in margins. const TEXT_FRAME: Rect = Rect::new(0.0, 0.0, 468.0, 648.0); +/// An encrypted PDF's box in the place cursor, which reads it without its password: a letter page. +const LOCKED_PAGE: Rect = Rect::new(0.0, 0.0, 612.0, 792.0); pub fn specs() -> Vec<CommandSpec> { vec![ @@ -79,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> { "Place…", ["File"], Some("Cmd+Shift+P"), - "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), @@ -106,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> { "Load Place Cursor", [], None, - "{paths?: [path…], files?: [{name, dataBase64}…], link?, template?, page?, crop?, text?, dxf?, layers?, hiddenLayers?, importSlices?, thumbnail?: px} load the place cursor (the `place` tool) with up to 100 files (as file.place reads them): a click places the current file at 100% with its top-left corner there, a drag places it at the dragged size (aspect kept), ←/→ and ↑/↓ cycle the files, Esc discards the current one; each placement is a file.place, and the previous tool returns after the last → {count, files: [{name, format, width, height, thumbnailBase64?}], skipped: [{name, error}]}", + "{paths?: [path…], files?: [{name, dataBase64}…], link?, template?, page?, crop?, text?, dxf?, layers?, hiddenLayers?, importSlices?, thumbnail?: px} load the place cursor (the `place` tool) with up to 100 files (as file.place reads them): a click places the current file at 100% with its top-left corner there, a drag places it at the dragged size (aspect kept), ←/→ and ↑/↓ cycle the files, Esc discards the current one; each placement is a file.place, and the previous tool returns after the last; an encrypted PDF, .ai or .ait file stays in the cursor at 612 × 792 pt (VectorCraft's own size) with needsPassword: true and no thumbnail, and a click on it in the app asks for its password (headless, its file.place fails for want of the password) → {count, files: [{name, format, width, height, thumbnailBase64?, needsPassword?}], skipped: [{name, error}]}", has_doc, queue ), @@ -304,7 +306,7 @@ fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, slices_o let link = src.path.filter(|_| !embed).map(|path| super::links::link_info(path, &src.bytes)); let mut warnings: Vec<String> = unread.into_iter().chain(fileio::size_note(&img.blob.bytes)).collect(); *slices_out = psd_slices(slices_from, natural, &mut warnings); - let clip = fileio::psdread::clipping_path(&src.bytes); + let clip = img.clip.clone().map(|(path, _)| path); return Ok(Loaded { name, format, art: Art::Image(img, clip), natural, warnings, link, board: None }); } if pdf { @@ -988,6 +990,14 @@ fn read_queue(doc: u64, p: Value, queued: Vec<Value>) -> Result<QueueRead> { } Err(e) => { let name = str_param(&q, "path").or(str_param(&q, "name")).map(fileio::file_name).unwrap_or_default(); + // An encrypted PDF stays, at a size of its own, so that a click in the app can ask + // for its password. + if let Some(format) = locked_pdf(&q, &e) { + let (w, h) = (LOCKED_PAGE.width(), LOCKED_PAGE.height()); + files.push(json!({ "name": name, "format": format, "width": w, "height": h, "needsPassword": true })); + entries.push(json!({ "params": q, "name": name, "width": w, "height": h })); + continue; + } skipped.push(json!({ "name": name, "error": e.to_string() })); } } @@ -995,6 +1005,22 @@ fn read_queue(doc: u64, p: Value, queued: Vec<Value>) -> Result<QueueRead> { Ok(QueueRead { doc, params: p, entries, files, skipped }) } +/// The format id of the file `q` names when it is a PDF, `.ai` or `.ait` file (a path with one of +/// those extensions, as the app's password dialog reads it) that opens only with a password, and +/// reading it failed with `e` for want of that password (not for a bad option). +fn locked_pdf(q: &Value, e: &EngineError) -> Option<&'static str> { + if !e.to_string().contains(&vectorcraft_pdf::PdfError::NeedsPassword.to_string()) { + return None; + } + let src = fileio::source(q, QUEUE).ok()?; + if src.path.is_some() && !matches!(fileio::extension(src.name).as_str(), "pdf" | "ai" | "ait") { + return None; + } + let format = fileio::detect(src.name, &src.bytes)?; + let locked = matches!(vectorcraft_pdf::open_pdf(&src.bytes, None).map(|_| ()), Err(vectorcraft_pdf::PdfError::NeedsPassword)); + (matches!(format.id, "pdf" | "ai" | "ait") && locked).then_some(format.id) +} + impl Session { /// `file.place.queue`'s checks (with no document open, the error `file.place.queue` gives) of /// `params` → what reads the files ([`QueueJob::read`]; on the @@ -1044,15 +1070,9 @@ fn queue(s: &mut Session, p: &Value) -> Result<Value> { /// 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/dcs.rs b/crates/engine/src/cmd/place/dcs.rs index 69a397c5d1..efa02e06a8 100644 --- a/crates/engine/src/cmd/place/dcs.rs +++ b/crates/engine/src/cmd/place/dcs.rs @@ -104,6 +104,7 @@ pub(crate) fn read(bytes: &[u8], path: Option<&str>) -> Result<DcsArt> { }; let blob = ImageBlob::separated_tiff_clipped(&p.separated, p.ppi, &files, clip.as_ref()) .ok_or_else(|| EngineError::Other("the plates can't be kept".into()))?; + let clip = clip.map(|path| (path, vectorcraft_geom::FillRule::NonZero)); let img = RasterImage { key: blob.content_key(), blob, width: p.separated.width, height: p.separated.height, ppi: p.ppi, clip }; let spots = p.separated.spots().map(|s| (s.name.clone(), s.cmyk)).collect(); Ok(DcsArt { img, xf: p.xf, page: p.page, clip: p.clip, spots, warnings: p.warnings }) 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<Vec<u8>> { }) .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/place/docx.rs b/crates/engine/src/cmd/place/docx.rs index 063444442e..804e3fd6ae 100644 --- a/crates/engine/src/cmd/place/docx.rs +++ b/crates/engine/src/cmd/place/docx.rs @@ -38,7 +38,7 @@ use std::collections::HashMap; -use roxmltree::Node; +use craft_xml::{Canonical, Doctype, El, Limits, Names, Options}; use vectorcraft_doc::text::Kashida; use vectorcraft_doc::{CharPosition, CharStyle, Justify, ParaDirection, ParaStyle, ScriptMetrics, TextRun}; @@ -88,6 +88,7 @@ const MAX_RUNS: usize = 100_000; /// WordprocessingML's namespaces: Transitional, then Strict. const W: [&str; 2] = ["http://schemas.openxmlformats.org/wordprocessingml/2006/main", "http://purl.oclc.org/ooxml/wordprocessingml/main"]; +const DOCX_NS: Canonical<'static> = Canonical::new(&[("w", W[0]), ("w", W[1])]); /// Is the file `name` with `bytes` a Word document: a ZIP archive named `.docx`, or one that holds /// `word/document.xml`? @@ -104,7 +105,7 @@ pub(super) fn import(bytes: &[u8], cmd: &str) -> Result<Story> { let main = relationship(&zip, "", "officeDocument", cmd)?.unwrap_or_else(|| "word/document.xml".into()); let Some(xml) = part(&zip, &main, cmd)? else { return Err(bad(cmd, "not a Word document: its package has no main document part")) }; let doc = parse(&xml, &main, cmd)?; - if local(doc.root_element()) != Some("document") { + if local(&doc) != Some("document") { return Err(bad(cmd, "not a Word document: its main part is not a WordprocessingML document")); } let folder = main.rfind('/').and_then(|i| main.get(..=i)).unwrap_or_default(); @@ -117,7 +118,7 @@ pub(super) fn import(bytes: &[u8], cmd: &str) -> Result<Story> { if let Some(xml) = part(&zip, &styles, cmd)? { r.styles(&parse(&xml, &styles, cmd)?); } - if let Some(body) = doc.root_element().children().find(|n| local(*n) == Some("body")) { + if let Some(body) = child(&doc, "body") { r.block(body, 0); } r.finish(cmd) @@ -158,57 +159,21 @@ fn part(zip: &Archive, name: &str, cmd: &str) -> Result<Option<String>> { } /// The XML of the part `name`. -fn parse<'a>(xml: &'a str, name: &str, cmd: &str) -> Result<roxmltree::Document<'a>> { - // roxmltree parses nested elements recursively. - if nesting(xml) > MAX_NESTING { - return Err(bad(cmd, format!("`{name}` in the Word document nests elements more than {MAX_NESTING} deep"))); +fn parse(xml: &str, name: &str, cmd: &str) -> Result<El> { + let opts = Options { + names: Names::Canonical(&DOCX_NS), + doctype: Doctype::Reject, + limits: Limits { max_depth: MAX_NESTING, max_nodes: MAX_NODES as usize, ..Limits::DEFAULT }, + ..Options::default() } - let opts = roxmltree::ParsingOptions { nodes_limit: MAX_NODES, ..roxmltree::ParsingOptions::default() }; - roxmltree::Document::parse_with_options(xml, opts).map_err(|e| bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}"))) -} - -/// How deep the elements of `xml` nest: start tags less end tags, at most, outside comments, -/// CDATA sections, processing instructions, declarations and quoted attribute values. -pub(crate) fn nesting(xml: &str) -> usize { - let b = xml.as_bytes(); - let (mut depth, mut most, mut i) = (0usize, 0usize, 0usize); - // The index just past the first `end` at or after `from` (the end of the text if none). - let past = |from: usize, end: &[u8]| { - b.get(from..).and_then(|rest| rest.windows(end.len()).position(|w| w == end)).map_or(b.len(), |at| from + at + end.len()) - }; - while let Some(at) = b.get(i..).and_then(|rest| rest.iter().position(|&c| c == b'<')) { - let start = i + at; - let rest = b.get(start..).unwrap_or_default(); - if rest.starts_with(b"<!--") { - i = past(start + 4, b"-->"); - } else if rest.starts_with(b"<![CDATA[") { - i = past(start + 9, b"]]>"); - } else if rest.starts_with(b"<?") { - i = past(start + 2, b"?>"); - } else if rest.starts_with(b"<!") || rest.starts_with(b"</") { - depth = depth.saturating_sub(usize::from(rest.starts_with(b"</"))); - i = past(start + 2, b">"); - } else { - // A start tag: up to its `>` outside quotes; `/>` closes it at once. - let mut j = start + 1; - let mut quote = None; - while let Some(&c) = b.get(j) { - match (quote, c) { - (None, b'"' | b'\'') => quote = Some(c), - (Some(q), _) if c == q => quote = None, - (None, b'>') => break, - _ => {} - } - j += 1; - } - if b.get(j.saturating_sub(1)) != Some(&b'/') { - depth += 1; - most = most.max(depth); - } - i = j + 1; - } - } - most + .strict(); + let doc = opts.parse(xml.as_bytes()).map_err(|e| match e { + craft_xml::Error::TooDeep(_) => bad(cmd, format!("`{name}` in the Word document nests elements more than {MAX_NESTING} deep")), + _ => bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}")), + })?; + crate::cmd::xmlattrs::validate(xml.as_bytes(), opts.limits) + .map_err(|e| bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}")))?; + Ok(doc) } /// The part that the first relationship of part `source` (`""`: the package) whose type ends in @@ -220,11 +185,10 @@ fn relationship(zip: &Archive, source: &str, kind: &str, cmd: &str) -> Result<Op let Some(xml) = part(zip, &rels, cmd)? else { return Ok(None) }; let doc = parse(&xml, &rels, cmd)?; let target = doc - .root_element() - .children() - .filter(|n| n.tag_name().name() == "Relationship" && n.attribute("TargetMode") != Some("External")) - .find(|n| n.attribute("Type").is_some_and(|t| t.rsplit('/').next() == Some(kind))) - .and_then(|n| n.attribute("Target")); + .elements() + .filter(|n| n.local() == "Relationship" && n.attr("TargetMode") != Some("External")) + .find(|n| n.attr("Type").is_some_and(|t| t.rsplit('/').next() == Some(kind))) + .and_then(|n| n.attr("Target")); Ok(target.map(|t| resolve(folder, t))) } @@ -248,22 +212,22 @@ fn resolve(folder: &str, target: &str) -> String { } /// `n`'s local name when it is a WordprocessingML element. -fn local<'a>(n: Node<'a, '_>) -> Option<&'a str> { - (n.is_element() && n.tag_name().namespace().is_some_and(|ns| W.contains(&ns))).then(|| n.tag_name().name()) +fn local(n: &El) -> Option<&str> { + n.name.strip_prefix("w:") } /// `n`'s first WordprocessingML child element named `name`. -fn child<'a, 'i>(n: Node<'a, 'i>, name: &str) -> Option<Node<'a, 'i>> { - n.children().find(|c| local(*c) == Some(name)) +fn child<'a>(n: &'a El, name: &str) -> Option<&'a El> { + n.elements().find(|c| local(c) == Some(name)) } /// `n`'s WordprocessingML attribute `name`. -fn attr<'a>(n: Node<'a, '_>, name: &str) -> Option<&'a str> { - n.attributes().find(|a| a.name() == name && a.namespace().is_some_and(|ns| W.contains(&ns))).map(|a| a.value()) +fn attr<'a>(n: &'a El, name: &str) -> Option<&'a str> { + n.attrs.iter().find_map(|(k, v)| k.strip_prefix("w:").filter(|&l| l == name).map(|_| v.as_str())) } /// An on/off property (ST_OnOff): on unless `w:val` is `false`, `0` or `off`. -fn on(n: Node) -> bool { +fn on(n: &El) -> bool { !matches!(attr(n, "val"), Some("false" | "0" | "off")) } @@ -280,12 +244,12 @@ fn measure(v: &str, per_pt: f64) -> Option<f64> { } /// Twentieths of a point. -fn twips(n: Node, name: &str) -> Option<f64> { +fn twips(n: &El, name: &str) -> Option<f64> { attr(n, name).and_then(|v| measure(v, 20.0)) } /// Half points. -fn half_points(n: Node) -> Option<f64> { +fn half_points(n: &El) -> Option<f64> { attr(n, "val").and_then(|v| measure(v, 2.0)) } @@ -462,21 +426,21 @@ struct Reader { impl Reader { /// The major and minor fonts of a theme part's font scheme. - fn theme_fonts(&mut self, doc: &roxmltree::Document) { + fn theme_fonts(&mut self, doc: &El) { for (slot, scheme) in self.theme.iter_mut().zip(["majorFont", "minorFont"]) { - *slot = doc - .descendants() - .find(|n| n.tag_name().name() == scheme) - .and_then(|n| n.children().find(|c| c.tag_name().name() == "latin")) - .and_then(|n| n.attribute("typeface")) + *slot = std::iter::once(doc) + .chain(doc.descendants()) + .find(|n| n.local() == scheme) + .and_then(|n| n.elements().find(|c| c.local() == "latin")) + .and_then(|n| n.attr("typeface")) .map(font_name) .filter(|f| !f.is_empty()); } } /// The document defaults and the styles of the styles part. - fn styles(&mut self, doc: &roxmltree::Document) { - for n in doc.root_element().children() { + fn styles(&mut self, doc: &El) { + for n in doc.elements() { match local(n) { Some("docDefaults") => { let props = |outer: &str, inner: &str| child(n, outer).and_then(|d| child(d, inner)); @@ -526,7 +490,7 @@ impl Reader { } /// The number of the font a `w:rFonts` element names. - fn font(&mut self, n: Node) -> Option<usize> { + fn font(&mut self, n: &El) -> Option<usize> { let theme = |v: &str| self.theme.get(usize::from(v.starts_with("minor"))).and_then(Option::as_deref); let name = attr(n, "asciiTheme") .and_then(theme) @@ -549,9 +513,9 @@ impl Reader { } /// The run properties of a `w:rPr` element. - fn run_props(&mut self, rpr: Node) -> RunProps { + fn run_props(&mut self, rpr: &El) -> RunProps { let mut p = RunProps::default(); - for n in rpr.children() { + for n in rpr.elements() { match local(n) { Some("rFonts") => p.font = self.font(n), Some("b") => p.bold = Some(on(n)), @@ -594,11 +558,11 @@ impl Reader { } /// The paragraphs, tables and containers of them that are `n`'s children. - fn block(&mut self, n: Node, depth: usize) { + fn block(&mut self, n: &El, depth: usize) { if depth > MAX_DEPTH { return; } - for c in n.children() { + for c in n.elements() { if self.full { return; } @@ -617,7 +581,7 @@ impl Reader { } /// A table: each row a paragraph, its cells separated by tabs. - fn table(&mut self, tbl: Node, depth: usize) { + fn table(&mut self, tbl: &El, depth: usize) { for row in items(tbl, "tr", depth) { for cell in items(row, "tc", depth) { self.flush(); @@ -638,7 +602,7 @@ impl Reader { } /// A paragraph. - fn paragraph(&mut self, p: Node, depth: usize) { + fn paragraph(&mut self, p: &El, depth: usize) { self.flush(); let ppr = child(p, "pPr"); let style = ppr @@ -675,11 +639,11 @@ impl Reader { } /// The runs of a paragraph, and the containers of runs in it. - fn inline(&mut self, n: Node, depth: usize) { + fn inline(&mut self, n: &El, depth: usize) { if depth > MAX_DEPTH { return; } - for c in n.children() { + for c in n.elements() { match local(c) { Some("r") => self.run(c), Some("hyperlink" | "ins" | "moveTo" | "smartTag" | "customXml" | "fldSimple" | "dir" | "bdo") => self.inline(c, depth + 1), @@ -694,7 +658,7 @@ impl Reader { } /// A run. - fn run(&mut self, r: Node) { + fn run(&mut self, r: &El) { let rpr = child(r, "rPr"); let mut chars = self.base; let style = rpr @@ -709,11 +673,10 @@ impl Reader { let props = self.run_props(n); chars.apply(&props, false); } - for c in r.children() { + for c in r.elements() { match local(c) { Some("t") => { - // Comments and processing instructions may split the text. - for ch in c.children().filter(|n| n.is_text()).filter_map(|n| n.text()).flat_map(str::chars) { + for ch in c.text().chars() { self.put(ch, chars); } } @@ -907,9 +870,9 @@ fn font_name(name: &str) -> String { } /// The paragraph properties of a `w:pPr` element. -fn para_props(ppr: Node) -> ParaProps { +fn para_props(ppr: &El) -> ParaProps { let mut p = ParaProps::default(); - for n in ppr.children() { + for n in ppr.elements() { match local(n) { Some("jc") => { p.align = match attr(n, "val") { @@ -945,12 +908,12 @@ fn para_props(ppr: Node) -> ParaProps { } /// `n`'s children named `name`, and those inside content controls and custom XML among them. -fn items<'a, 'i>(n: Node<'a, 'i>, name: &str, depth: usize) -> Vec<Node<'a, 'i>> { +fn items<'a>(n: &'a El, name: &str, depth: usize) -> Vec<&'a El> { let mut out = vec![]; if depth > MAX_DEPTH { return out; } - for c in n.children() { + for c in n.elements() { match local(c) { Some(l) if l == name => out.push(c), Some("sdt") => { @@ -979,15 +942,6 @@ mod tests { assert_eq!(measure("wide", 20.0), None); } - #[test] - fn nesting_counts_elements_outside_markup_that_is_not_an_element() { - assert_eq!(nesting(r#"<?xml version="1.0"?><a><b x="1>2" y='</c>'><c/></b><!-- <d><e> --><![CDATA[<f><g>]]></a>"#), 2); - assert_eq!(nesting("<a><b><c>"), 3, "unclosed elements count"); - assert_eq!(nesting("</a></b><a>"), 1); - assert_eq!(nesting("<a x=\"unterminated"), 1); - assert_eq!(nesting(""), 0); - } - #[test] fn targets_resolve_against_their_folder() { assert_eq!(resolve("", "word/document.xml"), "word/document.xml"); diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index a269ace561..6a0caf4cd6 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -40,8 +40,13 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.image.colorMask", "addon.image.removeBackground", "addon.image.removeColorMask", + "addon.packaging.check", + "addon.packaging.roles", + "addon.packaging.setRole", + "addon.packaging.setRoleSwatch", "addon.pathtools.addPoints", "addon.pathtools.close", + "addon.pathtools.commonTangents", "addon.pathtools.corner", "addon.pathtools.cornerRemove", "addon.pathtools.cornerSet", @@ -60,6 +65,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.pathtools.shape.set", "addon.pathtools.slideAnchor", "addon.pathtools.smooth", + "addon.pathtools.tangentCircle", "addon.pathtools.trim", "addon.pen.append", "addon.pen.close", @@ -622,6 +628,7 @@ pub(super) const ALLOWED: &[&str] = &[ "text.fonts", "text.getRange", "text.glyphAlternates", + "text.glyphCategories", "text.insertInline", "text.missingFonts", "text.replaceFont", @@ -700,8 +707,9 @@ pub(super) const ALLOWED: &[&str] = &[ ]; /// Commands a plug-in may not call although no rule refuses them, in order: they change the -/// preferences, a tool's options, a drag's state or the font names the whole app knows, run -/// plug-ins again, or read a file and report where it is on disk. +/// preferences, a tool's options, a drag's state or the font names the whole app knows, list the +/// fonts installed on the system as `text.fontList` does, run plug-ins again, or read a file and +/// report where it is on disk. pub(super) const DENIED: &[&str] = &[ "addon.cleanup.splitText", "addon.pathtools.movePointsTogether", @@ -714,5 +722,6 @@ pub(super) const DENIED: &[&str] = &[ "object.pathfinder.options", "stroke.arrowheads.edit", "stroke.arrowheads.list", + "text.similarFonts", "type.compositeFonts.set", ]; 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/rasterfx.rs b/crates/engine/src/cmd/rasterfx.rs index 5f412e080d..aaaef531bf 100644 --- a/crates/engine/src/cmd/rasterfx.rs +++ b/crates/engine/src/cmd/rasterfx.rs @@ -174,19 +174,14 @@ pub(crate) fn effects_scale(doc: &Document) -> f64 { (doc.raster_effects_ppi / 72.0).clamp(1.0 / 72.0, 2400.0 / 72.0) } -/// An embedded image (a new node of `out`, its pixels in `out.images`) of `whole` rendered alone -/// with `out`'s resources at `scale` over all it paints (the reach of its own, its members' and its -/// fills' and strokes' raster effects included). With `knockout`, the coverage of that art is knocked out -/// of the image, which then only holds what the effects add around it (a shadow to go under the -/// vector object). The document's raster effects settings add room around it and finish its pixels. -/// `None` when it paints nothing, when the area it covers overflows `f64` or the scale is not -/// positive, or when its PNG can't be encoded. -pub(crate) fn effect_image(out: &mut Document, whole: &Node, knockout: Option<&Node>, scale: f64) -> Option<Node> { +/// The region [`effect_image`] renders `whole` over in `d`, and the scale it renders at (`scale`, or +/// less for an image past 64 Mpx or a side the renderer can't address). `None` when it paints +/// nothing, when the area it covers overflows `f64` or the scale is not positive. +fn effect_region(d: &Document, whole: &Node, scale: f64) -> Option<(Rect, f64)> { // What it paints (its members' effects included), and how far its fills' and strokes' raster // effects reach beyond that. - let b = vectorcraft_render::painted_bounds(out, whole)?; - let look = out.raster_effects.clone(); - let reach = whole.appearance.items.iter().map(|i| effects::outset(i.effects(), b)).fold(0.0, f64::max) + 2.0 + look.add_around; + let b = vectorcraft_render::painted_bounds(d, whole)?; + let reach = whole.appearance.items.iter().map(|i| effects::outset(i.effects(), b)).fold(0.0, f64::max) + 2.0 + d.raster_effects.add_around; let b = b.inflate(reach, reach); // An area too large for f64 gives a zero scale and an image transform that is not finite. let area = b.width() * b.height(); @@ -201,6 +196,19 @@ pub(crate) fn effect_image(out: &mut Document, whole: &Node, knockout: Option<&N return None; } let region = Rect::new(b.x0, b.y0, b.x0 + (b.width() * scale).ceil().max(1.0) / scale, b.y0 + (b.height() * scale).ceil().max(1.0) / scale); + Some((region, scale)) +} + +/// An embedded image (a new node of `out`, its pixels in `out.images`) of `whole` rendered alone +/// with `out`'s resources at `scale` over all it paints (the reach of its own, its members' and its +/// fills' and strokes' raster effects included). With `knockout`, the coverage of that art is knocked out +/// of the image, which then only holds what the effects add around it (a shadow to go under the +/// vector object). The document's raster effects settings add room around it and finish its pixels. +/// `None` when it paints nothing, when the area it covers overflows `f64` or the scale is not +/// positive, or when its PNG can't be encoded. +pub(crate) fn effect_image(out: &mut Document, whole: &Node, knockout: Option<&Node>, scale: f64) -> Option<Node> { + let (region, scale) = effect_region(out, whole, scale)?; + let look = out.raster_effects.clone(); // Anti-alias off: hard edges (the effects themselves stay smooth). let anti_alias = if look.anti_alias { AntiAlias::Art } else { AntiAlias::None }; let mut img = render(out, vec![whole.clone()], region, scale, anti_alias); @@ -311,6 +319,19 @@ pub(crate) fn raster_image(d: &mut Document, n: &Node, below: bool, members: boo if !below && let Some(image) = rasterize_effect_image(d, n) { return Some(image); } + let whole = effect_art(n, below, members); + let bare = below.then(|| { + let mut b = whole.clone(); + strip_raster(&mut b, false); + b + }); + effect_image(d, &whole, bare.as_ref(), image_scale(d, n)) +} + +/// The art [`raster_image`] renders the raster effects of `n` from with `below` and `members`: +/// `n` without its transparency, a group's or layer's members without their raster effects when +/// both are set. +fn effect_art(n: &Node, below: bool, members: bool) -> Node { let mut whole = n.clone(); (whole.opacity, whole.blend) = (1.0, Default::default()); whole.extras_mut().mask = None; @@ -319,17 +340,39 @@ pub(crate) fn raster_image(d: &mut Document, n: &Node, below: bool, members: boo strip_raster(Arc::make_mut(c), true); } } - let bare = below.then(|| { - let mut b = whole.clone(); - strip_raster(&mut b, false); - b - }); - // A Rasterize effect at a finer resolution than the document's is rendered at its own. - let scale = raster_fx(n) - .iter() - .filter_map(|fx| if let RasterFx::Rasterize(r) = fx { r.ppi } else { None }) - .fold(effects_scale(d), |s, ppi| s.max(ppi / 72.0)); - effect_image(d, &whole, bare.as_ref(), scale) + whole +} + +/// Pixels per point of the image of the raster effects of `n`: the document's raster effects +/// resolution, or a Rasterize effect's finer one, which is rendered at its own. +fn image_scale(d: &Document, n: &Node) -> f64 { + raster_fx(n).iter().filter_map(|fx| if let RasterFx::Rasterize(r) = fx { r.ppi } else { None }).fold(effects_scale(d), |s, ppi| s.max(ppi / 72.0)) +} + +/// The pixels of the image [`raster_image`] makes of the raster effects of `n` in `d` with `below` +/// and `members`, as [`effect_image`] sizes it, or at the resolution and with the room around the +/// art of the object's own Rasterize effect when that is its only one ([`rasterize_effect_image`]); +/// 0 when it paints nothing. +pub(crate) fn raster_pixels(d: &Document, n: &Node, below: bool, members: bool) -> u64 { + if !below && let Some((art, r, _)) = rasterize_effect_art(d, n) { + // Measured as Object › Rasterize measures it. + let scale = r.ppi.unwrap_or(d.raster_effects_ppi) / 72.0; + let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE); + let size = vectorcraft_render::drawn_bounds(d, &art).map(|b| { + let b = b.inflate(r.add_around, r.add_around); + ((b.width() * scale).ceil().max(1.0), (b.height() * scale).ceil().max(1.0)) + }); + // Past Object › Rasterize's limits that image is not made, and the effect's image is. + if let Some((w, h)) = size + && w * h <= super::menucmds::MAX_PIXELS + && w <= side + && h <= side + { + return (w * h) as u64; + } + } + effect_region(d, &effect_art(n, below, members), image_scale(d, n)) + .map_or(0, |(r, scale)| ((r.width() * scale).round() * (r.height() * scale).round()) as u64) } /// The image Object › Rasterize makes of `n` with the options of `n`'s Effect › Rasterize, when @@ -339,15 +382,7 @@ pub(crate) fn raster_image(d: &mut Document, n: &Node, below: bool, members: boo /// the image is made of the art before them and moved by them, as the canvas draws it. `None` /// otherwise, when those Transform effects flatten the image, or when the image can't be made. fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option<Node> { - let [RasterFx::Rasterize(r)] = raster_fx(n)[..] else { return None }; - let staged = vectorcraft_render::rasterize_stage(d, n); - if let Some((_, map)) = &staged - && !(map.determinant().is_finite() && map.determinant().abs() > 1e-12) - { - return None; - } - let n = staged.as_ref().map_or(n, |(stage, _)| stage); - let at = n.appearance.effects.iter().position(|e| e.visible && e.id == effects::RASTERIZE)?; + let (whole, r, map) = rasterize_effect_art(d, n)?; let p = json!({ "ppi": r.ppi.unwrap_or(d.raster_effects_ppi), "colorModel": r.color_model.id(), @@ -356,20 +391,39 @@ fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option<Node> { "clippingMask": r.clipping_mask, "addAround": r.add_around, }); - let mut whole = n.clone(); - whole.appearance.effects.remove(at); - (whole.opacity, whole.blend) = (1.0, Default::default()); - whole.extras_mut().mask = None; // shortcut: expanded Rasterize effects stay RGB, as the object keeps its own opacity mask and the // image's transparency would need one too; upgrade when CMYK images carry alpha. let image = super::menucmds::rasterize_art(d, vec![whole], &p, "object.rasterize", false).ok()?; let mut image = image.into_node(d); - if let Some((_, map)) = staged { + if let Some(map) = map { image.transform(map, false); } Some(image) } +/// What [`rasterize_effect_image`] makes its image of: `n`, or the art before the Transform effects +/// that move the image, without the Rasterize effect and without its transparency; that effect's +/// options; and the map those Transform effects move the image by. `None` when `n` has another +/// raster effect, when the Rasterize effect is not its own, or when those Transform effects +/// flatten the image. +fn rasterize_effect_art(d: &Document, n: &Node) -> Option<(Node, effects::Rasterize, Option<Affine>)> { + let [RasterFx::Rasterize(r)] = raster_fx(n)[..] else { return None }; + let staged = vectorcraft_render::rasterize_stage(d, n); + if let Some((_, map)) = &staged + && !(map.determinant().is_finite() && map.determinant().abs() > 1e-12) + { + return None; + } + let (stage, map) = staged.map_or((None, None), |(stage, map)| (Some(stage), Some(map))); + let n = stage.as_ref().unwrap_or(n); + let at = n.appearance.effects.iter().position(|e| e.visible && e.id == effects::RASTERIZE)?; + let mut whole = n.clone(); + whole.appearance.effects.remove(at); + (whole.opacity, whole.blend) = (1.0, Default::default()); + whole.extras_mut().mask = None; + Some((whole, r, map)) +} + /// `v` (an object without its raster effects) replaced by `image` of the object with them: the /// image takes its place with its id, name and transparency (a layer keeps the image as its only /// member). diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index e54d68204e..b51bb4a97d 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> { "Recolor Artwork", ["Edit", "Edit Colors"], None, - "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded and empty rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}", + "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null] (what `group` is rewritten with, a null removing the group's swatch at its place; default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}", has_doc, apply ), @@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> { "Randomize Colors", [], None, - "{map: rows as recolor.apply, order?: true (shuffle the new colours among the rows that aren't excluded), saturationBrightness?: false (random saturation and brightness, hue kept), seed?: 0} → {map: the rows with their new colours as keys}", + "{map: rows as recolor.apply (an excluded row, or a row whose from is empty, keeps its new color), order?: true (shuffle the new colours among the rows that aren't excluded and hold current colors), saturationBrightness?: false (random saturation and brightness, hue kept), seed?: 0} → {map: the rows with their new colours as keys}", always, randomize ), @@ -1384,6 +1384,9 @@ struct Row { tint: f32, /// The row's own `model`, which takes the place of the command's for its colors. model: Option<ModelRule>, + /// `added`: with no current colors, the new color is a color added to the group, which it + /// joins after the colors of the rows with current colors. + added: bool, } /// The color model a row's colors take (`model`): each color's own, the new color's, or the @@ -1437,9 +1440,10 @@ fn parse_rows(p: &Value, cmd: &str) -> Result<Vec<Row>> { }; let cur = |v: &Value| Match::of(v).ok_or_else(|| bad(cmd, format!("bad current colour {v}"))); match p.get("map") { - Some(Value::Object(m)) => { - m.iter().map(|(k, v)| Ok(Row { from: vec![cur(&json!(k))?], to: new(Some(v))?, exclude: false, tint: 1.0, model: None })).collect() - } + Some(Value::Object(m)) => m + .iter() + .map(|(k, v)| Ok(Row { from: vec![cur(&json!(k))?], to: new(Some(v))?, exclude: false, tint: 1.0, model: None, added: false })) + .collect(), Some(Value::Array(rows)) => rows .iter() .map(|r| { @@ -1450,7 +1454,8 @@ fn parse_rows(p: &Value, cmd: &str) -> Result<Vec<Row>> { }; let tint = (super::number_or(r, "tint", 100.0, cmd)? / 100.0).clamp(0.0, 1.0) as f32; let model = ModelRule::param(r, cmd)?; - Ok(Row { from, to: new(r.get("to"))?, exclude: switch_or(r, "exclude", false, cmd)?, tint, model }) + let added = switch_or(r, "added", false, cmd)?; + Ok(Row { from, to: new(r.get("to"))?, exclude: switch_or(r, "exclude", false, cmd)?, tint, model, added }) }) .collect(), _ => Err(bad(cmd, "missing `map` (rows [{from, to}] or {current: new})")), @@ -1487,6 +1492,10 @@ struct ColorMap { group: Vec<GroupSwatch>, keys: HashMap<ColorKey, usize>, hexes: HashMap<String, usize>, + /// The current colors of the rows whose new color was removed (`to: null`, not excluded), + /// which keep their colors. + removed_keys: std::collections::HashSet<ColorKey>, + removed_hexes: std::collections::HashSet<String>, /// Set when a colour took a new colour of another model in its own model. converted: std::cell::Cell<bool>, /// The Global Adjust every mapped colour takes after its row's new colour. @@ -1505,11 +1514,23 @@ impl ColorMap { group, keys: HashMap::new(), hexes: HashMap::new(), + removed_keys: Default::default(), + removed_hexes: Default::default(), converted: Default::default(), adjust, }; for (n, r) in rows.iter().enumerate().filter(|(_, r)| !r.from.is_empty()) { - let Some(to) = r.new_color() else { continue }; + let Some(to) = r.new_color() else { + if !r.exclude { + for m in &r.from { + match m { + Match::Key(k) => out.removed_keys.insert(*k), + Match::Hex(h) => out.removed_hexes.insert(h.clone()), + }; + } + } + continue; + }; let i = out.rows.len(); let colors: Vec<Color> = r.from.iter().map(Match::color).collect(); let link = links.get(n).cloned().flatten(); @@ -1550,9 +1571,18 @@ impl ColorMap { /// the row gives it the new color in that color's model and the Global Adjust gives it the /// swatch's new color at that tint; /// other rows map the colour, which loses its link when it changes or when the group's rewrite - /// would change it. True when anything changed. + /// would change it; a color of a row whose new color was removed keeps its color and loses its + /// link to a swatch of the group whose rewrite would change it. True when anything changed. fn map_link(&self, c: &mut Color, link: &mut Option<String>, tint: &mut f32) -> bool { - let Some(i) = self.row_of(*c) else { return false }; + let Some(i) = self.row_of(*c) else { + let removed = self.removed_keys.contains(&ColorKey::of(c)) || self.removed_hexes.contains(&c.to_hex()); + let rewritten = link.as_deref().and_then(|n| self.group.iter().find(|g| g.name == n)).is_some_and(|g| g.shown.tinted(*tint) != *c); + if removed && rewritten { + *link = None; + return true; + } + return false; + }; let (Some(row), Some(l)) = (self.rows.get(i), self.links.get(i)) else { return false }; if l.is_none() && let Some(g) = link.as_deref().and_then(|n| self.group.iter().find(|g| g.name == n)) @@ -1650,18 +1680,27 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> { Some(Value::Array(cs)) => Some(cs), Some(_) => return Err(bad(C, "`groupColors` must be an array")), }; - let new: Vec<Color> = match group_colors { + // A null in groupColors removes the group's swatch at its place. + let new: Vec<Option<Color>> = match group_colors { Some(cs) => cs .iter() - .map(|v| { - color_value(v) + .map(|v| match v { + Value::Null => Ok(None), + v => color_value(v) .map(|c| adjust.apply(c)) - .map(|c| in_doc_model(palette.as_ref().map_or(c, |pl| pl.nearest(c)))) - .ok_or_else(|| bad(C, format!("bad colour {v} in groupColors"))) + .map(|c| Some(in_doc_model(palette.as_ref().map_or(c, |pl| pl.nearest(c))))) + .ok_or_else(|| bad(C, format!("bad colour {v} in groupColors"))), }) .collect::<Result<_>>()?, - // A row with no current colors gives the group no color. - None => rows.iter().filter(|r| !r.from.is_empty()).filter_map(Row::new_color).map(|c| mapped_adjust.apply(c)).collect(), + // A row with no current colors gives the group no color, unless it is a color added to + // the group: those follow the colors of the rows with current colors. + None => rows + .iter() + .filter(|r| !r.from.is_empty()) + .chain(rows.iter().filter(|r| r.from.is_empty() && r.added)) + .filter_map(Row::new_color) + .map(|c| Some(mapped_adjust.apply(c))) + .collect(), }; let rename = text_param(p, "rename", C)?; let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok(); @@ -1696,7 +1735,8 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> { .iter() .zip(&new) .filter(|(w, _)| w.global && !w.is_reserved()) - .map(|(w, c)| GroupSwatch { name: w.name.clone(), color: *c, shown: d.linked_color(*c, w.spot) }) + .filter_map(|(w, c)| Some((w, (*c)?))) + .map(|(w, c)| GroupSwatch { name: w.name.clone(), color: c, shown: d.linked_color(c, w.spot) }) .collect() }) .unwrap_or_default(); @@ -1746,8 +1786,11 @@ fn randomize(_: &mut Session, p: &Value) -> Result<Value> { let mut rng = Rng::new(super::menucmds::whole_or(p, "seed", 0, C)?); let (order, saturation_brightness) = (switch_or(p, "order", true, C)?, switch_or(p, "saturationBrightness", false, C)?); // Each new color with its row's tint and model: a tint moves with its color, and goes when - // the color changes; a model moves with its color. - let mut news: Vec<(Color, f32, Option<ModelRule>)> = rows.iter().filter_map(|r| r.new_color().map(|c| (c, r.tint, r.model))).collect(); + // the color changes; a model moves with its color. A row with no current colors recolors + // nothing, so it keeps its new color and takes no other row's. + let takes = |r: &Row| !r.from.is_empty() && r.new_color().is_some(); + let mut news: Vec<(Color, f32, Option<ModelRule>)> = + rows.iter().filter(|r| takes(r)).filter_map(|r| r.new_color().map(|c| (c, r.tint, r.model))).collect(); if order { rng.shuffle(&mut news); } @@ -1765,7 +1808,7 @@ fn randomize(_: &mut Session, p: &Value) -> Result<Value> { .iter() .map(|r| { let (to, tint, model) = - if r.new_color().is_some() { news.next().map_or((None, 1.0, None), |(c, t, m)| (Some(c), t, m)) } else { (r.to, r.tint, r.model) }; + if takes(r) { news.next().map_or((None, 1.0, None), |(c, t, m)| (Some(c), t, m)) } else { (r.to, r.tint, r.model) }; let mut row = json!({"from": r.from.iter().map(Match::to_json).collect::<Vec<_>>(), "to": to.as_ref().map(key_str)}); if r.exclude { row["exclude"] = json!(true); @@ -1776,6 +1819,9 @@ fn randomize(_: &mut Session, p: &Value) -> Result<Value> { if let Some(m) = model { row["model"] = json!(m.id()); } + if r.added { + row["added"] = json!(true); + } row }) .collect(); @@ -1938,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) } @@ -1979,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/select.rs b/crates/engine/src/cmd/select.rs index e5fa5f75b3..791aa47f39 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -82,19 +82,11 @@ pub fn specs() -> Vec<CommandSpec> { "Cancel Key Object", [], None, - "{id?: a selected top-level object (not a layer, a compound-path member or an object inside another selected object); one of two or more or the only one with ruler guides selected (the Selection tool: a click on one object of a selection of several, or of one with guides; on the key again: no id), guide?: index (a selected ruler guide, guide.list, with one or more objects selected: the Selection tool's click on a selected guide; Align lines the objects up on it and the guide stays put), anchor?: [subpath, anchor] with `id` the path (an anchor point selected with Direct Selection beside at least one other point becomes the key anchor: Align and Distribute move the other points relative to it and it stays put; select.anchors add or toggle of one point makes it the key anchor, as a Shift-click does)} the key object Align aligns to and Distribute Spacing spaces from; without `id` or `guide` it cancels the key, as does a selection that holds only the key and objects inside it (one object, or a group key and its own members) and no ruler guide, or a key guide with no object selected or taken out of the selection, or a key anchor that is deselected, deleted or left as the only selected point; any other id, guide or anchor is an error that leaves the key as it was → {key, guide?, keyAnchor?} (the resulting key object, or null; guide: the key guide, left out without one; keyAnchor: {id, anchor}, left out without one)", + "{id?: a selected top-level object (not a layer, a compound-path member or an object inside another selected object); one of two or more or the only one with ruler guides selected (the Selection tool: a click on one object of a selection of several, or of one with guides; on the key again: no id), guide?: index (a selected ruler guide, guide.list, with one or more objects selected: the Selection tool's click on a selected guide; Align lines the objects up on it and the guide stays put), anchor?: [subpath, anchor] with `id` the path (an anchor point selected with Direct Selection beside at least one other point becomes the key anchor: Align and Distribute move the other points relative to it and it stays put; a click without modifiers on an already-selected anchor point makes it the key anchor)} the key object Align aligns to and Distribute Spacing spaces from; without `id` or `guide` it cancels the key, as does a selection that holds only the key and objects inside it (one object, or a group key and its own members) and no ruler guide, or a key guide with no object selected or taken out of the selection, or a key anchor that is deselected, deleted or left as the only selected point; any other id, guide or anchor is an error that leaves the key as it was → {key, guide?, keyAnchor?} (the resulting key object, or null; guide: the key guide, left out without one; keyAnchor: {id, anchor}, left out without one)", has_doc, key ), - cmd!( - "select.anchors", - "Select Anchors", - [], - None, - "{id, anchors: [[subpath, anchor]…], mode: \"set\"|\"add\"|\"toggle\"}; add or toggle that selects one point makes it the key anchor while another point is selected too (see select.key)", - has_doc, - anchors - ), + cmd!("select.anchors", "Select Anchors", [], None, "{id, anchors: [[subpath, anchor]…], mode: \"set\"|\"add\"|\"toggle\"}", has_doc, anchors), cmd!( "select.segments", "Select Segments", @@ -734,17 +726,32 @@ fn key_anchor(s: &mut Session, id: Option<NodeId>, guide: Option<usize>, v: &Val let st = s.doc()?; let sel = &st.selection; let on_path = st.doc.node(id).and_then(|n| n.path_data()).is_some_and(|p| p.subpaths.get(r.0).is_some_and(|sp| r.1 < sp.anchors.len())); - if !on_path || sel.segments.contains_key(&id) || !sel.anchors.get(&id).is_some_and(|set| set.contains(&r)) { + let is_selected_anchor = on_path + && !sel.segments.contains_key(&id) + && (sel.anchors.get(&id).is_some_and(|set| set.contains(&r)) || (!sel.anchors.contains_key(&id) && sel.contains(id))); + if !is_selected_anchor { return Err(bad(C, format!("anchor [{}, {}] of object {id} is not a selected anchor point", r.0, r.1))); } // Check the new key on a copy first, so a request that fails leaves the key as it was. let mut trial = sel.clone(); + if !trial.anchors.contains_key(&id) + && let Some(p) = st.doc.node(id).and_then(|n| n.path_data()) + { + trial.anchors.insert(id, p.anchors().map(|(s, a, _)| (s, a)).collect()); + } trial.key_anchor = Some((id, r)); trial.prune(&st.doc); if trial.key_anchor.is_none() { return Err(bad(C, "select another anchor point to align to the key anchor")); } - s.select(|_, sel| sel.key_anchor = Some((id, r)))?; + s.select(|d, sel| { + if !sel.anchors.contains_key(&id) + && let Some(p) = d.node(id).and_then(|n| n.path_data()) + { + sel.anchors.insert(id, p.anchors().map(|(s, a, _)| (s, a)).collect()); + } + sel.key_anchor = Some((id, r)); + })?; key_result(s) } @@ -891,23 +898,15 @@ fn anchors(s: &mut Session, p: &Value) -> Result<Value> { if whole && let Some(path) = d.node(id).and_then(|n| n.path_data()) { e.extend(path.anchors().map(|(s, i, _)| (s, i))); } - // One point that add or toggle selects becomes the key anchor (a Shift-click with Direct - // Selection); `prune` drops it unless another point is selected too. - let single = refs.len() == 1; - let mut newest = None; for r in refs { if mode == "toggle" && e.contains(&r) { e.remove(&r); - } else if e.insert(r) && single { - newest = Some(r); + } else { + e.insert(r); } } if e.is_empty() { sel.remove(id); - } else if mode != "set" - && let Some(r) = newest - { - sel.key_anchor = Some((id, r)); } })?; ok() diff --git a/crates/engine/src/cmd/spelling.rs b/crates/engine/src/cmd/spelling.rs index 35d1a12774..cd8b4890f2 100644 --- a/crates/engine/src/cmd/spelling.rs +++ b/crates/engine/src/cmd/spelling.rs @@ -7,17 +7,20 @@ //! `removeWord`, `changeWord`), which every document's check takes as right; Ignore All //! (`text.spelling.ignoreAll`) skips a word in the active document only. -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; use std::ops::Range; use std::sync::atomic::{AtomicU64, Ordering}; use craft_proof::{IssueKind, Options, ProofLang}; use serde_json::{Value, json}; use vectorcraft_doc::{Document, NodeId, NodeKind, TextObject}; +use vectorcraft_text::edit; use super::menucmds::whole_or; +use super::textedit::text_mut; +use super::typecmd::refresh_bounds; use super::typemenu::{all_texts, text_ids}; -use super::{CommandSpec, Result, Session, always, bad, checked_ids_param, cmd, has_doc, str_param}; +use super::{CommandSpec, EngineError, Result, Session, always, bad, checked_ids_param, cmd, has_doc, str_param}; /// Most unknown words one check lists; past it the result says `more`. pub const MAX_WORDS: usize = 10_000; @@ -36,10 +39,19 @@ pub fn specs() -> Vec<CommandSpec> { "Check Spelling", [], None, - "{ids?: [id…] (type objects, or groups holding them; default: every visible, unlocked type object)} the words the dictionaries don't know, each in its run's language (English when it has none; none in a language without a dictionary), each paragraph on its own, in paint order (given ids too) → {words: [{id, start: byte, end: byte, word, lang}…], more: bool (more than 10000 words, the rest left out)}. text.editRange {id, start, end, insert} changes one", + "{ids?: [id…] (type objects, or groups holding them; default: every visible, unlocked type object), from?: {id, byte} (go on from there: the words of that type object that start at byte or later, then the objects after it; id must be one of the objects checked), max?: 1..10000 (default 10000)} the words the dictionaries don't know, each in its run's language (English when it has none; none in a language without a dictionary), each paragraph on its own, in paint order (given ids too) → {words: [{id, start: byte, end: byte, word, lang}…], more: bool (more than max words, the rest left out: check again with from {id, byte: end} of the last word)}. text.editRange {id, start, end, insert} changes one", has_doc, check ), + cmd!( + "text.spelling.change", + "Change All", + [], + None, + "{to: string, words: [{id, start: byte, end: byte}…] (words of type objects, as text.spelling.check lists them; none overlapping)} replaces each word with to, all in one undo step, each object laid out once (Check Spelling's Change All); a word that already reads as to is left alone, and with no other word there is no edit and no undo step; an error, with nothing changed, when a word's bytes are not in its object's text → {changed: count of words replaced}", + has_doc, + change_words + ), cmd!( query "text.spelling.suggest", "Spelling Suggestions", @@ -107,22 +119,42 @@ pub fn specs() -> Vec<CommandSpec> { } /// `text.spelling.check`: the unknown words of the given type objects (or every visible, unlocked -/// one), in paint order, each paragraph checked on its own, at most [`MAX_WORDS`] of them. +/// one), in paint order, each paragraph checked on its own, at most `max` of them, starting at +/// `from` when it is given. fn check(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.spelling.check"; // Given `ids` are checked like Find and Replace's, so a malformed one is an error rather than // a check of the whole document. - let ids = match p.get("ids").filter(|v| !v.is_null()) { + let mut ids = match p.get("ids").filter(|v| !v.is_null()) { Some(_) => in_paint_order(&s.doc()?.doc, text_ids(&s.doc()?.doc, &checked_ids_param(s, p, "ids", C)?)), None => all_texts(&s.doc()?.doc), }; + let max = whole_or(p, "max", MAX_WORDS as u64, C)?; + let max = usize::try_from(max).ok().filter(|m| (1..=MAX_WORDS).contains(m)).ok_or_else(|| bad(C, format!("`max` must be 1 to {MAX_WORDS}")))?; let st = s.doc()?; + // Where the last check stopped: the objects before it are skipped, and the bytes of its object + // before `byte`. + let mut from_byte = 0; + if let Some(from) = p.get("from").filter(|v| !v.is_null()) { + let (id, byte) = from_param(from, C)?; + let Some(pos) = ids.iter().position(|i| i.0 == id) else { + return Err(bad(C, format!("`from.id` {id} is not one of the type objects checked"))); + }; + let Some(NodeKind::Text(t)) = st.doc.node(NodeId(id)).map(|n| &n.kind) else { + return Err(bad(C, format!("`from.id` {id} is not a type object"))); + }; + let len = t.plain_text().len(); + from_byte = usize::try_from(byte).ok().filter(|b| *b <= len).ok_or_else(|| bad(C, format!("`from.byte` is past the end of {id}'s text")))?; + ids.drain(..pos); + } let mut words = vec![]; let mut more = false; for id in ids { let Some(NodeKind::Text(t)) = st.doc.node(id).map(|n| &n.kind) else { continue }; let text = t.plain_text(); - let (found, cut) = misspellings(t, &st.spelling_ignored, MAX_WORDS - words.len()); + // Only the first object listed starts part way. + let from = std::mem::take(&mut from_byte); + let (found, cut) = misspellings_from(t, &st.spelling_ignored, from, max - words.len()); for m in found { let Some(word) = text.get(m.range.clone()) else { continue }; words.push(json!({ "id": id.0, "start": m.range.start, "end": m.range.end, "word": word, "lang": m.lang.tag() })); @@ -135,6 +167,87 @@ fn check(s: &mut Session, p: &Value) -> Result<Value> { Ok(json!({ "words": words, "more": more })) } +/// `text.spelling.check`'s `from`: `{id, byte}`, both whole numbers. +fn from_param(from: &Value, command: &str) -> Result<(u64, u64)> { + let Some(o) = from.as_object() else { return Err(bad(command, "`from` must be {id, byte}")) }; + if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "id" | "byte")) { + return Err(bad(command, format!("`from` takes id and byte, not `{k}`"))); + } + let id = o.get("id").and_then(Value::as_u64).ok_or_else(|| bad(command, "`from.id` must be a type object's id"))?; + let byte = o.get("byte").and_then(Value::as_u64).ok_or_else(|| bad(command, "`from.byte` must be a whole number"))?; + Ok((id, byte)) +} + +/// `text.spelling.change`: Change All, every listed word replaced in one edit. Each object's words +/// are changed back to front, so the bytes of the ones before stay true, and the object is laid out +/// once at the end rather than once for each word. +fn change_words(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "text.spelling.change"; + let to = str_param(p, "to").ok_or_else(|| bad(C, "missing `to`"))?.to_string(); + let list = p.get("words").and_then(Value::as_array).ok_or_else(|| bad(C, "`words` must be a list of {id, start, end}"))?; + let mut by_id: BTreeMap<NodeId, Vec<(usize, usize)>> = BTreeMap::new(); + for w in list { + let (id, start, end) = word_param_range(w, C)?; + by_id.entry(NodeId(id)).or_default().push((start, end)); + } + // Every word checked against its object before anything changes. + let st = s.doc()?; + for (id, ranges) in &mut by_id { + let Some(NodeKind::Text(t)) = st.doc.node(*id).map(|n| &n.kind) else { + return Err(bad(C, format!("{} is not a type object", id.0))); + }; + let text = t.plain_text(); + ranges.sort_unstable(); + let mut last_end = 0; + for &(a, b) in ranges.iter() { + if a >= b || text.get(a..b).is_none() { + return Err(bad(C, format!("{a}..{b} is not a word of {}'s text", id.0))); + } + if a < last_end { + return Err(bad(C, format!("words of {} overlap at byte {a}", id.0))); + } + last_end = b; + } + // A word that already reads as `to` is left alone, so a list of only those makes no edit. + ranges.retain(|&(a, b)| text.get(a..b) != Some(to.as_str())); + } + by_id.retain(|_, ranges| !ranges.is_empty()); + let changed: usize = by_id.values().map(Vec::len).sum(); + if changed == 0 { + return Ok(json!({ "changed": 0 })); + } + s.edit("Change All", |d, _| { + for (id, ranges) in &by_id { + let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?; + for &(a, b) in ranges.iter().rev() { + // Paragraph styles and ruby follow each edit, as in `text.editRange`. + t.splice_paras(a, b, &to); + edit::replace_range(&mut t.runs, a, b, &to); + t.ruby_after_replace(a, b, to.len()); + } + refresh_bounds(t); + } + Ok(()) + })?; + Ok(json!({ "changed": changed })) +} + +/// One of `text.spelling.change`'s `words`: `{id, start, end}`, all whole numbers. +fn word_param_range(w: &Value, command: &str) -> Result<(u64, usize, usize)> { + let Some(o) = w.as_object() else { return Err(bad(command, "each of `words` must be {id, start, end}")) }; + if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "id" | "start" | "end")) { + return Err(bad(command, format!("each of `words` takes id, start and end, not `{k}`"))); + } + let id = o.get("id").and_then(Value::as_u64).ok_or_else(|| bad(command, "a word's `id` must be a type object's id"))?; + let byte = |k: &str| { + o.get(k) + .and_then(Value::as_u64) + .and_then(|b| usize::try_from(b).ok()) + .ok_or_else(|| bad(command, format!("a word's `{k}` must be a whole number"))) + }; + Ok((id, byte("start")?, byte("end")?)) +} + /// One word of a type object its dictionaries don't know ([`misspellings`]). #[derive(Clone, Debug, PartialEq)] pub struct Misspelling { @@ -149,6 +262,13 @@ pub struct Misspelling { /// All words). At most `max` of them; the flag says the list was cut short there. What /// `text.spelling.check` lists for one object, and what Auto Spell Check underlines. pub fn misspellings(t: &TextObject, ignored: &BTreeSet<String>, max: usize) -> (Vec<Misspelling>, bool) { + misspellings_from(t, ignored, 0, max) +} + +/// [`misspellings`] of the words that start at byte `from` or later. The paragraphs that end at +/// or before `from` are not checked; the paragraph that holds `from` is checked whole, since +/// craft-proof reads a paragraph's language from all of it. +pub fn misspellings_from(t: &TextObject, ignored: &BTreeSet<String>, from: usize, max: usize) -> (Vec<Misspelling>, bool) { let text = t.plain_text(); // Each run in its own language, at its bytes of the plain text. let mut spans: Vec<(Range<usize>, ProofLang)> = Vec::with_capacity(t.runs.len()); @@ -166,6 +286,11 @@ pub fn misspellings(t: &TextObject, ignored: &BTreeSet<String>, max: usize) -> ( let mut para_start = 0; for para in text.split('\n') { let para_end = para_start + para.len(); + // No word of a paragraph that ends at `from` starts there or later. + if para_end <= from { + para_start = para_end + 1; + continue; + } let para_spans: Vec<(Range<usize>, ProofLang)> = spans .iter() .filter_map(|(r, lang)| { @@ -178,6 +303,9 @@ pub fn misspellings(t: &TextObject, ignored: &BTreeSet<String>, max: usize) -> ( continue; } let (start, end) = (para_start + issue.start, para_start + issue.end); + if start < from { + continue; + } let Some(word) = text.get(start..end) else { continue }; if craft_proof::custom_word(word).is_some_and(|w| ignored.contains(&w)) { continue; diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index 09ae0b8e41..e8fb1349c3 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -22,7 +22,7 @@ pub fn specs() -> Vec<CommandSpec> { "Stroke Options", ["Window", "Stroke"], None, - "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take → {objects: how many objects took the stroke options}", + "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads → {objects: how many objects took the stroke options}", has_doc, stroke_set ), @@ -31,7 +31,7 @@ pub fn specs() -> Vec<CommandSpec> { "Stroke Weight Up", [], Some("Cmd+Alt+."), - "{ids?|id?} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke are left alone. With nothing selected (and no ids), the weight of the next object drawn. On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row for every label of its kind (docs/mcp.md) → {objects}", + "{ids?|id?} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke are left alone. With nothing selected (and no ids), the weight of the next object drawn. On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {objects}", has_doc, |s, p| stroke_step(s, p, true) ), @@ -234,8 +234,11 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> { let item = item_target(s, p, C)?.of_kind(s, false); let mut ids = if item == ItemTarget::Top { own_stroke_or_leaves(s, p)? } else { item.targets(s, p)? }; let new_art = no_targets(&ids, p); + let given = !ids.is_empty(); // The art of a graph design in a series keeps the design's stroke. - ids = super::appearance::drop_design_art(&s.doc()?.doc, ids); + ids = super::appearance::drop_design_art_rows(s, ids, item, false, C)?; + // With only design art, the weight for new art stays as it is too. + let only_design_art = given && ids.is_empty(); if item == ItemTarget::Top { // Images and symbol instances take no stroke from the panel. let d = &s.doc()?.doc; @@ -304,8 +307,10 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> { } }; let of = super::appearance::reference_of(s, p, item, C)?; - // The objects counted: with a design's art, those with a row equal to the art's. - let ids = edit_items(s, &ids, item, of, C, "Stroke", false, |n, index| { + // The objects counted: with a design's art, those with a row equal to the art's. A graph line keeps the weight + // given to it, also when it already showed it. + let writes = super::graph::RowWrites { weight: change.weight.is_some(), ..super::graph::RowWrites::NONE }; + let ids = super::appearance::edit_items_writing(s, &ids, item, of, C, "Stroke", false, writes, |n, index| { if index.is_none() && let NodeKind::Text(t) = &mut n.kind { @@ -329,7 +334,9 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> { })?; // Commit the new-art template only after the complete request is validated // and the selected artwork edit has succeeded. - if let Some(w) = change.weight { + if let Some(w) = change.weight + && !only_design_art + { s.paint.stroke_width = w; } if new_art && let Some(st) = s.new_art_stroke_mut() { @@ -372,7 +379,7 @@ fn stroke_step(s: &mut Session, p: &Value, up: bool) -> Result<Value> { } return Ok(json!({"objects": 0})); } - let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids); + let ids = super::appearance::drop_design_art_rows(s, ids, item, false, c)?; let label = if up { "Stroke Weight Up" } else { "Stroke Weight Down" }; edit_items(s, &ids, item, None, c, label, false, |n, index| { if index.is_none() @@ -517,7 +524,7 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result<Value> { let ids = item.targets(s, p)?; let new_art = no_targets(&ids, p); // The art of a graph design in a series keeps the design's stroke. - let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids); + let ids = super::appearance::drop_design_art_rows(s, ids, item, false, C)?; let arrows_and_profile = |st: &mut StrokeLayer| { if let Some(sc) = scale { st.arrow_scale = sc; diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 86019048f8..5780e65ed8 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -31,7 +31,7 @@ pub fn specs() -> Vec<CommandSpec> { "Apply Graphic Style", ["Window", "Graphic Styles"], None, - "{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores the label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}", + "{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows (with `add`: of the kinds of row the style shows) and, without `add`, its object opacity and blend mode for every label or line of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}", has_doc, style_apply ), @@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> { "New Graphic Style", ["Window", "Graphic Styles"], None, - "{name?, id?} a style from object `id` or the first selected object: its appearance, opacity, blend mode, isolate and knockout (a group without fills or strokes of its own lends its topmost object's, type its characters'; a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own stands for the topmost path directly in it; placed gradients are kept relative to its bounds); links the object, unless it is the art of a graph design in a series. Names are made unique → {name}", + "{name?, id?} a style from object `id` or the first selected object: its appearance, opacity, blend mode, isolate and knockout (a group without fills or strokes of its own lends its topmost object's, type its characters'; a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own stands for the topmost path directly in it, and a graph's Axes or Legend group with none of these for its topmost line or label; placed gradients are kept relative to its bounds); links the object, unless it is the art of a graph design in a series. Names are made unique → {name}", has_doc, style_new ), @@ -68,7 +68,7 @@ pub fn specs() -> Vec<CommandSpec> { "Redefine Graphic Style", ["Window", "Appearance"], None, - "{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it); the objects still linked to it update, and that object becomes linked. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores the label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {name}", + "{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it; a graph's Axes or Legend group: its topmost line or label); the objects still linked to it update, and that object becomes linked. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, a linked Axes group to its lines and labels and a linked Legend group to its labels, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}", has_doc, style_redefine ), @@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> { "Break Link to Graphic Style", ["Window", "Graphic Styles"], None, - "{ids?|id?, target?: \"object\"|\"contents\"} unlink the objects (default: the selection) from their graphic style; they keep their look. A graph series group's id stands for the group and the paths directly in it", + "{ids?|id?, target?: \"object\"|\"contents\"} unlink the objects (default: the selection) from their graphic style; they keep their look. A graph series group's id stands for the group and the paths directly in it, a graph's Axes group for the group and its lines and labels, and its Legend group for the group and its labels", has_doc, style_break_link ), @@ -364,6 +364,9 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> { let shows = |kind: bool| g.appearance.items.iter().any(|it| it.is_fill() == kind && it.visible()); let kinds = (shows(true), shows(false)); super::appearance::capture_series_writes(&before, d, &ids, kinds, kinds, false, false); + // A label or graph line keeps its new rows of those kinds for its kind. The other kind, the object opacity and + // the blend mode stay as the kind keeps them. + super::graph::capture_label_kind_rows(d, &ids, kinds, false); } else { d.graphic_style_id(i); let g = d.graphic_styles[i].clone(); @@ -373,9 +376,9 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> { } super::appearance::clear_stood_for(d, &groups); super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, true); + // A label or graph line keeps its new rows for its kind. + super::graph::capture_label_rows(d, &ids); } - // A label keeps its new rows for its kind of label. - super::graph::capture_label_rows(d, &ids); Ok(()) })?; ok() diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 8868143ef3..b43446af8b 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> { "Swatch Options", ["Window", "Swatches"], None, - "{name, newName?, color? (e.g. {l, a, b} for a Lab colour; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill; the swatch's own color and a color given with mode keep their model), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour), global?, spot? (spot colours are always global), paint?: paint.setFill params ({color}, {gradient} or {swatch}) or {pattern: name} replacing the swatch's colour; gradient or pattern with one of the same kind (stored as swatch.new stores it: a gradient keeps its aspect with or without start/end and holds no swatch link; a pattern is untransformed)} edit a swatch in any colour group, as one undo step. Fills, strokes, text, gradient stops and tint swatches linked to a global swatch take its new colour (at their own tint) and name; turning Global off unlinks them (they keep their colour). Colour, mode and spot apply to solid colours only; a tint swatch only takes a new name (edit its base) → {name, relinked: paints changed}", + "{name, newName?, color? (e.g. {l, a, b} for a Lab colour; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill; the swatch's own color and a color given with mode keep their model), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour), global?, spot? (spot colours are always global), paint?: paint.setFill params ({color}, {gradient} or {swatch}) or {pattern: name} replacing the swatch's colour; gradient or pattern with one of the same kind (stored as swatch.new stores it: a gradient keeps its aspect with or without start/end and holds no swatch link; a pattern is untransformed)} edit a swatch in any colour group, as one undo step. Fills, strokes, text, gradient stops and tint swatches linked to a global swatch take its new colour (at their own tint) and name; turning Global off unlinks them (they keep their colour). A fold line role the swatch carries (addon.packaging.roles) stays with it under its new name, and moves to a new swatch name when Global is turned off. Colour, mode and spot apply to solid colours only; a tint swatch only takes a new name (edit its base) → {name, relinked: paints changed}", has_doc, swatch_edit ), @@ -93,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> { "Merge Swatches", ["Window", "Swatches"], None, - "{names: [two or more solid-colour swatches], name?: the merged swatch's name (one swatch kept)} keep the first (its name and colour) and delete the others; paints linked to them take its colour and link to it (or unlink when it isn't global), and gradient stops linked to them drop their process plates, as one undo step → {name, merged: [deleted names], relinked}", + "{names: [two or more solid-colour swatches], name?: the merged swatch's name (one swatch kept)} keep the first (its name and colour) and delete the others; paints linked to them take its colour and link to it (or unlink when it isn't global), and gradient stops linked to them drop their process plates, as one undo step. When the kept swatch is global and carries no fold line role (addon.packaging.roles), it takes the role of the first merged swatch that carried one → {name, merged: [deleted names], relinked}", has_doc, swatch_merge ), @@ -937,6 +937,8 @@ fn swatch_edit(s: &mut Session, p: &Value) -> Result<Value> { } } let relinked = map_swatch_links(d, &mut |c, l, t| relink.apply(c, l, t)); + // A fold line role carried by the swatch follows its new name, as the strokes do. + super::addons::role_swatch_edited(d, &name, &to, global); super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?; Ok(relinked) })?; @@ -1139,6 +1141,8 @@ fn swatch_merge(s: &mut Session, p: &Value) -> Result<Value> { take_swatches(d, merged, |_| true); map_all_paints(d, &mut unplate); let relinked = map_swatch_links(d, &mut relink); + // The lines of a merged role swatch link to the kept swatch, which takes that role. + super::addons::role_swatches_merged(d, merged, keep, link.is_some()); super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?; Ok(relinked) })?; @@ -1251,43 +1255,54 @@ impl GroupEdit { } /// Rewrite colour group `group` with `colors`: its swatches take them in order (keeping their -/// names, kinds and global or spot flags), extra colours are added as new swatches and swatches -/// past the end are removed. Paints linked to its global swatches follow (a removed swatch's are -/// unlinked); `rename` renames the group. A built-in swatch (None, Registration) it would change or -/// remove is refused. -pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Color], rename: Option<&str>, cmd: &str) -> Result<GroupEdit> { +/// names, kinds and global or spot flags), a `None` removes the swatch at its place, extra colors +/// are added as new swatches and swatches past the end are removed. Paints linked to its global +/// swatches follow (a removed swatch's are unlinked); `rename` renames the group. A built-in swatch +/// (None, Registration) it would change or remove is refused. +pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Option<Color>], rename: Option<&str>, cmd: &str) -> Result<GroupEdit> { let gi = d.swatch_groups.iter().position(|g| g.name == group).ok_or_else(|| bad(cmd, format!("no colour group `{group}`")))?; let name = match rename.map(str::trim).filter(|n| !n.is_empty() && *n != group) { Some(n) => d.free_swatch_name(n), None => group.to_string(), }; let old = &d.swatch_groups[gi].swatches; - if let Some(w) = old.iter().enumerate().find(|(i, w)| w.is_reserved() && colors.get(*i).is_none_or(|c| w.paint.color() != Some(*c))).map(|x| x.1) + if let Some(w) = old + .iter() + .enumerate() + .find(|(i, w)| w.is_reserved() && colors.get(*i).copied().flatten().is_none_or(|c| w.paint.color() != Some(c))) + .map(|x| x.1) { return Err(bad(cmd, format!("`{}` can't be edited or removed", w.name))); } let colorized_ok = super::paint::check_colorized(d).is_ok(); let mut relinks = vec![]; - let mut swatches = std::mem::take(&mut d.swatch_groups[gi].swatches); - for gone in swatches.split_off(colors.len().min(swatches.len())) { - if gone.global { - relinks.push(Relink { from: gone.name.clone(), to: gone.name, color: None, keep: false }); + let old = std::mem::take(&mut d.swatch_groups[gi].swatches); + let old_len = old.len(); + // The swatches that stay, each with its new color. + let mut kept: Vec<(Swatch, Color)> = vec![]; + for (i, w) in old.into_iter().enumerate() { + match colors.get(i).copied().flatten() { + Some(c) => kept.push((w, c)), + None if w.global => relinks.push(Relink { from: w.name.clone(), to: w.name, color: None, keep: false }), + None => {} } } - for (w, c) in swatches.iter_mut().zip(colors) { - if w.paint.color() != Some(*c) { + let mut swatches = Vec::with_capacity(kept.len()); + for (mut w, c) in kept { + if w.paint.color() != Some(c) { // A tint swatch becomes a colour of its own. - w.paint = Paint::solid(*c); + w.paint = Paint::solid(c); if w.global { // Art linked to a Lab spot shows it as the Spot Colors options say. - relinks.push(Relink { from: w.name.clone(), to: w.name.clone(), color: Some(d.linked_color(*c, w.spot)), keep: true }); + relinks.push(Relink { from: w.name.clone(), to: w.name.clone(), color: Some(d.linked_color(c, w.spot)), keep: true }); } } + swatches.push(w); } let mut free = d.free_swatch_names(); free.insert(&name); swatches.iter().for_each(|w| free.insert(&w.name)); - for c in colors.iter().skip(swatches.len()) { + for c in colors.iter().skip(old_len).flatten() { let nm = free.take(&color_name(*c)); swatches.push(Swatch { name: nm, paint: Paint::solid(*c), global: false, spot: false }); } @@ -1316,6 +1331,7 @@ fn swatch_edit_group(s: &mut Session, p: &Value) -> Result<Value> { let colors: Vec<Color> = colors.into_iter().enumerate().map(|(i, c)| if old.get(i) == Some(&Some(c)) { c } else { super::paint::new_color(s, p, c) }).collect(); let rename = str_param(p, "rename"); + let colors: Vec<Option<Color>> = colors.into_iter().map(Some).collect(); let e = s.edit("Edit Color Group", |d, _| rewrite_group(d, group, &colors, rename, C))?; e.defaults(s)?; Ok(json!({"name": e.name, "swatches": e.swatches, "relinked": e.relinked})) diff --git a/crates/engine/src/cmd/symboledit.rs b/crates/engine/src/cmd/symboledit.rs index 606ab40fcf..77266b5aaa 100644 --- a/crates/engine/src/cmd/symboledit.rs +++ b/crates/engine/src/cmd/symboledit.rs @@ -495,7 +495,8 @@ pub(crate) fn sync(before: &Document, d: &mut Document) -> Result<()> { let (old, old_group) = match before.symbol_edit.as_ref().filter(|b| b.layer == se.layer) { None => return Ok(()), Some(b) => match art_of(before) { - Some(old) if same(&old) => return Ok(()), + // Turning on Align to Pixel Grid writes the art back too, so the layer shows it snapped. + Some(old) if same(&old) && (before.symbol_pixel_aligned(&se.symbol) || !d.symbol_pixel_aligned(&se.symbol)) => return Ok(()), old => (old.unwrap_or_default(), b.group), }, }; @@ -529,6 +530,24 @@ pub(crate) fn sync(before: &Document, d: &mut Document) -> Result<()> { }; d.symbols[index].art = Arc::new(new_art); follow_objects(d, &se.symbol, (&old, old_group), (&art, group)); + // A pixel-aligned symbol stores its art on the pixel grid while it is edited too, and the + // editing layer shows the snapped art. + if d.symbol_pixel_aligned(&se.symbol) && super::object::snap_symbol_art(d, &se.symbol) { + let stored = &d.symbols[index].art; + let snapped: Vec<Arc<Node>> = if group { stored.children().map(|c| c.to_vec()).unwrap_or_default() } else { vec![stored.clone()] }; + let mut snapped = snapped.into_iter().map(|n| { + let mut n = (*n).clone(); + n.transform(se.xf, false); + Arc::new(n) + }); + if let Some(ch) = d.node_mut(se.layer).and_then(Node::children_mut) { + for c in ch.iter_mut().filter(|c| !c.is_ruler_guide()) { + if let Some(n) = snapped.next() { + *c = n; + } + } + } + } if let Some(e) = d.symbol_edit.as_mut() { e.changed = true; e.group = group; diff --git a/crates/engine/src/cmd/symbollib.rs b/crates/engine/src/cmd/symbollib.rs index 63096c9d98..b82be77f43 100644 --- a/crates/engine/src/cmd/symbollib.rs +++ b/crates/engine/src/cmd/symbollib.rs @@ -499,12 +499,13 @@ fn instance(name: &str) -> Node { } /// Symbol `from`'s Symbol Options in `src` (natural size, registration, export type, 9-slice -/// guides) given to symbol `to` of `d`. +/// guides, Align to Pixel Grid) given to symbol `to` of `d`. fn copy_options(src: &Document, from: &str, d: &mut Document, to: &str) { set_natural_size(d, to, Some(natural_size(src, from))); d.set_symbol_registration(to, src.symbol_registration(from)); d.set_symbol_export_type(to, src.symbol_export_type(from)); d.set_symbol_nine_slice(to, src.symbol_nine_slice(from)); + d.set_symbol_pixel_aligned(to, src.symbol_pixel_aligned(from)); } fn builtin_info(b: &BuiltinSymbolLibrary) -> LibraryInfo { diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 769ca7e6c5..9079f7b892 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> { "Character", [], None, - "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away in horizontal type, the glyph keeping its shape; 100 sets the ink edge to edge; a character without ink, such as a space, keeps its width; a ligature or a letter with its marks takes the value of its first character; tracking, kerning and Insert Aki are added after it, and justification keeps it; vertical type keeps the characters' spacing; 0 by default; a value that is not a number or is outside the range is refused), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options: the characters are drawn in that form of the font, the OpenType feature trad, expt, jp04, jp90, jp78, jp83, fwid, hwid, twid or qwid, one form at a time; a character the font has no such glyph for keeps its own; \"default\", Revert To Default Forms, draws the font's default glyphs; a form other than \"default\" takes away the characters' glyph choice (text.setGlyphAlternate); with fullWidth, halfWidth, thirdWidth or quarterWidth, proportionalMetrics is kept but `palt` is not applied, and the font's pair kerning is turned off; another value is refused), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes), glyphAlternate?: null (takes away the glyph choice text.setGlyphAlternate made on the characters, in the same undo step as the other attributes; any other value is refused)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away, the glyph keeping its shape; 100 sets the ink edge to edge; a color glyph's ink is its color art or bitmap; a character without ink, such as a space, keeps its width; a ligature or a letter with its marks takes the value of its first character; tracking, kerning and Insert Aki are added after it, and justification keeps it; in vertical type an upright character is measured above and below its ink inside its cell down the column, a character lying on its side along its own width, and a tate-chu-yoko block's characters across the column, the block keeping its one em; 0 by default; a value that is not a number or is outside the range is refused), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options: the font's mark glyphs among the characters, those its GDEF table classes as marks such as Arabic harakat and Hebrew points, move right by a positive horizontal value and up by a positive vertical one, relative to their letters, in thousandths of the size; a harakat or Hebrew point styled apart from its letter takes its own values and stays attached to it, and another mark takes its letter's; letters and fonts without mark classes do not move; 0 by default; a value that is not a number or is outside the range is refused, naming the key), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options: the characters are drawn in that form of the font, the OpenType feature trad, expt, jp04, jp90, jp78, jp83, fwid, hwid, twid or qwid, one form at a time; a character the font has no such glyph for keeps its own; \"default\", Revert To Default Forms, draws the font's default glyphs; a form other than \"default\" takes away the characters' glyph choice (text.setGlyphAlternate); with fullWidth, halfWidth, thirdWidth or quarterWidth, proportionalMetrics is kept but `palt` is not applied, and the font's pair kerning is turned off; another value is refused), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes), glyphAlternate?: null (takes away the glyph choice text.setGlyphAlternate made on the characters, in the same undo step as the other attributes; any other value is refused)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_range_style ), @@ -470,6 +470,9 @@ pub(crate) struct CharChange { aki_right: Option<f64>, /// Tsume, in percent. tsume: Option<f64>, + /// Adjust Horizontal and Vertical Diacritic Position, in 1/1000 em. + diacritic_horizontal: Option<f64>, + diacritic_vertical: Option<f64>, standard_vertical_roman: Option<bool>, no_break: Option<bool>, digits: Option<vectorcraft_doc::Digits>, @@ -548,6 +551,16 @@ pub(crate) fn aki_param(p: &Value, key: &str, cmd: &str) -> Result<Option<f64>> if (lo..=hi).contains(&v) { Ok(Some(v)) } else { Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))) } } +/// `diacriticHorizontal` or `diacriticVertical` (Adjust Horizontal and Vertical Diacritic +/// Position): a number of thousandths of an em within +/// [`vectorcraft_doc::text::MAX_DIACRITIC_POSITION`] either way. Any other value is an error. +pub(crate) fn diacritic_param(p: &Value, key: &str, cmd: &str) -> Result<Option<f64>> { + let Some(v) = p.get(key).filter(|v| !v.is_null()) else { return Ok(None) }; + let v = v.as_f64().filter(|v| v.is_finite()).ok_or_else(|| bad(cmd, format!("`{key}` must be a number")))?; + let (lo, hi) = (-vectorcraft_doc::text::MAX_DIACRITIC_POSITION, vectorcraft_doc::text::MAX_DIACRITIC_POSITION); + if (lo..=hi).contains(&v) { Ok(Some(v)) } else { Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))) } +} + /// `tsume` (Tsume): a percentage from 0 to [`vectorcraft_doc::text::MAX_TSUME`]. Any other value is /// an error. pub(crate) fn tsume_param(p: &Value, cmd: &str) -> Result<Option<f64>> { @@ -852,6 +865,8 @@ impl CharChange { aki_left: aki_param(p, "akiLeft", cmd)?, aki_right: aki_param(p, "akiRight", cmd)?, tsume: tsume_param(p, cmd)?, + diacritic_horizontal: diacritic_param(p, "diacriticHorizontal", cmd)?, + diacritic_vertical: diacritic_param(p, "diacriticVertical", cmd)?, standard_vertical_roman: flag("standardVerticalRoman"), no_break: flag("noBreak"), digits: digits_param(p, cmd)?, @@ -918,6 +933,8 @@ impl CharChange { && self.aki_left.is_none() && self.aki_right.is_none() && self.tsume.is_none() + && self.diacritic_horizontal.is_none() + && self.diacritic_vertical.is_none() && self.standard_vertical_roman.is_none() && self.no_break.is_none() && self.digits.is_none() @@ -963,7 +980,8 @@ impl CharChange { } } - /// The character alignment, direction and East Asian settings of [`Self::apply`]. + /// The character alignment, direction, diacritic positions and East Asian settings of + /// [`Self::apply`]. fn apply_cjk(&self, st: &mut CharStyle) { if let Some(v) = self.char_align { st.char_align = v; @@ -1010,6 +1028,12 @@ impl CharChange { if let Some(v) = self.tsume { st.tsume = v; } + if let Some(v) = self.diacritic_horizontal { + st.diacritic_horizontal = v; + } + if let Some(v) = self.diacritic_vertical { + st.diacritic_vertical = v; + } if let Some(v) = self.standard_vertical_roman { st.standard_vertical_roman = v; } @@ -1806,6 +1830,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> { para: super::create::new_type_para(), paras: Vec::new(), first_para_continues: false, + first_para_lead: None, area: Default::default(), path_effect: Default::default(), path_align: Default::default(), @@ -2112,6 +2137,7 @@ fn headline_tracking(t: &TextObject, target: f64) -> Option<f64> { para: Default::default(), paras: Vec::new(), first_para_continues: false, + first_para_lead: None, area: Default::default(), path_effect: Default::default(), path_align: Default::default(), diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 18f87d44f7..e560c831cd 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -223,6 +223,8 @@ pub fn char_attrs(v: &CharStyle) -> Map<String, Value> { ("akiLeft", json!(v.aki_left)), ("akiRight", json!(v.aki_right)), ("tsume", json!(v.tsume)), + ("diacriticHorizontal", json!(v.diacritic_horizontal)), + ("diacriticVertical", json!(v.diacritic_vertical)), ("standardVerticalRoman", json!(v.standard_vertical_roman)), ("noBreak", json!(v.no_break)), ("digits", json!(v.digits)), @@ -253,6 +255,7 @@ pub fn para_attrs(v: &ParaStyle) -> Map<String, Value> { ("kinsoku", json!(v.kinsoku)), ("kinsoku_type", json!(v.kinsoku_type)), ("bunri_kinshi", json!(v.bunri_kinshi)), + ("kurikaeshi_moji_shori", json!(v.kurikaeshi_moji_shori)), ("roman_hanging", json!(v.roman_hanging)), ("kashida", json!(v.kashida)), ("korean_line_break_anywhere", json!(v.korean_line_break_anywhere)), @@ -513,6 +516,16 @@ pub(crate) fn style_attrs(d: &Document, para: bool, name: &str) -> Option<Map<St if para { Kind::Para } else { Kind::Char }.attrs(d, name) } +/// The fill of `[Normal Character Style]` in `d`: black, or the fill a redefinition gave it. New +/// type starts in that style ([Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html): +/// every character is in it by default; [FAQs on fonts](https://helpx.adobe.com/illustrator/using/fonts-faq.html): +/// new type's defaults are changed by editing it), so it takes this fill, not the current fill +/// left from the last shape (#7975). +pub(crate) fn normal_char_fill(d: &Document) -> vectorcraft_color::Paint { + let normal = Kind::Char.attrs(d, NORMAL_CHAR).unwrap_or_default(); + with_attrs(&CharStyle::default(), &normal, "text.create").map_or_else(|_| CharStyle::default().fill, |st| st.fill) +} + /// `attrs` in the form `charStyle.new` (`para`: `paraStyle.new`) stores them in `d`, or `None` /// when they don't pass its checks. pub(crate) fn stored_style_attrs(d: &Document, para: bool, attrs: &Map<String, Value>) -> Option<Map<String, Value>> { @@ -584,6 +597,13 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma if changed(key) && !(lo..=hi).contains(&st.tsume) { return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); } + let hi = vectorcraft_doc::text::MAX_DIACRITIC_POSITION; + let lo = -hi; + for (key, value) in [("diacriticHorizontal", st.diacritic_horizontal), ("diacriticVertical", st.diacritic_vertical)] { + if changed(key) && !(lo..=hi).contains(&value) { + return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); + } + } let lines = vectorcraft_doc::text::WARICHU_LINES; if changed("warichuLines") && !lines.contains(&st.warichu_lines) { return Err(bad(&c, format!("`warichuLines` must be a whole number from {} to {}", lines.start(), lines.end()))); @@ -1081,12 +1101,12 @@ fn unused(s: &mut Session, kind: Kind) -> Result<Value> { /// The styles of `kind` in `src` that load, with their source names so that art in the file keeps /// referring to them: not the Normal style, and not one whose attributes don't read, whose sizes, -/// scales, leading, shifts, Insert Aki, Tsume, Warichu Settings or stroke width are out of the range `charStyle.new` takes, whose +/// scales, leading, shifts, Insert Aki, Tsume, diacritic positions, Warichu Settings or stroke width are out of the range `charStyle.new` takes, whose /// indents, spacing, Hyphenation or Justification options or tab stops are out of the range /// `paraStyle.new` takes, or whose name is empty, which are skipped. → (the styles, the names in /// `src` of those skipped) fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) { - const RANGED: [&str; 22] = [ + const RANGED: [&str; 24] = [ "size", "h_scale", "v_scale", @@ -1095,6 +1115,8 @@ fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) { "akiLeft", "akiRight", "tsume", + "diacriticHorizontal", + "diacriticVertical", "tcyUpDown", "tcyLeftRight", "warichuLines", diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index b2ceb94508..e8f57aa14f 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -399,6 +399,8 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() { json!({"akiRight": 1000.1}), json!({"tsume": -0.1}), json!({"tsume": 100.1}), + json!({"diacriticHorizontal": -1000.1}), + json!({"diacriticVertical": 1000.1}), ] { let key = attrs.as_object().unwrap().keys().next().unwrap(); for cmd in ["charStyle.edit", "charStyle.setAttrs", "charStyle.new"] { @@ -422,7 +424,8 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() { "baseline_shift": -1296.0, "tcyUpDown": 1296.0, "tcyLeftRight": -1296.0, "akiLeft": 0.0, "akiRight": 1000.0, - "tsume": 100.0 + "tsume": 100.0, + "diacriticHorizontal": -1000.0, "diacriticVertical": 1000.0 }}), ) .unwrap(); diff --git a/crates/engine/src/cmd/threads.rs b/crates/engine/src/cmd/threads.rs index ad41d1d220..f4f807cb15 100644 --- a/crates/engine/src/cmd/threads.rs +++ b/crates/engine/src/cmd/threads.rs @@ -225,7 +225,9 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { .collect(); let refs: Vec<&TextObject> = frames.iter().collect(); let parts = vectorcraft_text::thread::distribute(vectorcraft_text::FontDb::global(), &refs, &story, ¶s); - for (id, part) in live.iter().zip(parts) { + let texts: Vec<String> = parts.iter().map(|p| p.runs.iter().map(|r| r.text.as_str()).collect()).collect(); + let leads = first_para_leads(&texts, &parts.iter().map(|p| p.continues).collect::<Vec<_>>()); + for ((id, part), lead) in live.iter().zip(parts).zip(leads) { if let Some(NodeKind::Text(t)) = doc.node_mut(*id).map(|n| &mut n.kind) { let mut next = (**t).clone(); next.runs = part.runs; @@ -241,6 +243,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { || part.list_count != t.list_count || part.list_level_counts != t.list_level_counts || continues != t.first_para_continues + || lead != t.first_para_lead { t.runs = next.runs; t.para = next.para; @@ -250,6 +253,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { t.list_count = part.list_count; t.list_level_counts = part.list_level_counts; t.first_para_continues = continues; + t.first_para_lead = lead; refresh_bounds(t); } } @@ -384,17 +388,42 @@ pub(crate) fn mark_continued(doc: &mut Document) { let live: Vec<NodeId> = thread.into_iter().filter(|id| text_of(doc, *id).is_some()).collect(); let frames: Vec<&TextObject> = live.iter().filter_map(|id| text_of(doc, *id)).collect(); let marks = vectorcraft_text::thread::continued(&frames); - for (id, on) in live.iter().zip(marks) { + let texts: Vec<String> = frames.iter().map(|t| t.plain_text()).collect(); + let leads = first_para_leads(&texts, &marks); + for ((id, on), lead) in live.iter().zip(marks).zip(leads) { if let Some(NodeKind::Text(t)) = doc.node_mut(*id).map(|n| &mut n.kind) - && t.first_para_continues != on + && (t.first_para_continues != on || t.first_para_lead != lead) { t.first_para_continues = on; + t.first_para_lead = lead; refresh_bounds(t); } } } } +/// [`TextObject::first_para_lead`] for each frame of a thread, from the frames' plain `texts` and +/// whether each one's first paragraph `continues` from the frame before: the last character of +/// that paragraph in the frames before that a repeat mark could stand for, or None. One pass over +/// the frames: each frame's lead is carried forward to the next. +fn first_para_leads(texts: &[String], continues: &[bool]) -> Vec<Option<char>> { + // The lead the next frame takes when its first paragraph continues from this one. + let mut carry = None; + texts + .iter() + .enumerate() + .map(|(k, text)| { + #[cfg(test)] + LEAD_SCANS.with(|c| c.set(c.get() + 1)); + let lead = carry.filter(|_| continues.get(k) == Some(&true)); + let tail = text.rsplit('\n').next().unwrap_or(text); + // A paragraph break in this frame ends the paragraph the lead came from. + carry = vectorcraft_text::repeat_base(tail).or(lead.filter(|_| tail.len() == text.len())); + lead + }) + .collect() +} + #[cfg(test)] thread_local! { /// Tests: how many times [`story_of`] and [`ThreadIndex::of`] went through the document's @@ -402,6 +431,8 @@ thread_local! { static THREAD_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; /// Tests: how many times [`story_in`] went through a thread's frames on this thread. static STORY_BUILDS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; + /// Tests: how many frame texts [`first_para_leads`] went through on this thread. + static LEAD_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; } /// Tests: how many times [`story_of`] and [`ThreadIndex::of`] have gone through the document's @@ -417,6 +448,12 @@ pub(crate) fn story_builds() -> usize { STORY_BUILDS.with(std::cell::Cell::get) } +/// Tests: how many frame texts [`first_para_leads`] has gone through on this thread. +#[cfg(test)] +pub(crate) fn lead_scans() -> usize { + LEAD_SCANS.with(std::cell::Cell::get) +} + /// The frames of the thread that `id` is a frame of, in thread order, each area type or type on a /// path; empty when `id` is in no thread or the thread has fewer than two such frames. pub(crate) fn story_of(d: &Document, id: NodeId) -> Vec<NodeId> { diff --git a/crates/engine/src/cmd/threads/tests.rs b/crates/engine/src/cmd/threads/tests.rs index 2694a61e6c..82ac2f9f76 100644 --- a/crates/engine/src/cmd/threads/tests.rs +++ b/crates/engine/src/cmd/threads/tests.rs @@ -2226,3 +2226,57 @@ fn paragraph_indents_check_every_entry_and_skip_a_change_that_changes_nothing() assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); assert_eq!(text_of(&s.doc().unwrap().doc, NodeId(c)).unwrap().para_at(1).left_indent, 30.0); } + +/// Kurikaeshi Moji Shori: a frame whose first paragraph continues carries the last character of +/// that paragraph in the frames before that a repeat mark can stand for, looking past frames that +/// hold only repeat marks and stopping at the paragraph's start; a frame that starts a paragraph +/// carries none. Flowing the story and opening a file both set it. +#[test] +fn a_continued_frame_carries_the_character_a_repeat_mark_stands_for() { + let leads = |texts: &[&str], continues: &[bool]| first_para_leads(&texts.iter().map(|t| t.to_string()).collect::<Vec<_>>(), continues); + assert_eq!(leads(&["時", "々す"], &[false, true]), [None, Some('時')]); + assert_eq!(leads(&["時", "々", "々"], &[false, true, true]), [None, Some('時'), Some('時')]); + assert_eq!(leads(&["時\nか\u{3099}", "ゝ"], &[false, true]), [None, Some('か')]); + assert_eq!(leads(&["時\n々", "々"], &[false, true]), [None, None]); + assert_eq!(leads(&["時\n", "々"], &[false, false]), [None, None]); + assert_eq!(leads(&[], &[]), Vec::<Option<char>>::new()); + // Opening a file marks the frames as they were saved. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap(); + let mut ids = Vec::new(); + for (x, text) in [(10, "日時"), (200, "々す")] { + let id = + s.execute("text.create", &json!({"x": x, "y": 10, "text": text, "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap(); + ids.push(NodeId(id)); + } + let mut d = (*s.doc().unwrap().doc).clone(); + d.text_threads = vec![ids.clone()]; + mark_continued(&mut d); + let tb = text_of(&d, ids[1]).unwrap(); + assert!(tb.first_para_continues); + assert_eq!(tb.first_para_lead, Some('時')); + // Flowing the story through the frames sets it from the text each frame now holds. + reflow(&d.clone(), &mut d); + let (ta, tb) = (text_of(&d, ids[0]).unwrap(), text_of(&d, ids[1]).unwrap()); + assert_eq!([ta.plain_text(), tb.plain_text()].concat(), "日時々す"); + assert!(tb.first_para_continues); + assert_eq!(tb.first_para_lead, vectorcraft_text::repeat_base(&ta.plain_text())); +} + +/// Kurikaeshi Moji Shori: the leads of a thread whose frames hold only repeat marks come from one +/// pass over the frames, each frame's text gone through once, not once for every frame after it. +#[test] +fn continued_frame_leads_go_through_each_frame_once() { + let n = 2000; + let mut texts = vec!["時".to_string()]; + texts.extend(std::iter::repeat_n("々\u{2028}".to_string(), n - 1)); + let continues: Vec<bool> = (0..n).map(|k| k > 0).collect(); + let before = lead_scans(); + let leads = first_para_leads(&texts, &continues); + assert!(lead_scans() - before <= n, "{} frame texts gone through for {n} frames", lead_scans() - before); + assert_eq!(leads.first(), Some(&None)); + assert!(leads.iter().skip(1).all(|l| *l == Some('時'))); + // A paragraph break stops the carry, and a frame that starts a paragraph carries nothing. + let leads = first_para_leads(&["時".into(), "々\nす".into(), "々".into(), "日".into(), "々".into()], &[false, true, true, false, true]); + assert_eq!(leads, [None, Some('時'), Some('す'), None, Some('日')]); +} diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index b92f70e910..c239cf040e 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> { "Create Outlines", ["Type"], Some("Cmd+Shift+O"), - "{} convert the selected text to groups of compound paths (one per glyph); the type object's own fills and strokes (not its characters') go on paths of its whole outline, below or above the glyphs as its Characters row places them; the group keeps the object's transparency, opacity mask and effects, once; a frame of threaded text leaves its thread with the text it shows; a dimension whose label is outlined becomes a plain group of its art → {ids}", + "{} convert the selected text to groups of compound paths (one per glyph); on type scaled unevenly, sheared or flattened, each glyph's stroke becomes a filled path over it, shaped as the canvas strokes it; the type object's own fills and strokes (not its characters') go on paths of its whole outline, below or above the glyphs as its Characters row places them; the group keeps the object's transparency, opacity mask and effects, once; a frame of threaded text leaves its thread with the text it shows; a dimension whose label is outlined becomes a plain group of its art → {ids}", has_selection, create_outlines ), @@ -619,16 +619,25 @@ fn scale_text_attributes(s: &mut Session, p: &Value) -> Result<Value> { /// A path (or compound path) of `outline`, a piece of type `t`'s outline in text space, painted as /// run `run` and placed in the document as the canvas paints it ([`paint_type_piece`]: unplaced /// gradients fitted to `bounds`, the layout's bounds, stroke weights scaled by the type's -/// transform); `None` when the piece has no path. -fn type_piece(d: &mut Document, t: &TextObject, bounds: kurbo::Rect, run: usize, outline: &kurbo::BezPath) -> Option<Node> { +/// transform), followed by a path (or compound path) filled with the run's stroke when the type's +/// transform is not a similarity; empty when the piece has no path. +fn type_piece(d: &mut Document, t: &TextObject, bounds: kurbo::Rect, run: usize, outline: &kurbo::BezPath) -> Vec<Node> { let path = PathData::from_bezpath(outline); if path.is_empty() { - return None; + return vec![]; } let st = t.runs.get(run).map(|r| r.style.clone()).unwrap_or_else(|| t.first_style()); let mut node = shape_node(d, path, None); - vectorcraft_render::effects::paint_type_piece(&mut node, &st, bounds, t.xf); - Some(node) + let stroke = vectorcraft_render::effects::paint_type_piece(&mut node, &st, bounds, t.xf); + let mut out = vec![node]; + if let Some(s) = stroke + && let Some(path) = s.path_data() + { + let mut filled = shape_node(d, path.clone(), None); + filled.appearance = s.appearance.clone(); + out.push(filled); + } + out } fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> { @@ -675,9 +684,7 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> { children.push(Arc::new(d.reid(&art))); break 'glyph; } - if let Some(node) = type_piece(d, t, lay.bounds, g.run, &g.outline) { - children.push(Arc::new(node)); - } + children.extend(type_piece(d, t, lay.bounds, g.run, &g.outline).into_iter().map(Arc::new)); } run_end.insert(g.run, children.len()); } @@ -686,10 +693,9 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> { // nothing there either). let mut ruby: Vec<(usize, Arc<Node>)> = vec![]; for g in &lay.ruby { - let Some(node) = type_piece(d, t, lay.bounds, g.run, &g.outline) else { continue }; // After the glyphs of its run and of the runs before it. let at = run_end.range(..=g.run).map(|(_, end)| *end).max().unwrap_or(0); - ruby.push((at, Arc::new(node))); + ruby.extend(type_piece(d, t, lay.bounds, g.run, &g.outline).into_iter().map(|node| (at, Arc::new(node)))); } ruby.sort_by_key(|(at, _)| *at); let mut ruby = ruby.into_iter().peekable(); @@ -711,9 +717,7 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> { // Underline and strikethrough bars become paths of their run's paint too (#847). for (run, bar) in vectorcraft_text::decorations(&lay, vectorcraft_text::FontDb::global(), t) { all.extend(bar.iter()); - if let Some(node) = type_piece(d, t, lay.bounds, run, &bar) { - children.push(Arc::new(node)); - } + children.extend(type_piece(d, t, lay.bounds, run, &bar).into_iter().map(Arc::new)); } // The object's own fills and strokes (not its characters') paint the whole outline: // those below the Characters row under the characters, the others over them, with @@ -1034,7 +1038,17 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> { // not in a scaled label's own units). let mut labels_changed = false; if range.is_none() { - labels_changed = super::graph::capture_label_styles(d, &ids, &|st| { + let gives_character = font.is_some() + || style.is_some() + || size.is_some() + || leading.is_some() + || tracking.is_some() + || fill.is_some() + || stroke.is_some() + || !stroke_weight.is_empty() + || features.is_some() + || feature_changes.as_ref().is_some_and(|c| !c.is_empty()); + let change = |st: &mut vectorcraft_doc::CharStyle| { if let Some(f) = &font { st.font_family = f.clone(); st.font_version = None; @@ -1075,7 +1089,13 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> { if let Some(c) = &feature_changes { st.features = super::textedit::change_features(&st.features, c); } - }); + }; + // A command that gives character attributes keeps the style even when they equal the labels' own. + labels_changed = if gives_character { + super::graph::capture_label_styles_given(d, &ids, &change) + } else { + super::graph::capture_label_styles(d, &ids, &change) + }; } Ok(((), labels_changed)) })?; diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index a63ebff9c4..aa6b75032d 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -504,6 +504,62 @@ fn bunri_kinshi_is_set_per_paragraph_and_saved_only_when_on() { assert!(!text(&s).para_at(0).bunri_kinshi && !text(&s).para_at(1).bunri_kinshi); } +/// Paragraph panel menu › Kurikaeshi Moji Shori: off for new type and for a paragraph saved before +/// it, and saved only when on; `text.setFormat {kurikaeshiMojiShori}` sets it per paragraph in one +/// undo step, records nothing when the paragraphs already have the value, refuses a value that is +/// not true or false, and paragraph styles carry it. The text keeps its repeat marks. +#[test] +fn kurikaeshi_moji_shori_is_set_per_paragraph_and_saved_only_when_on() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 10, "size": 20, "text": "時々\nすゝ"})).unwrap()["id"].as_u64().unwrap(); + let text = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("text"), + }; + assert!(!text(&s).para_at(0).kurikaeshi_moji_shori, "new type has it off"); + assert!(serde_json::to_value(text(&s).para_at(0)).unwrap().get("kurikaeshi_moji_shori").is_none()); + let old: vectorcraft_doc::ParaStyle = serde_json::from_value(json!({"justify": "Left"})).unwrap(); + assert!(!old.kurikaeshi_moji_shori, "saved before the option: off"); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + // Only the second paragraph. + let second = "時々\n".len(); + s.execute("text.setFormat", &json!({"kurikaeshiMojiShori": true, "start": second, "end": second})).unwrap(); + assert!(!text(&s).para_at(0).kurikaeshi_moji_shori && text(&s).para_at(1).kurikaeshi_moji_shori); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + assert_eq!(text(&s).plain_text(), "時々\nすゝ", "the text keeps its marks"); + // The same value again records nothing. + s.execute("text.setFormat", &json!({"kurikaeshiMojiShori": true, "start": second, "end": second})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + let saved = serde_json::to_value(text(&s).para_at(1)).unwrap(); + assert_eq!(saved["kurikaeshi_moji_shori"], true); + let back: vectorcraft_doc::ParaStyle = serde_json::from_value(saved).unwrap(); + assert!(back.kurikaeshi_moji_shori); + let reopened = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let Some(NodeKind::Text(back)) = reopened.node(NodeId(id)).map(|n| &n.kind) else { panic!("text") }; + assert!(!back.para_at(0).kurikaeshi_moji_shori && back.para_at(1).kurikaeshi_moji_shori, "the file keeps it per paragraph"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!text(&s).para_at(1).kurikaeshi_moji_shori); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(text(&s).para_at(1).kurikaeshi_moji_shori); + for bad in [json!("yes"), json!(1)] { + assert!(s.execute("text.setFormat", &json!({"ids": [id], "kurikaeshiMojiShori": bad, "kinsoku": "none"})).is_err(), "{bad}"); + } + assert!(s.execute("text.setRangeStyle", &json!({"id": id, "kurikaeshiMojiShori": false})).is_err()); + assert!( + text(&s).para_at(1).kurikaeshi_moji_shori && text(&s).para_at(1).kinsoku != vectorcraft_doc::Kinsoku::None, + "a refused call changes nothing" + ); + // A paragraph style carries it. + s.execute("paraStyle.new", &json!({"name": "Repeats", "attrs": {"kurikaeshi_moji_shori": true}})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": "Repeats", "id": id})).unwrap(); + assert!(text(&s).para_at(0).kurikaeshi_moji_shori && text(&s).para_at(1).kurikaeshi_moji_shori); + s.execute("paraStyle.new", &json!({"name": "Marks", "attrs": {"kurikaeshi_moji_shori": false}})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": "Marks", "id": id})).unwrap(); + assert!(!text(&s).para_at(0).kurikaeshi_moji_shori && !text(&s).para_at(1).kurikaeshi_moji_shori); +} + /// Paragraph panel › Insert Kashidas: `text.setFormat {kashida}` sets it per paragraph in one /// undo step, the paragraph is saved with it only when it is not None and opens with it, an /// unknown value changes nothing, and paragraph styles carry it. @@ -1921,6 +1977,66 @@ fn tsume_is_a_character_attribute() { assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step for a refused call"); } +/// Adjust Horizontal and Vertical Diacritic Position (Character panel, Middle Eastern options): +/// character attributes in thousandths of an em, 0 by default and saved only when not 0. Both +/// commands set them in one undo step, setting one leaves the other, a call that gives the values +/// the text already has records none, and a value that is not a number or lies outside -1000 to +/// 1000 is refused, naming the key, before anything changes; the native file and a character style +/// captured from the characters carry them. +#[test] +fn diacritic_positions_are_character_attributes() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "بَب"})).unwrap()["id"].as_u64().unwrap(); + let runs = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.runs.clone(), + _ => panic!("text"), + }; + let moved = |s: &Session| runs(s).iter().map(|r| (r.text.clone(), r.style.diacritic_horizontal, r.style.diacritic_vertical)).collect::<Vec<_>>(); + let saved = serde_json::to_value(&runs(&s)[0].style).unwrap(); + assert!(saved.get("diacriticHorizontal").is_none() && saved.get("diacriticVertical").is_none()); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("text.setFormat", &json!({"diacriticHorizontal": -150})).unwrap(); + s.execute("text.setFormat", &json!({"diacriticVertical": 250})).unwrap(); + assert_eq!(moved(&s), [("بَب".to_string(), -150.0, 250.0)], "setting one leaves the other"); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("text.setFormat", &json!({"diacriticHorizontal": -150, "diacriticVertical": 250})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step without a change"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(moved(&s), [("بَب".to_string(), -150.0, 0.0)], "one undo step"); + s.execute("edit.redo", &json!({})).unwrap(); + + let mark = "بَ".len(); + s.execute("text.setRangeStyle", &json!({"id": id, "start": "ب".len(), "end": mark, "diacriticVertical": -1000})).unwrap(); + assert_eq!(moved(&s), [("ب".to_string(), -150.0, 250.0), ("\u{064E}".to_string(), -150.0, -1000.0), ("ب".to_string(), -150.0, 250.0)]); + let saved = serde_json::to_value(&runs(&s)[1].style).unwrap(); + assert_eq!((saved["diacriticHorizontal"].clone(), saved["diacriticVertical"].clone()), (json!(-150.0), json!(-1000.0))); + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") }; + let reopened: Vec<_> = t.runs.iter().map(|r| (r.text.clone(), r.style.diacritic_horizontal, r.style.diacritic_vertical)).collect(); + assert_eq!(reopened, moved(&s)); + let attrs = super::super::textstyles::char_attrs(&runs(&s)[1].style); + assert_eq!((attrs["diacriticHorizontal"].clone(), attrs["diacriticVertical"].clone()), (json!(-150.0), json!(-1000.0))); + + let before = moved(&s); + let undo = s.doc().unwrap().history.undo.len(); + for (cmd, p, want) in [ + ("text.setFormat", json!({"diacriticHorizontal": "50"}), "`diacriticHorizontal` must be a number"), + ("text.setFormat", json!({"diacriticVertical": 1000.5}), "`diacriticVertical` must be from -1000 to 1000"), + ("text.setRangeStyle", json!({"id": id, "diacriticVertical": true}), "`diacriticVertical` must be a number"), + ( + "text.setRangeStyle", + json!({"id": id, "start": 0, "end": mark, "diacriticHorizontal": -1001}), + "`diacriticHorizontal` must be from -1000 to 1000", + ), + ] { + let e = s.execute(cmd, &p).unwrap_err(); + assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg == want), "{cmd} {p}: {e}"); + } + assert_eq!(moved(&s), before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step for a refused call"); +} + /// Standard Vertical Roman Alignment (Character panel menu, East Asian options): a character /// attribute, off by default and saved only when on. Documents written before it read as off; a /// character style captured from the characters carries it. diff --git a/crates/engine/src/cmd/typecmd/noop_tests.rs b/crates/engine/src/cmd/typecmd/noop_tests.rs index 02481d8bee..b4f5cb2099 100644 --- a/crates/engine/src/cmd/typecmd/noop_tests.rs +++ b/crates/engine/src/cmd/typecmd/noop_tests.rs @@ -102,6 +102,34 @@ fn a_kept_graph_label_style_change_alone_records_one_undo_step() { records_nothing(&mut s, "text.setStyle", p); } +/// `text.setStyle` on a graph label with only `justify`, which the label already has, records no undo step and keeps no +/// character style for its kind of label. +#[test] +fn a_justify_only_style_change_on_a_graph_label_records_nothing() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4"; + let graph = NodeId( + s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + let doc = s.doc().unwrap().doc.clone(); + let legend = doc.node(graph).unwrap().children().unwrap().iter().find(|c| c.name.as_deref() == Some("Legend")).unwrap(); + let label = legend + .children() + .unwrap() + .iter() + .find_map(|c| match &c.kind { + NodeKind::Text(t) if t.plain_text() == "2025" => Some(c.id), + _ => None, + }) + .unwrap(); + records_nothing(&mut s, "text.setStyle", json!({"ids": [label.0], "justify": "left"})); + let kept = s.doc().unwrap().doc.node(graph).unwrap().extras().graph.as_deref().unwrap().label_styles.legend.clone(); + assert!(kept.is_none(), "the legend keeps a style"); +} + /// `text.setText` with the text the type already has records no undo step; new text records one. #[test] fn the_same_text_records_no_undo_step() { diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index 0701f6eeca..da930d7e59 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -1783,6 +1783,13 @@ fn strip_formatting(n: &mut vectorcraft_doc::Node) { fn paste_plain(s: &mut Session, p: &Value) -> Result<Value> { let saved = s.clipboard.nodes.clone(); + // Pasted colors linked to a swatch merged with the document's show its color, so a pasted pie's legend labels take + // the contrast of the wedges as pasted. A `swatchConflict` the paste refuses is left to its error. + if let (Ok(choices), Ok(st)) = (super::clipboard::SwatchChoices::parse("edit.pasteWithoutFormatting", p), s.doc()) { + let same_doc = s.clipboard.source_doc == Some(st.uid); + let d = std::sync::Arc::clone(&st.doc); + s.clipboard.show_merged_colors(&d, &choices, same_doc); + } for n in &mut s.clipboard.nodes { strip_formatting(n); } diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index 8e58132ce0..229aa1db3a 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -11,6 +11,7 @@ //! visibility, `@` for image, no prefix for text). `variable.loadLibrary` replaces the variables and data sets with the //! variables and data sets of a variable library, the XML file of the reference app's Save //! Variable Library, and `variable.saveLibrary` writes the variables and data sets as one. +//! `variable.import` (the panel's Import…) runs one of the two readers by the file's extension. //! Agents reach every command through `run_command`, like all engine commands. use std::collections::{BTreeMap, BTreeSet}; @@ -865,6 +866,22 @@ fn dataset_step(s: &mut Session, cmd: &str, forward: bool) -> Result<Value> { apply_dataset(s, &name) } +/// The Variables panel's Import…: a data source file read by its extension, a CSV, TSV or TXT +/// file as `dataset.import` reads it and an XML file as `variable.loadLibrary` reads it. The +/// result is that command's, with `format` set to `csv` or `xml`. +fn variable_import(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "variable.import"; + let path = str_param(p, "path").ok_or_else(|| bad(C, "missing `path`"))?; + let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase); + let (format, mut out) = match ext.as_deref() { + Some("csv" | "tsv" | "txt") => ("csv", dataset_import(s, &json!({"path": path}))?), + Some("xml") => ("xml", load_library(s, &json!({"path": path}))?), + _ => return Err(bad(C, "Import reads a data source file ending in .csv, .tsv, .txt or .xml")), + }; + out["format"] = json!(format); + Ok(out) +} + pub fn specs() -> Vec<CommandSpec> { vec![ cmd!( @@ -1057,6 +1074,15 @@ pub fn specs() -> Vec<CommandSpec> { has_doc, dataset_import ), + cmd!( + "variable.import", + "Import…", + ["Window", "Variables"], + None, + "{path} import a data source file, chosen by its extension (any case): a .csv, .tsv or .txt file is read as dataset.import reads it, and an .xml file as variable.loadLibrary reads it, with their refusals and undo steps; any other extension, or none, is refused before the file is read → the result of that command with `format`: `csv` or `xml`", + has_doc, + variable_import + ), cmd!( query "dataset.export", "Export Data Sets…", diff --git a/crates/engine/src/cmd/variablecmds/library.rs b/crates/engine/src/cmd/variablecmds/library.rs index 2392a80ee4..ceab798373 100644 --- a/crates/engine/src/cmd/variablecmds/library.rs +++ b/crates/engine/src/cmd/variablecmds/library.rs @@ -60,8 +60,8 @@ fn library_bytes(p: &Value, cmd: &str) -> Result<Vec<u8>> { /// up to [`MAX_LIBRARY_ENTITIES`] entity declarations, each with a name of at most [`MAX_NAME`] /// bytes and a quoted value that holds no `<`, `&` or `%`. Anything else in it is refused, and so is /// a text that the replacements make longer than [`MAX_LIBRARY_BYTES`]. The XML parser then refuses -/// any other document type declaration, so [`nesting`](super::place::docx::nesting) counts the -/// elements the parser reads. +/// any other document type declaration, so its depth and node limits count the elements it +/// reads. fn without_doctype(xml: &str, cmd: &str) -> Result<String> { let b = xml.as_bytes(); let past = |from: usize, end: &str| xml.get(from..).and_then(|rest| rest.find(end)).map(|at| from + at + end.len()); @@ -240,22 +240,25 @@ impl Library { /// type declaration defines are read as [`without_doctype`] says. fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result<Library> { let xml = without_doctype(xml, cmd)?; - // roxmltree parses nested elements recursively. - if crate::cmd::place::docx::nesting(&xml) > MAX_LIBRARY_NESTING { - return Err(bad(cmd, format!("the variable library nests elements more than {MAX_LIBRARY_NESTING} deep"))); + let opts = craft_xml::Options { + names: craft_xml::Names::AsWritten, + limits: craft_xml::Limits { max_depth: MAX_LIBRARY_NESTING, max_nodes: MAX_LIBRARY_NODES as usize, ..craft_xml::Limits::DEFAULT }, + ..craft_xml::Options::default() } - let opts = roxmltree::ParsingOptions { nodes_limit: MAX_LIBRARY_NODES, ..roxmltree::ParsingOptions::default() }; - let doc = - roxmltree::Document::parse_with_options(&xml, opts).map_err(|e| bad(cmd, format!("the variable library is not well-formed XML: {e}")))?; - let is = |n: &roxmltree::Node, name: &str| n.is_element() && n.tag_name().name() == name; - let Some(root) = doc.descendants().find(|n| is(n, "variableSets")) else { + .strict(); + let doc = opts.parse(xml.as_bytes()).map_err(|e| match e { + craft_xml::Error::TooDeep(_) => bad(cmd, format!("the variable library nests elements more than {MAX_LIBRARY_NESTING} deep")), + _ => bad(cmd, format!("the variable library is not well-formed XML: {e}")), + })?; + crate::cmd::xmlattrs::validate(xml.as_bytes(), opts.limits).map_err(|e| bad(cmd, format!("the variable library is not well-formed XML: {e}")))?; + let Some(root) = std::iter::once(&doc).chain(doc.descendants()).find(|n| n.is(craft_xml::Local("variableSets"))) else { return Err(bad(cmd, "the file holds no `variableSets` element")); }; - let sets: Vec<roxmltree::Node> = root.children().filter(|n| is(n, "variableSet")).collect(); + let sets: Vec<&craft_xml::El> = root.children(craft_xml::Local("variableSet")).collect(); let (mut variables, mut kinds, mut refs) = (Vec::new(), BTreeMap::new(), Vec::new()); - for var in sets.iter().flat_map(|s| s.children()).filter(|n| is(n, "variables")).flat_map(|v| v.children()).filter(|n| is(n, "variable")) { - let name = named(var.attribute("varName"), "varName", cmd)?; - let trait_name = var.attribute("trait").map(|t| t.chars().take(MAX_NAME).collect::<String>()); + for var in sets.iter().flat_map(|s| s.children(craft_xml::Local("variables"))).flat_map(|v| v.children(craft_xml::Local("variable"))) { + let name = named(var.attr("varName"), "varName", cmd)?; + let trait_name = var.attr("trait").map(|t| t.chars().take(MAX_NAME).collect::<String>()); let kind = trait_kind(trait_name.as_deref()); if kinds.insert(name.clone(), kind).is_some() { return Err(bad(cmd, format!("variable `{name}` is declared twice"))); @@ -265,7 +268,7 @@ fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result<Library> { } if kind == VariableKind::Text { // `docRef="id('…')"` names the element of the variable's bound object. - let element = var.attribute("docRef").and_then(|r| r.trim().strip_prefix("id('")?.strip_suffix("')")).filter(|e| !e.is_empty()); + let element = var.attr("docRef").and_then(|r| r.trim().strip_prefix("id('")?.strip_suffix("')")).filter(|e| !e.is_empty()); if let Some(element) = element { refs.push((name.clone(), element.to_string())); } @@ -276,10 +279,8 @@ fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result<Library> { return Err(bad(cmd, "the variable library declares no variables")); } let (mut datasets, mut seen) = (Vec::new(), BTreeSet::new()); - for row in - sets.iter().flat_map(|s| s.children()).filter(|n| is(n, "sampleDataSets")).flat_map(|d| d.children()).filter(|n| is(n, "sampleDataSet")) - { - let name = named(row.attribute("dataSetName"), "dataSetName", cmd)?; + for row in sets.iter().flat_map(|s| s.children(craft_xml::Local("sampleDataSets"))).flat_map(|d| d.children(craft_xml::Local("sampleDataSet"))) { + let name = named(row.attr("dataSetName"), "dataSetName", cmd)?; if !seen.insert(name.clone()) { return Err(bad(cmd, format!("data set `{name}` is declared twice"))); } @@ -287,8 +288,8 @@ fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result<Library> { return Err(bad(cmd, format!("the variable library declares more than {MAX_LIBRARY_DATASETS} data sets"))); } let (mut values, mut held) = (BTreeMap::new(), BTreeSet::new()); - for el in row.children().filter(roxmltree::Node::is_element) { - let var = el.tag_name().name(); + for el in row.elements() { + let var = el.local(); let Some(kind) = kinds.get(var) else { return Err(bad(cmd, format!("data set `{name}` holds a value for `{var}`, which the library doesn't declare"))); }; @@ -315,12 +316,12 @@ fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result<Library> { /// white space round them, and an element holding only white space gives none. A variable of /// unknown kind takes no value, so what its element holds is passed over. `set` names the data set /// in the errors. -fn library_value(el: roxmltree::Node, kind: VariableKind, set: &str, cmd: &str) -> Result<Option<DataValue>> { - let refused = |what: &str| bad(cmd, format!("data set `{set}` holds a value for `{}` that isn't {what}", el.tag_name().name())); - let text = || if elements(el).next().is_some() { None } else { Some(deep_text(el)) }; +fn library_value(el: &craft_xml::El, kind: VariableKind, set: &str, cmd: &str) -> Result<Option<DataValue>> { + let refused = |what: &str| bad(cmd, format!("data set `{set}` holds a value for `{}` that isn't {what}", el.local())); + let text = || if el.elements().next().is_some() { None } else { Some(el.deep_text()) }; match kind { VariableKind::Text => { - let paras: Vec<String> = elements(el).filter(|n| n.tag_name().name() == "p").map(deep_text).collect(); + let paras: Vec<String> = el.children(craft_xml::Local("p")).map(craft_xml::El::deep_text).collect(); Ok((!paras.is_empty()).then(|| DataValue::Text(paras.join("\n")))) } VariableKind::Visibility => { @@ -346,16 +347,6 @@ fn library_value(el: roxmltree::Node, kind: VariableKind, set: &str, cmd: &str) } } -/// The elements among `n`'s children. -fn elements<'a, 'i>(n: roxmltree::Node<'a, 'i>) -> impl Iterator<Item = roxmltree::Node<'a, 'i>> { - n.children().filter(roxmltree::Node::is_element) -} - -/// The text of every text node inside `n`, in order. -fn deep_text(n: roxmltree::Node) -> String { - n.descendants().filter(roxmltree::Node::is_text).filter_map(|t| t.text()).collect() -} - /// The absolute path a library's image value `text` names: a `file:` URL's path (`file:///…`, /// `file://localhost/…` or `file:/…`), its `%XX` escapes decoded (a URL with a host names a share, /// `//host/…`), or `text` itself. `None` unless that is an absolute path: one starting with `/` or @@ -428,29 +419,28 @@ fn library_file(path: &str) -> String { /// series, or when `el` holds only white space, there is no value. Anything else in `el`, more than /// [`MAX_GRAPH_CATEGORIES`] rows or [`MAX_GRAPH_SERIES`] series (what a graph holds), and CSV longer /// than graph values hold, are refused. -fn graph_value(el: roxmltree::Node, set: &str, cmd: &str) -> Result<Option<DataValue>> { - let var = el.tag_name().name(); +fn graph_value(el: &craft_xml::El, set: &str, cmd: &str) -> Result<Option<DataValue>> { + let var = el.local(); let refused = || bad(cmd, format!("data set `{set}` holds a value for `{var}` that isn't a graph's `data` element")); - let named = |name: &'static str| move |n: &roxmltree::Node| n.tag_name().name() == name; - let mut children = elements(el); + let named = |name: &'static str| craft_xml::Local(name); + let mut children = el.elements(); let data = match (children.next(), children.next()) { - (None, _) if deep_text(el).trim_matches(XML_SPACE).is_empty() => return Ok(None), - (Some(data), None) if data.tag_name().name() == "data" => data, + (None, _) if el.deep_text().trim_matches(XML_SPACE).is_empty() => return Ok(None), + (Some(data), None) if data.local() == "data" => data, _ => return Err(refused()), }; // Labels keep their white space; numbers are read without it. let series: Vec<String> = - elements(data).find(named("propertyRow")).map(|r| elements(r).filter(named("value")).skip(1).map(deep_text).collect()).unwrap_or_default(); - let rows: Vec<roxmltree::Node> = - elements(data).filter(named("values")).flat_map(elements).filter(named("row")).take(MAX_GRAPH_CATEGORIES + 1).collect(); + data.child(named("propertyRow")).map(|r| r.children(named("value")).skip(1).map(craft_xml::El::deep_text).collect()).unwrap_or_default(); + let rows: Vec<&craft_xml::El> = data.children(named("values")).flat_map(|v| v.children(named("row"))).take(MAX_GRAPH_CATEGORIES + 1).collect(); if rows.is_empty() && series.is_empty() { return Ok(None); } let too_many = || bad(cmd, format!("data set `{set}` holds a graph value for `{var}` with {}", graph_limits())); // A row's values after its name. - let wide = |row: &roxmltree::Node| { - let mut values = elements(*row).filter(named("value")).peekable(); - let _name = values.next_if(|v| v.attribute("key") == Some("name")); + let wide = |row: &&craft_xml::El| { + let mut values = row.children(named("value")).peekable(); + let _name = values.next_if(|v| v.attr("key") == Some("name")); values.count() > MAX_GRAPH_SERIES }; if rows.len() > MAX_GRAPH_CATEGORIES || series.len() > MAX_GRAPH_SERIES || rows.iter().any(wide) { @@ -462,12 +452,12 @@ fn graph_value(el: roxmltree::Node, set: &str, cmd: &str) -> Result<Option<DataV let read: Vec<(Option<String>, Vec<Option<f64>>)> = rows .iter() .map(|row| { - let mut values = elements(*row).filter(named("value")).peekable(); - let name = values.next_if(|v| v.attribute("key") == Some("name")); - labelled |= name.is_some_and(|v| v.attribute("type") == Some("string") || !deep_text(v).is_empty()); - let name = name.map(deep_text); - let number = |v: roxmltree::Node| deep_text(v).trim_matches(XML_SPACE).parse::<f64>().ok().filter(|n| n.is_finite()); - let numbers = values.map(|v| if v.attribute("type") == Some("string") { None } else { number(v) }); + let mut values = row.children(named("value")).peekable(); + let name = values.next_if(|v| v.attr("key") == Some("name")); + labelled |= name.is_some_and(|v| v.attr("type") == Some("string") || !v.deep_text().is_empty()); + let name = name.map(craft_xml::El::deep_text); + let number = |v: &craft_xml::El| v.deep_text().trim_matches(XML_SPACE).parse::<f64>().ok().filter(|n| n.is_finite()); + let numbers = values.map(|v| if v.attr("type") == Some("string") { None } else { number(v) }); (name, numbers.collect()) }) .collect(); diff --git a/crates/engine/src/cmd/wand.rs b/crates/engine/src/cmd/wand.rs index 218871972f..00f3e0551d 100644 --- a/crates/engine/src/cmd/wand.rs +++ b/crates/engine/src/cmd/wand.rs @@ -5,13 +5,14 @@ use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use vectorcraft_color::Paint; -use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_doc::{ColorMode, Document, Node, NodeId, NodeKind}; use super::select::selectable_ids; -use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, has_doc, object_param, str_param}; +use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, has_doc, object_param, str_param, switch_or}; -/// Magic Wand panel settings. Tolerances: colours as 0–255 RGB distance, stroke weight in -/// points, opacity in percent. +/// Magic Wand panel settings. Tolerances: colors as a Euclidean distance, 0–255 between RGB +/// values in an RGB document and 0–100 between CMYK percentages in a CMYK document; stroke +/// weight in points; opacity in percent. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct WandSettings { @@ -58,33 +59,68 @@ pub fn specs() -> Vec<CommandSpec> { "Magic Wand Options", ["Window", "Magic Wand"], None, - "{fillColor?, fillTolerance?: 0-255, strokeColor?, strokeTolerance?: 0-255, strokeWeight?, weightTolerance?: pt, opacity?, opacityTolerance?: %, blendingMode?, reset?: bool} → the settings", + "{fillColor?, fillTolerance?: 0-255 in an RGB document or 0-100 in a CMYK one, strokeColor?, strokeTolerance?: as fillTolerance, strokeWeight?, weightTolerance?: 0-1000 pt, opacity?, opacityTolerance?: 0-100 %, blendingMode?, reset?: bool} → the settings; a value out of range is an error and changes nothing, and an omitted one keeps its setting", always, set ), - cmd!(query "magicWand.options", "Magic Wand Settings", [], None, "{} → the Magic Wand settings", always, |s, _| Ok(json!(s.menu.wand))), + cmd!( + query "magicWand.options", + "Magic Wand Settings", + [], + None, + "{} → the Magic Wand settings (color tolerances at most 100 in a CMYK document)", + always, + |s, _| Ok(json!(s.menu.wand.effective(active_mode(s)))) + ), ] } -fn set(s: &mut Session, p: &Value) -> Result<Value> { - if bool_or(p, "reset", false) { - s.menu.wand = WandSettings::default(); +/// The active document's color mode, RGB with no document open. +fn active_mode(s: &Session) -> ColorMode { + s.doc().map(|st| st.doc.color_mode).unwrap_or_default() +} + +/// The largest Fill Color and Stroke Color tolerance in a document of `mode`. +pub fn color_tolerance_max(mode: ColorMode) -> f64 { + match mode { + ColorMode::Rgb => 255.0, + ColorMode::Cmyk => 100.0, } - let mut v = serde_json::to_value(&s.menu.wand).map_err(|e| EngineError::Other(e.to_string()))?; - if let (Some(o), Some(src)) = (v.as_object_mut(), p.as_object()) { - for (k, val) in src { - if o.contains_key(k) { - o.insert(k.clone(), val.clone()); - } +} + +fn set(s: &mut Session, p: &Value) -> Result<Value> { + const CMD: &str = "magicWand.set"; + let mode = active_mode(s); + let color_max = color_tolerance_max(mode); + let mut w = if switch_or(p, "reset", false, CMD)? { WandSettings::default() } else { s.menu.wand.clone() }; + for (key, flag) in [ + ("fillColor", &mut w.fill_color), + ("strokeColor", &mut w.stroke_color), + ("strokeWeight", &mut w.stroke_weight), + ("opacity", &mut w.opacity), + ("blendingMode", &mut w.blending_mode), + ] { + // Only a missing key keeps the setting; null, like any other value that isn't true or + // false, is an error. + if let Some(v) = p.get(key) { + *flag = v.as_bool().ok_or_else(|| bad(CMD, format!("`{key}` must be true or false")))?; } } - let mut w: WandSettings = serde_json::from_value(v).map_err(|e| bad("magicWand.set", e.to_string()))?; - w.fill_tolerance = w.fill_tolerance.clamp(0.0, 255.0); - w.stroke_tolerance = w.stroke_tolerance.clamp(0.0, 255.0); - w.weight_tolerance = w.weight_tolerance.clamp(0.0, 1000.0); - w.opacity_tolerance = w.opacity_tolerance.clamp(0.0, 100.0); + for (key, value, max) in [ + ("fillTolerance", &mut w.fill_tolerance, color_max), + ("strokeTolerance", &mut w.stroke_tolerance, color_max), + ("weightTolerance", &mut w.weight_tolerance, 1000.0), + ("opacityTolerance", &mut w.opacity_tolerance, 100.0), + ] { + let Some(v) = p.get(key) else { continue }; + let n = v.as_f64().ok_or_else(|| bad(CMD, format!("`{key}` must be a number, not {v}")))?; + if !(n.is_finite() && (0.0..=max).contains(&n)) { + return Err(bad(CMD, format!("`{key}` must be from 0 to {max}, not {n}"))); + } + *value = n; + } s.menu.wand = w; - Ok(json!(s.menu.wand)) + Ok(json!(s.menu.wand.effective(mode))) } /// The fill an object shows: type's comes from its characters (the first run speaks for all; type @@ -104,25 +140,48 @@ pub(crate) fn stroke_of(n: &Node) -> (Paint, f64) { } } -/// Are two paints within `tol` (0–255 Euclidean RGB distance)? Non-solid paints must match exactly. -pub fn similar_paint(a: &Paint, b: &Paint, tol: f64) -> bool { +/// Are two paints within `tol`? In an RGB document `tol` is a 0–255 Euclidean distance between +/// the display RGB values; in a CMYK document it is a 0–100 Euclidean distance between the CMYK +/// percentages (a CMYK color's own values, any other color converted to CMYK). Non-solid paints +/// must match exactly. +pub fn similar_paint(a: &Paint, b: &Paint, tol: f64, mode: ColorMode) -> bool { match (a.color(), b.color()) { (Some(x), Some(y)) => { - let (x, y) = (x.to_rgb(), y.to_rgb()); - let d: f64 = (0..3).map(|i| ((x[i] - y[i]) as f64 * 255.0).powi(2)).sum::<f64>().sqrt(); - d <= tol + 1e-6 + let (d, margin) = match mode { + ColorMode::Rgb => { + let (x, y) = (x.to_rgb(), y.to_rgb()); + ((0..3).map(|i| ((x[i] - y[i]) as f64 * 255.0).powi(2)).sum::<f64>().sqrt(), 1e-6) + } + // CMYK components are f32 fractions, so a distance of exactly `tol` points can come + // out a few millionths over. + ColorMode::Cmyk => { + let (x, y) = (x.to_cmyk(), y.to_cmyk()); + ((0..4).map(|i| ((x[i] - y[i]) as f64 * 100.0).powi(2)).sum::<f64>().sqrt(), 1e-4) + } + }; + d <= tol + margin } _ => a == b, } } impl WandSettings { - /// Does `n` match `reference` on every enabled attribute? - pub fn matches(&self, reference: &Node, n: &Node) -> bool { + /// The settings in effect in a document of `mode`: the color tolerances are capped at that + /// mode's maximum, so a larger value set in an RGB document applies as 100 in a CMYK one and + /// comes back in an RGB one. + pub fn effective(&self, mode: ColorMode) -> WandSettings { + let max = color_tolerance_max(mode); + WandSettings { fill_tolerance: self.fill_tolerance.min(max), stroke_tolerance: self.stroke_tolerance.min(max), ..self.clone() } + } + + /// Does `n` match `reference` on every enabled attribute, comparing colors as in a document of + /// `mode`? + pub fn matches(&self, reference: &Node, n: &Node, mode: ColorMode) -> bool { + let w = self.effective(mode); let (rs, rw) = stroke_of(reference); let (ns, nw) = stroke_of(n); - (!self.fill_color || similar_paint(&fill_of(reference), &fill_of(n), self.fill_tolerance)) - && (!self.stroke_color || similar_paint(&rs, &ns, self.stroke_tolerance)) + (!w.fill_color || similar_paint(&fill_of(reference), &fill_of(n), w.fill_tolerance, mode)) + && (!w.stroke_color || similar_paint(&rs, &ns, w.stroke_tolerance, mode)) && (!self.stroke_weight || (rw - nw).abs() <= self.weight_tolerance + 1e-9) && (!self.opacity || ((reference.opacity - n.opacity).abs() as f64 * 100.0) <= self.opacity_tolerance + 1e-6) && (!self.blending_mode || reference.blend == n.blend) @@ -156,12 +215,13 @@ fn magic_wand(s: &mut Session, p: &Value) -> Result<Value> { let st = s.doc()?; let reference = st.doc.node(id).ok_or(EngineError::NoNode(id))?.clone(); let w = s.menu.wand.clone(); + let mode = st.doc.color_mode; // In isolation mode only the isolated group's contents can be picked, as for Select Same. let inside = st.isolation.map(|iso| selectable_ids(&st.doc, Some(iso))); let hits: Vec<NodeId> = paintable(&st.doc) .into_iter() .filter(|i| inside.as_ref().is_none_or(|set| set.contains(i))) - .filter(|i| st.doc.node(*i).is_some_and(|n| w.matches(&reference, n))) + .filter(|i| st.doc.node(*i).is_some_and(|n| w.matches(&reference, n, mode))) .collect(); let ids: Vec<NodeId> = match str_param(p, "mode").unwrap_or("set") { "add" => st.selection.objects.iter().copied().chain(hits.iter().copied().filter(|h| !st.selection.objects.contains(h))).collect(), @@ -232,6 +292,137 @@ mod tests { assert_eq!(selected(&s), [b]); } + /// A 10 × 10 rectangle at `x` filled and stroked with the given colors (JSON color values). + fn painted(s: &mut Session, x: f64, fill: Value, stroke: Value) -> u64 { + let id = s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({ "color": fill })).unwrap(); + s.execute("paint.setStroke", &json!({ "color": stroke })).unwrap(); + id + } + + fn cmyk(c: f64, m: f64, y: f64, k: f64) -> Value { + json!({"model": "cmyk", "c": c, "m": m, "y": y, "k": k}) + } + + #[test] + fn cmyk_document_compares_fill_and_stroke_colors_in_cmyk() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap(); + let white = cmyk(0.0, 0.0, 0.0, 0.0); + let a = painted(&mut s, 0.0, cmyk(0.1, 0.0, 0.0, 0.0), white.clone()); + let b = painted(&mut s, 20.0, cmyk(0.0, 0.0, 0.0, 0.0), white.clone()); + let c = painted(&mut s, 40.0, cmyk(0.0, 0.1, 0.0, 0.0), white.clone()); + // a to b is 10 points of cyan; a to c is 10 points of cyan and 10 of magenta (14.1). + s.execute("magicWand.set", &json!({"fillTolerance": 10})).unwrap(); + s.execute("select.magicWand", &json!({"id": a})).unwrap(); + assert_eq!(selected(&s), [a, b]); + s.execute("magicWand.set", &json!({"fillTolerance": 9.9})).unwrap(); + s.execute("select.magicWand", &json!({"id": a})).unwrap(); + assert_eq!(selected(&s), [a]); + s.execute("magicWand.set", &json!({"fillTolerance": 14.2})).unwrap(); + s.execute("select.magicWand", &json!({"id": a})).unwrap(); + assert_eq!(selected(&s), [a, b, c]); + // Stroke Color alone, the same rule: d's stroke is 5 points of black from a's. + let d = painted(&mut s, 60.0, cmyk(1.0, 1.0, 1.0, 1.0), cmyk(0.0, 0.0, 0.0, 0.05)); + s.execute("magicWand.set", &json!({"fillColor": false, "strokeColor": true, "strokeTolerance": 5})).unwrap(); + s.execute("select.magicWand", &json!({"id": d})).unwrap(); + assert_eq!(selected(&s), [a, b, c, d]); + s.execute("magicWand.set", &json!({"strokeTolerance": 4.9})).unwrap(); + s.execute("select.magicWand", &json!({"id": d})).unwrap(); + assert_eq!(selected(&s), [d]); + } + + #[test] + fn cmyk_document_compares_gray_as_black_ink() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap(); + let none = cmyk(0.0, 0.0, 0.0, 0.0); + let a = painted(&mut s, 0.0, json!({"gray": 0.5}), none.clone()); + let b = painted(&mut s, 20.0, cmyk(0.0, 0.0, 0.0, 0.5), none.clone()); + let c = painted(&mut s, 40.0, cmyk(0.0, 0.0, 0.0, 0.6), none); + s.execute("magicWand.set", &json!({"fillTolerance": 0})).unwrap(); + s.execute("select.magicWand", &json!({"id": a})).unwrap(); + assert_eq!(selected(&s), [a, b]); + s.execute("magicWand.set", &json!({"fillTolerance": 10})).unwrap(); + s.execute("select.magicWand", &json!({"id": a})).unwrap(); + assert_eq!(selected(&s), [a, b, c]); + } + + #[test] + fn rgb_document_keeps_the_rgb_distance() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap(); + let a = rect(&mut s, 0.0, "#000000", 1.0); + let b = rect(&mut s, 20.0, "#0a0000", 1.0); + s.execute("magicWand.set", &json!({"fillTolerance": 10})).unwrap(); + s.execute("select.magicWand", &json!({"id": a})).unwrap(); + assert_eq!(selected(&s), [a, b]); + s.execute("magicWand.set", &json!({"fillTolerance": 9.9})).unwrap(); + s.execute("select.magicWand", &json!({"id": a})).unwrap(); + assert_eq!(selected(&s), [a]); + assert_eq!(s.execute("magicWand.set", &json!({"fillTolerance": 255})).unwrap()["fillTolerance"], 255.0); + } + + #[test] + fn set_rejects_tolerances_out_of_range_and_changes_nothing() { + let mut s = Session::new(); + // With no document the color range is the RGB one. + assert!(s.execute("magicWand.set", &json!({"fillTolerance": 256})).is_err()); + s.execute("magicWand.set", &json!({"fillTolerance": 200})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap(); + s.execute("magicWand.set", &json!({"fillTolerance": 40, "strokeTolerance": 50})).unwrap(); + let before = s.execute("magicWand.options", &json!({})).unwrap(); + for bad_value in [ + json!({"fillTolerance": 101}), + json!({"strokeTolerance": 100.5}), + json!({"fillTolerance": -1}), + json!({"fillTolerance": "40"}), + json!({"weightTolerance": 1001}), + json!({"opacityTolerance": -0.5}), + json!({"fillColor": "yes"}), + json!({"fillTolerance": null}), + json!({"strokeColor": null}), + json!({"reset": "yes", "fillColor": false}), + json!({"reset": true, "fillTolerance": 101}), + json!({"fillColor": false, "strokeTolerance": 101}), + ] { + let e = s.execute("magicWand.set", &bad_value).unwrap_err().to_string(); + assert!(e.contains("magicWand.set"), "{bad_value}: {e}"); + assert_eq!(s.execute("magicWand.options", &json!({})).unwrap(), before, "{bad_value} changed the settings"); + } + assert!(s.execute("magicWand.set", &json!({"fillTolerance": 101})).unwrap_err().to_string().contains("from 0 to 100")); + assert_eq!(s.execute("magicWand.set", &json!({"fillTolerance": 100})).unwrap()["fillTolerance"], 100.0); + // An omitted value keeps its setting. + assert_eq!(s.execute("magicWand.set", &json!({"strokeColor": true})).unwrap()["strokeTolerance"], 50.0); + } + + #[test] + fn a_larger_rgb_tolerance_applies_as_100_in_a_cmyk_document_and_comes_back() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap(); + s.execute("magicWand.set", &json!({"fillTolerance": 200, "strokeTolerance": 60})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap(); + let o = s.execute("magicWand.options", &json!({})).unwrap(); + assert_eq!((o["fillTolerance"].as_f64(), o["strokeTolerance"].as_f64()), (Some(100.0), Some(60.0))); + // Setting another field does not overwrite the stored fill tolerance. + assert_eq!(s.execute("magicWand.set", &json!({"opacity": true})).unwrap()["fillTolerance"], 100.0); + // 100 applies: two colors 100 points apart in one channel match, 100 apart in two do not. + let none = cmyk(0.0, 0.0, 0.0, 0.0); + let a = painted(&mut s, 0.0, cmyk(0.0, 0.0, 0.0, 0.0), none.clone()); + let b = painted(&mut s, 20.0, cmyk(1.0, 0.0, 0.0, 0.0), none.clone()); + let c = painted(&mut s, 40.0, cmyk(1.0, 1.0, 0.0, 0.0), none); + s.execute("magicWand.set", &json!({"opacity": false})).unwrap(); + s.execute("select.magicWand", &json!({"id": a})).unwrap(); + assert_eq!(selected(&s), [a, b]); + assert!(!selected(&s).contains(&c)); + s.execute("document.activate", &json!({"index": 0})).unwrap(); + assert_eq!(s.execute("magicWand.options", &json!({})).unwrap()["fillTolerance"], 200.0); + // Reset gives 32 in either mode. + s.execute("document.activate", &json!({"index": 1})).unwrap(); + let o = s.execute("magicWand.set", &json!({"reset": true})).unwrap(); + assert_eq!((o["fillTolerance"].as_f64(), o["strokeTolerance"].as_f64()), (Some(32.0), Some(32.0))); + } + #[test] fn isolation_mode_limits_the_wand_to_the_isolated_group() { let mut s = Session::new(); 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<u8>, 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/cmd/xmlattrs.rs b/crates/engine/src/cmd/xmlattrs.rs new file mode 100644 index 0000000000..6dd2578fae --- /dev/null +++ b/crates/engine/src/cmd/xmlattrs.rs @@ -0,0 +1,55 @@ +//! Attribute uniqueness checks missing from the pinned shared XML reader's strict mode. +//! +//! Temporary consumer guard: parsing remains in craft-xml. Move this invariant into the +//! shared strict reader and remove this second event pass when that dependency is updated. + +/// Check names before canonical/local-name rewriting can collapse distinct attributes. +/// The event reader and namespace scope use the same caller-supplied resource caps. +pub(super) fn validate(xml: &[u8], limits: craft_xml::Limits) -> Result<(), String> { + use std::collections::BTreeSet; + + let opts = craft_xml::Options { limits, doctype: craft_xml::Doctype::Reject, ..Default::default() }.strict(); + let mut events = opts.events(xml); + let mut bindings: Vec<(String, String)> = Vec::new(); + let mut scopes = Vec::new(); + while let Some(event) = events.next().map_err(|e| e.to_string())? { + match event { + craft_xml::Event::Start { attrs, .. } => { + scopes.push(bindings.len()); + let mut raw = BTreeSet::new(); + for (key, value) in &attrs { + if !raw.insert(key.as_str()) { + return Err(format!("duplicate attribute `{key}`")); + } + if let Some(prefix) = key.strip_prefix("xmlns:") { + if bindings.len() >= limits.max_attrs { + return Err("too many in-scope namespace declarations".into()); + } + bindings.push((prefix.to_string(), value.clone())); + } + } + let mut expanded = BTreeSet::new(); + for (key, _) in &attrs { + if key == "xmlns" || key.starts_with("xmlns:") { + continue; + } + // Default namespaces do not apply to attributes. Preserve undeclared + // prefixes for standalone SVG library fragments, as the importer did. + let name = match key.split_once(':') { + Some(("xml", local)) => ("http://www.w3.org/XML/1998/namespace", local), + Some((prefix, local)) => { + bindings.iter().rev().find(|(p, _)| p == prefix).map_or(("", key.as_str()), |(_, uri)| (uri.as_str(), local)) + } + None => ("", key.as_str()), + }; + if !expanded.insert(name) { + return Err(format!("duplicate expanded attribute `{key}`")); + } + } + } + craft_xml::Event::End { .. } => bindings.truncate(scopes.pop().unwrap_or(0)), + _ => {} + } + } + Ok(()) +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index aeb723c963..4f7532108d 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -179,6 +179,9 @@ pub struct Session { /// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder /// ([`Session::attach_scripts_dir`]). scripts_dir: Option<std::path::PathBuf>, + /// The folder of File Info's metadata templates; `None`: no folder + /// ([`Session::attach_metadata_templates_dir`]). + metadata_templates_dir: Option<std::path::PathBuf>, /// The folder of the New Document profiles `file.new` starts documents from; `None`: none, /// every document starts with the defaults ([`Session::attach_new_doc_profiles`]). new_doc_profile_dir: Option<std::path::PathBuf>, diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 871ca4f399..88d9bd1761 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2012,7 +2012,11 @@ impl Session { Ok(Ok(Progress::Done(_))) if job.host.dialogs.unused() > 0 => { let n = job.host.dialogs.unused(); let kind = LimitKind::Host; - let message = format!("`answers` has {n} answer{} the script did not use", if n == 1 { "" } else { "s" }); + let message = if n == 1 { + format!("`answers` has {n} answer the script did not use") + } else { + format!("`answers` has {n} answers the script did not use") + }; Some(self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0 })) } Ok(Ok(Progress::Done(_))) => { diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index b2836d159c..4415566d13 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -26,6 +26,9 @@ impl Session { vectorcraft_doc::hit::set_image_paint(vectorcraft_render::effects::image_paint); // Clicks inside a clip group fall in the region its clipping path's effects give it. vectorcraft_doc::hit::set_clip_region(vectorcraft_render::effects::reshaped_clip_outline); + // Clicks and marquees find paths, compound paths, groups and layers where their geometry + // effects draw them. + vectorcraft_doc::hit::set_drawn_art(vectorcraft_render::effects::preview::drawn_art); // Clicks find a blend's steps and an envelope's distorted art where the canvas draws them, // evaluated again when the fonts, the hyphenation exceptions or the plug-ins change. vectorcraft_doc::hit::set_live_art(vectorcraft_render::effects::expand_live, || { @@ -93,6 +96,7 @@ impl Session { color_settings_file: None, plugin_dir: None, scripts_dir: None, + metadata_templates_dir: None, new_doc_profile_dir: None, plugin_output: None, plugin_install_approval: None, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2c475c87d4..2665fc4d8f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -197,6 +197,7 @@ mod symbol_nine_slice; mod symbolbounds; mod symboledit; mod symbollib; +mod tangent_line; mod targeting; mod textcombos; mod textedit; @@ -3311,6 +3312,85 @@ fn flare_ring_seed_moves_only_the_rings() { assert_eq!(s.doc().unwrap().history.undo.len(), undo); } +/// `shape.ellipse` without `anchors`, or with 4, draws the live ellipse it always drew. +#[test] +fn ellipse_with_four_anchors_is_the_live_ellipse() { + let mut s = session(); + let draw = |s: &mut Session, extra: Option<u64>| { + let mut p = json!({"x": 40, "y": 30, "width": 120, "height": 80}); + if let Some(n) = extra { + p["anchors"] = json!(n); + } + let id = NodeId(s.execute("shape.ellipse", &p).unwrap()["id"].as_u64().unwrap()); + s.doc().unwrap().doc.node(id).unwrap().clone() + }; + let (plain, four) = (draw(&mut s, None), draw(&mut s, Some(4))); + for n in [&plain, &four] { + assert!(matches!(n.live_shape(), Some(vectorcraft_doc::LiveShape::Ellipse { .. })), "{:?}", n.live_shape()); + assert_eq!(n.path_data().unwrap().anchor_count(), 4); + } + assert_eq!(plain.path_data(), four.path_data()); + assert_eq!(plain.live_shape(), four.live_shape()); +} + +/// Any other count draws a closed plain path of that many smooth anchors on the ellipse, its +/// bounds the typed size, as one undo step. +#[test] +fn ellipse_anchors_draw_that_many_anchors_on_the_ellipse() { + let mut s = session(); + let (x, y, w, h) = (40.0, 30.0, 120.0, 80.0); + let (c, rx, ry) = (Point::new(x + w / 2.0, y + h / 2.0), w / 2.0, h / 2.0); + for n in [2u64, 3, 5, 6, 8] { + let undo = s.doc().unwrap().history.undo.len(); + let id = NodeId(s.execute("shape.ellipse", &json!({"x": x, "y": y, "width": w, "height": h, "anchors": n})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{n}: one undo step"); + let node = s.doc().unwrap().doc.node(id).unwrap(); + assert!(node.live_shape().is_none(), "{n}: a plain path"); + let path = node.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + let sp = &path.subpaths[0]; + assert!(sp.closed, "{n}"); + assert_eq!(sp.anchors.len() as u64, n); + for a in &sp.anchors { + assert_eq!(a.kind, vectorcraft_geom::AnchorKind::Smooth, "{n}"); + let on = ((a.p.x - c.x) / rx).powi(2) + ((a.p.y - c.y) / ry).powi(2); + assert!((on - 1.0).abs() < 0.01, "{n}: {:?} is off the ellipse ({on})", a.p); + } + let b = path.bounds().unwrap(); + for (got, want) in [(b.x0, x), (b.y0, y), (b.x1, x + w), (b.y1, y + h)] { + assert!((got - want).abs() < 1e-6, "{n}: bounds {b:?}"); + } + } + // The first anchor is the left one, and they run clockwise on screen, as the live ellipse's do. + let id = NodeId(s.execute("shape.ellipse", &json!({"x": x, "y": y, "width": w, "height": h, "anchors": 8})).unwrap()["id"].as_u64().unwrap()); + let sp = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].clone(); + assert!(sp.anchors[0].p.distance(Point::new(x, c.y)) < 1e-6, "{:?}", sp.anchors[0].p); + assert!(sp.anchors[2].p.distance(Point::new(c.x, y)) < 1e-6, "{:?}", sp.anchors[2].p); +} + +/// An `anchors` that is not a whole number from 2 to 1000 is refused, and nothing is drawn. +#[test] +fn ellipse_refuses_a_bad_anchor_count() { + let mut s = session(); + let undo = s.doc().unwrap().history.undo.len(); + let range = |got: &str| format!("`anchors` must be a whole number between 2 and 1000 (got {got})"); + for (bad, want) in [ + (json!(0), range("0")), + (json!(1), range("1")), + (json!(2.5), range("2.5")), + (json!(-3), range("-3")), + (json!(1001), range("1001")), + (json!("x"), "`anchors` must be a number, not \"x\"".to_string()), + (json!("6"), "`anchors` must be a number, not \"6\"".to_string()), + (json!(true), "`anchors` must be a number, not true".to_string()), + ] { + let e = s.execute("shape.ellipse", &json!({"x": 0, "y": 0, "width": 50, "height": 50, "anchors": bad})).unwrap_err().to_string(); + assert!(e.contains(&want), "{bad}: {e}"); + } + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + assert!(s.doc().unwrap().doc.layers[0].children().unwrap().is_empty()); +} + /// Through the session, Ctrl/Cmd in the Flare tool's center drag keeps the center's size while the /// drag sizes the halo, and the flare drawn keeps both. #[test] 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/assets_3d.rs b/crates/engine/src/tests/assets_3d.rs index cdef5b1dfc..2d1fbd7761 100644 --- a/crates/engine/src/tests/assets_3d.rs +++ b/crates/engine/src/tests/assets_3d.rs @@ -89,6 +89,45 @@ fn export_3d_object_refuses_objects_without_a_3d_effect_and_bad_formats() { assert_eq!(r["added"], 1); } +/// Without `ids`, the selected objects without a 3D effect, a group whose 3D effect is on its fill +/// (it draws nothing to export) and a 3D object inside another selected one are left out; a +/// selection with none left is refused. +#[test] +fn export_3d_object_leaves_flat_objects_in_the_selection_out() { + let mut s = session(); + let plain = run(&mut s, "shape.rectangle", json!({"x": 10.0, "y": 100.0, "width": 40.0, "height": 30.0}))["id"].as_u64().unwrap(); + let filled = run(&mut s, "shape.rectangle", json!({"x": 10.0, "y": 200.0, "width": 40.0, "height": 30.0}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids": [filled]})); + let group = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids": [group]})); + run(&mut s, "appearance.addFill", json!({})); + run(&mut s, "effect.apply", json!({"effect": "threeD.extrude"})); + // `effect.apply` puts a group's 3D effect on the group itself; a file can hold one on its fill. + s.edit("fill", |d, _| { + let n = d.node_mut(vectorcraft_doc::NodeId(group)).unwrap(); + let fx = n.appearance.effects.remove(0); + n.appearance.items[0].effects_mut().push(fx); + Ok(()) + }) + .unwrap(); + run(&mut s, "select.set", json!({"ids": [plain, group]})); + let before = undo_len(&s); + assert!(s.execute("assets.add3D", &json!({})).is_err(), "no object with a 3D effect to export"); + assert_eq!(undo_len(&s), before); + let inner = extruded(&mut s, 100.0, "Inner"); + let other = run(&mut s, "shape.rectangle", json!({"x": 200.0, "y": 10.0, "width": 40.0, "height": 30.0}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids": [inner, other]})); + let outer = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids": [outer]})); + run(&mut s, "effect.apply", json!({"effect": "threeD.extrude"})); + run(&mut s, "select.set", json!({"ids": [plain, group, inner, outer]})); + let r = run(&mut s, "assets.add3D", json!({})); + assert_eq!(r["added"], 1, "{r}"); + let nodes: Vec<Value> = run(&mut s, "assets.list", json!({}))["assets"].as_array().unwrap().iter().map(|a| a["nodes"].clone()).collect(); + assert_eq!(nodes, [json!([outer])]); + assert!(s.execute("assets.add3D", &json!({"ids": [plain, outer]})).is_err(), "ids are still refused"); +} + #[test] fn the_format_is_set_per_asset_and_only_a_change_is_an_undo_step() { let mut s = session(); diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index a2e9eb3012..77258b7eb7 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1037,6 +1037,40 @@ fn brush_freehand_direct_call_has_one_undo_step() { assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Paintbrush"), "a stroke with a brush is a Paintbrush step"); } +/// A `brush.freehand` call that continues a path by one point changes only the path's brush, and +/// applies `keepSelected` as a longer continuation does: off, the path is deselected while the +/// rest of the selection stays; on, the path is selected. A call that leaves the brush as it is +/// changes neither the selection nor the undo history. +#[test] +fn brush_freehand_continued_by_one_point_follows_keep_selected() { + let mut s = session(); + let r = s.execute("brush.freehand", &json!({"points": [[10, 10], [60, 40], [120, 10]], "style": "brush", "brush": "Charcoal"})).unwrap(); + let p = NodeId(r["id"].as_u64().unwrap()); + let a = rect(&mut s, 200.0, 200.0, 10.0, 10.0); + let extend = json!({"id": p.0, "end": "end"}); + + select(&mut s, &[p, a]); + let off = json!({"points": [[120, 10]], "extend": extend, "brush": "Dots", "keepSelected": false}); + assert_eq!(s.execute("brush.freehand", &off).unwrap()["id"], json!(p.0)); + assert_eq!(brush_of(&s, p).as_deref(), Some("Dots")); + assert_eq!(selected(&s), [a], "Keep selected off: the path is deselected and the rest stays"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(brush_of(&s, p).as_deref(), Some("Charcoal"), "one Undo takes back the brush"); + assert_eq!(selected(&s), [p, a], "Undo gives back the earlier selection"); + + select(&mut s, &[a]); + let on = json!({"points": [[120, 10]], "extend": extend, "brush": "Dots"}); + s.execute("brush.freehand", &on).unwrap(); + assert_eq!(brush_of(&s, p).as_deref(), Some("Dots")); + assert_eq!(selected(&s), [p], "Keep selected on: the continued path is selected"); + + select(&mut s, &[a]); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("brush.freehand", &on).unwrap(); + assert_eq!(selected(&s), [a], "the same brush again: the selection stays"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "the same brush again: no undo step"); +} + /// `brush.freehand` refuses a brush for a path with no stroke (a continued path, a redrawn one /// and a new filled pencil path while the stroke is None) instead of reporting it painted: the /// document, the selection and the undo history stay as they were. Without a brush the path is @@ -2565,3 +2599,50 @@ fn symbol_sort_by_name_orders_the_symbols_in_one_undo_step() { s.execute("symbol.sortByName", &json!({})).unwrap(); assert_eq!(s.doc().unwrap().history.undo.len(), before); } + +/// `cmd::current_symbol` answers what `symbol.list` answers as `current`, and what `rule` (the +/// stored name while a symbol has it, else the first of all the names) answers: +/// with no symbols, with no stored name, with a stored name that is not first, after the current +/// symbol is deleted, with a stored name no symbol has and with a stored value that is not text. +#[test] +fn current_symbol_is_the_current_symbol_list_answers() { + fn rule(d: &Document) -> Option<String> { + let names: Vec<String> = d.symbols.iter().map(|s| s.name.clone()).collect(); + let stored = d.unknown.get("currentSymbol").and_then(Value::as_str).filter(|n| d.symbols.iter().any(|s| s.name == *n)).map(str::to_string); + stored.or_else(|| names.into_iter().next()) + } + fn check(s: &mut Session, want: Option<&str>, case: &str) { + let listed = s.execute("symbol.list", &json!({})).unwrap()["current"].clone(); + let d = &s.doc().unwrap().doc; + let helper = crate::cmd::current_symbol(d); + assert_eq!(helper.as_deref(), want, "{case}"); + assert_eq!(json!(helper), listed, "{case}: symbol.list"); + assert_eq!(helper, rule(d), "{case}: the rule"); + } + fn store(s: &mut Session, v: Value) { + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).unknown.insert("currentSymbol".into(), v); + } + let mut s = session(); + check(&mut s, None, "no symbols"); + store(&mut s, json!("Gone")); + check(&mut s, None, "no symbols and a stored name"); + for (i, name) in ["A", "B", "C"].into_iter().enumerate() { + rect(&mut s, 20.0 * i as f64, 0.0, 10.0, 10.0); + s.execute("symbol.new", &json!({"name": name})).unwrap(); + } + check(&mut s, Some("C"), "the newest symbol is current"); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).unknown.remove("currentSymbol"); + check(&mut s, Some("A"), "no stored name"); + s.execute("symbol.setCurrent", &json!({"name": "B"})).unwrap(); + check(&mut s, Some("B"), "a stored name that is not first"); + s.execute("symbol.delete", &json!({"name": "B"})).unwrap(); + check(&mut s, Some("A"), "the current symbol deleted"); + store(&mut s, json!("Renamed")); + check(&mut s, Some("A"), "a stored name no symbol has"); + store(&mut s, json!(3)); + check(&mut s, Some("A"), "a stored number"); + store(&mut s, json!(["C"])); + check(&mut s, Some("A"), "a stored list"); + store(&mut s, json!("C")); + check(&mut s, Some("C"), "a stored name that is last"); +} diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index c7160f9316..cf56247042 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -4272,15 +4272,26 @@ fn live_paint_bucket_double_click_across_a_junction_paints_the_joined_edges() { s.pointer(&PointerEvent::new(kind, x, 50.0).with_mods(shift), v).unwrap(); } assert_eq!(middle.iter().map(|e| node(&s, *e).appearance.stroke_paint()).collect::<Vec<_>>(), [green.clone(), green.clone(), green]); - // `through` takes edge ids, with scope "connected" only. + // `through` takes the group's edge ids, each once, with scope "connected" only; a face's id, an + // unknown id or an edge given twice is refused and changes nothing. + let face = vectorcraft_tools::builder::faces(&node(&s, g)).first().map(|f| f.id).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let depth = s.doc().unwrap().history.undo.len(); for p in [ json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": "x"}), json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [-1]}), json!({"group": g.0, "point": [15, 50], "scope": "samePaint", "through": []}), json!({"group": g.0, "point": [15, 50], "through": []}), + json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [face.0]}), + json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [999_999_999]}), + json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [middle[1].0, middle[1].0]}), ] { assert!(s.execute("livePaint.strokeEdge", &p).is_err(), "{p}"); } + assert_eq!(s.doc().unwrap().doc, before); + assert_eq!(s.doc().unwrap().history.undo.len(), depth); + let r = s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [middle[1].0]})).unwrap(); + assert_eq!(r["count"], 3, "an edge of the group is taken"); } /// A double-click whose second press lands on the next joined edge and is released back on the @@ -4318,6 +4329,32 @@ fn live_paint_bucket_double_click_released_back_on_the_first_edge_paints_the_joi assert_eq!(middle.iter().map(|e| node(&s, *e).appearance.stroke_paint()).collect::<Vec<_>>(), [green.clone(), green.clone(), green]); } +/// With Paint Fills and Paint Strokes both on, a double-click on an edge after a click that filled +/// a face whose fill was the edge's stroke paint paints the joined edges: the face is not sent as +/// an edge to join through. +#[test] +fn live_paint_bucket_edge_double_click_after_filling_a_face_paints_the_joined_edges() { + let mut s = session(); + let g = live_squares(&mut s, &[0.0, 50.0]); + let [a, b] = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0)])[..] else { panic!("two faces") }; + let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0)); + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 51.0)); + paint_parts(&mut s, &all, &black, &[(a, black.clone()), (b, black.clone())]); + let v = ViewInfo::default(); + s.select_tool("livePaintBucket", v).unwrap(); + s.set_tool_option("paintStrokes", &json!(true)); + s.paint.fill = green.clone(); + s.paint.stroke = green.clone(); + for (kind, x) in [(PointerKind::Down, 25.0), (PointerKind::Up, 25.0), (PointerKind::Down, 50.0), (PointerKind::Up, 50.0)] { + s.pointer(&PointerEvent::new(kind, x, 25.0), v).unwrap(); + } + assert_eq!(fill_of(&s, a), green, "the first click fills the face"); + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 50.0, 25.0), v).unwrap(); + assert!(all.iter().all(|e| node(&s, *e).appearance.stroke_paint() == green), "every joined edge is painted"); + assert_eq!(fill_of(&s, b), black); +} + /// A triple-click whose second press holds Cmd (it goes to the selection tool Cmd lends) matches /// the fill the face had before the first click: the lent press counts as one that paints nothing. #[test] @@ -5354,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(); @@ -5810,9 +5881,10 @@ fn add_image(s: &mut Session, r: &vectorcraft_trace::Raster, xf: Affine) -> Node .unwrap() } -/// The traced paths of an Image Trace object: its children but the image and the seam fills. +/// The traced paths of an Image Trace object: its children but the image and the seam fills' +/// clip group (a trace makes no other clip group). fn traced_paths(n: &Node) -> Vec<Arc<Node>> { - n.children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Image(_)) && c.name.as_deref() != Some("Seam Fills")).cloned().collect() + n.children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Image(_) | NodeKind::Group { clip: true, .. })).cloned().collect() } #[test] @@ -6513,7 +6585,12 @@ fn image_trace_abutting_seam_fills_sit_under_the_paths() { assert!(matches!(kids[0].kind, NodeKind::Image(_))); let group = seams(&n).unwrap(); assert!(Arc::ptr_eq(&group, &kids[1]), "the seam fills come under the paths"); - let strokes = group.children().unwrap(); + assert!(matches!(group.kind, NodeKind::Group { clip: true, .. }), "{group:?}"); + // The two paths cover the image, so the strokes are clipped to its box. + let (clip, strokes) = group.children().unwrap().split_first().unwrap(); + assert!(matches!(clip.kind, NodeKind::Path { clipping: true, .. }), "{clip:?}"); + let cb = outline(clip).0.bounds().unwrap(); + assert!([cb.x0, cb.y0, cb.x1 - 80.0, cb.y1 - 40.0].iter().all(|v| v.abs() < 1e-9), "{cb:?}"); assert_eq!(strokes.len(), 1); assert_eq!(strokes[0].appearance.fill_paint(), Paint::None); let AppearanceItem::Stroke(layer) = &strokes[0].appearance.items[0] else { panic!("{:?}", strokes[0].appearance) }; @@ -6531,6 +6608,14 @@ fn image_trace_abutting_seam_fills_sit_under_the_paths() { assert_eq!(names.len(), 3, "{names:?}"); assert_eq!(names[0], "Edges", "{names:?}"); assert_eq!(n.children().unwrap()[0].id, group.id); + // Above a path, the seam fills' group is refused by name, not as an Auto Grouping group. + let (mut s, _, r) = made("abutting", "imageTrace.make", false); + let g = NodeId(r["id"].as_u64().unwrap()); + let kids = node(&s, g).children().unwrap().clone(); + s.execute("object.arrange.bringToFront", &json!({"ids": [kids[1].id.0]})).unwrap(); + assert_eq!(node(&s, g).children().unwrap().last().map(|c| c.id), Some(kids[1].id)); + let e = s.execute("imageTrace.expand", &json!({"id": g.0, "byColor": true})).unwrap_err().to_string(); + assert!(e.contains("seam fills") && !e.contains("Auto Grouping"), "{e}"); let (mut s, img, _) = made("abutting", "imageTrace.make", false); assert_eq!(ids(&s.execute("imageTrace.release", &json!({})).unwrap()), vec![img]); // Make and Expand by color too. @@ -6540,13 +6625,126 @@ fn image_trace_abutting_seam_fills_sit_under_the_paths() { // Overlapping paths are stacked: no seam fills. let (s, _, r) = made("overlapping", "imageTrace.make", false); assert!(seams(&node(&s, NodeId(r["id"].as_u64().unwrap()))).is_none()); - // An image stretched 3× across and squeezed to half height: 1.5 pixels at the larger scale. +} + +/// With white left out, the seam fills are clipped to the image's box within the traced paths' +/// box, so the expanded trace measures as its paths do, also on a turned image. +#[test] +fn image_trace_seam_fills_stay_within_the_traced_paths_box() { + let seams = |n: &Node| n.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Seam Fills")).cloned(); + let band = vectorcraft_trace::Raster::from_fn(24, 16, |x, y| match ((4..12).contains(&y), x < 12) { + (false, _) => [255; 4], + (true, true) => [200, 30, 30, 255], + (true, false) => [30, 30, 200, 255], + }); + for xf in [Affine::IDENTITY, Affine::translate((100.0, 100.0)) * Affine::rotate(0.5)] { + let mut s = session(); + add_image(&mut s, &band, xf); + let r = s + .execute( + "imageTrace.makeAndExpand", + &json!({"params": {"mode": "color", "palette": "limited", "colors": 3, "method": "abutting", "ignoreWhite": true}}), + ) + .unwrap(); + assert_eq!(r["paths"], 2, "{r}"); + let n = node(&s, NodeId(r["id"].as_u64().unwrap())); + let group = seams(&n).unwrap(); + let clip = &group.children().unwrap()[0]; + assert!(matches!(clip.kind, NodeKind::Path { clipping: true, .. }), "{clip:?}"); + let cb = outline(clip).0.bounds().unwrap(); + let paths = n.children().unwrap()[1..].iter().filter_map(|c| c.geometric_bounds()).reduce(|a, b| a.union(b)).unwrap(); + assert_eq!(n.geometric_bounds(), Some(paths), "{xf:?}"); + assert!(cb.x0 >= paths.x0 - 1e-9 && cb.y0 >= paths.y0 - 1e-9 && cb.x1 <= paths.x1 + 1e-9 && cb.y1 <= paths.y1 + 1e-9, "{xf:?}: {cb:?}"); + if xf == Affine::IDENTITY { + assert!([cb.x0, cb.y0 - 4.0, cb.x1 - 24.0, cb.y1 - 12.0].iter().all(|v| v.abs() < 1e-9), "{cb:?}"); + } + } +} + +/// On an image stretched more one way than another, the seam fills are the strokes' outlines in +/// image pixels, filled: on an image stretched 20× across, the one along a horizontal edge covers +/// 0.75 image pixels on each side of it, as on an image scaled alike both ways, and does not reach +/// across the transparent rows above the edge. +#[test] +fn image_trace_seam_fills_on_a_stretched_image_stay_near_their_edge() { + // Red beside blue, the edge between them anti-aliased, on an image stretched 3× across and + // squeezed to half height: the outline is 1.5 pixels (4.5 points) across the vertical edge. + let art = vectorcraft_trace::Raster::from_fn(40, 20, |x, _| { + let share = (16.4 - f64::from(x)).clamp(0.0, 1.0); + let mix = |a: f64, b: f64| (a * share + b * (1.0 - share)).round() as u8; + [mix(200.0, 30.0), mix(40.0, 90.0), mix(50.0, 200.0), 255] + }); let mut s = session(); add_image(&mut s, &art, Affine::scale_non_uniform(3.0, 0.5)); let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap(); - let group = seams(&node(&s, NodeId(r["id"].as_u64().unwrap()))).unwrap(); - let AppearanceItem::Stroke(layer) = &group.children().unwrap()[0].appearance.items[0] else { panic!("{group:?}") }; - assert!((layer.width - 4.5).abs() < 1e-9, "{}", layer.width); + let n = node(&s, NodeId(r["id"].as_u64().unwrap())); + let kids = n.children().unwrap(); + assert_eq!(kids[1].name.as_deref(), Some("Seam Fills")); + let fill = &kids[1].children().unwrap()[1]; + assert_eq!(fill.appearance.stroke_paint(), Paint::None, "{:?}", fill.appearance); + assert_eq!(fill.appearance.fill_paint(), kids[2].appearance.fill_paint(), "the lower path's color"); + let bb = outline(fill).0.bounds().unwrap(); + assert!((bb.width() - 4.5).abs() < 0.05 && bb.y0.abs() < 1e-6 && (bb.y1 - 10.0).abs() < 1e-6, "{bb:?}"); + // Rows 0 to 5 transparent, 5 to 10 red, 10 to 20 blue. + let art = vectorcraft_trace::Raster::from_fn(40, 20, |_, y| match y { + 0..5 => [0, 0, 0, 0], + 5..10 => [200, 30, 30, 255], + _ => [30, 30, 200, 255], + }); + let mut s = session(); + add_image(&mut s, &art, Affine::scale_non_uniform(20.0, 1.0)); + let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap(); + let n = node(&s, NodeId(r["id"].as_u64().unwrap())); + let group = n.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Seam Fills")).cloned().unwrap(); + let (_, members) = group.children().unwrap().split_first().unwrap(); + assert!(!members.is_empty(), "{group:?}"); + for m in members { + // What the member covers: its outline, grown by half its stroke's width. + let half = m.appearance.items.iter().fold(0.0_f64, |w, it| match it { + AppearanceItem::Stroke(l) => w.max(l.width / 2.0), + _ => w, + }); + let bb = outline(m).0.bounds().unwrap(); + let (y0, y1) = (bb.y0 - half, bb.y1 + half); + assert!(y0 > 9.25 - 1e-6 && y1 < 10.75 + 1e-6, "covers y {y0} to {y1}: {m:?}"); + } + // Renamed, the group of filled outlines is still the seam fills: Expand by color keeps it under + // every color's group. + s.execute("layer.setProps", &json!({"id": group.id.0, "name": "Edges"})).unwrap(); + s.execute("imageTrace.expand", &json!({"id": n.id.0, "byColor": true})).unwrap(); + assert_eq!(node(&s, n.id).children().unwrap()[0].id, group.id); +} + +/// A trace made before the seam fills were clipped holds them in a group without a clip: Expand by +/// color keeps that group under every color's group too, named or renamed. +#[test] +fn image_trace_expand_by_color_keeps_unclipped_seam_fills() { + let art = vectorcraft_trace::Raster::from_fn(40, 20, |x, _| { + let share = (16.4 - f64::from(x)).clamp(0.0, 1.0); + let mix = |a: f64, b: f64| (a * share + b * (1.0 - share)).round() as u8; + [mix(200.0, 30.0), mix(40.0, 90.0), mix(50.0, 200.0), 255] + }); + for name in [Some("Seam Fills"), None] { + let mut s = session(); + add_image(&mut s, &art, Affine::scale(2.0)); + let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap(); + let g = NodeId(r["id"].as_u64().unwrap()); + // The seam fills as such a trace holds them: the strokes alone, in a plain group. + let seams = node(&s, g).children().unwrap()[1].clone(); + let NodeKind::Group { clip: true, children } = &seams.kind else { panic!("{seams:?}") }; + let mut legacy = Node::group(seams.id, children[1..].to_vec()); + legacy.name = name.map(Into::into); + s.edit("legacy", |d, _| { + let NodeKind::Group { children, .. } = &mut d.node_mut(g).unwrap().kind else { panic!("trace group") }; + children[1] = Arc::new(legacy); + Ok(()) + }) + .unwrap(); + s.execute("imageTrace.expand", &json!({"id": g.0, "byColor": true})).unwrap(); + let kids = node(&s, g).children().unwrap().clone(); + assert_eq!(kids.len(), 3, "{name:?}: {kids:?}"); + assert_eq!(kids[0].id, seams.id, "{name:?}"); + } } /// Expand by color: each color's paths in a group of their own, named by the color, the groups @@ -7609,6 +7807,51 @@ fn image_trace_views_draw_on_screen_only_and_expand_to_the_result() { } } +/// Outline views draw the traced paths' outlines and leave out an Abutting trace's seam fills +/// (their clipping box and strokes, or on a stretched image the strokes' filled outlines), renamed +/// too. +#[test] +fn image_trace_outline_view_leaves_out_the_seam_fills() { + // Red beside blue in the middle of a transparent 60 × 40 image, placed at 50, 50 and scaled 2×, + // or 2× across and 2.5× down. + let art = vectorcraft_trace::Raster::from_fn(60, 40, |x, y| match ((10..50).contains(&x) && (10..30).contains(&y), x < 30) { + (false, _) => [0, 0, 0, 0], + (true, true) => [200, 30, 30, 255], + (true, false) => [30, 30, 200, 255], + }); + for (scale, stretched) in [(Affine::scale(2.0), false), (Affine::scale_non_uniform(2.0, 2.5), true)] { + let mut s = session(); + add_image(&mut s, &art, Affine::translate((50.0, 50.0)) * scale); + let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap(); + let g = NodeId(r["id"].as_u64().unwrap()); + let seams = + node(&s, g).children().unwrap().iter().find(|c| matches!(c.kind, NodeKind::Group { clip: true, .. })).cloned().expect("seam fills"); + // Strokes, or on the stretched image their outlines, filled. + let members = &seams.children().unwrap()[1..]; + assert!(!members.is_empty()); + for m in members { + let (fill, stroke) = (m.appearance.fill_paint(), m.appearance.stroke_paint()); + assert_eq!((fill != Paint::None, stroke != Paint::None), (stretched, !stretched), "{scale:?}: {fill:?}, {stroke:?}"); + } + s.execute("imageTrace.setView", &json!({"id": g.0, "view": "outlines"})).unwrap(); + let screen = render_doc(&s, true); + // The image's top edge (y = 50), away from the art: nothing drawn. + for x in [60, 110, 160] { + assert!(screen.pixel(x, 50)[0] > 245 && screen.pixel(x, 51)[0] > 245, "{scale:?}, x = {x}: {:?}", screen.pixel(x, 50)); + } + // The art's left edge (x = 70) is outlined. + assert!((68..=72).any(|x| screen.pixel(x, 90)[0] < 128), "{scale:?}"); + // Beside the red and blue paths' shared edge (x = 110), inside the seam band (1.5 units + // each side on the stretched image) but off the traced outlines (x = 109 and 110): nothing. + for x in [108, 111] { + assert!(screen.pixel(x, 100)[0] > 245, "{scale:?}, x = {x}: {:?}", screen.pixel(x, 100)); + } + // Renamed, the group is still left out: the view draws as it did. + s.execute("layer.setProps", &json!({"id": seams.id.0, "name": "Edges"})).unwrap(); + assert!(render_doc(&s, true).pixels == screen.pixels, "{scale:?}: renamed seam fills drawn"); + } +} + /// #569: merging the regions of a rosette of unfilled ellipses (each off the centre, petals /// overlapping) merges every region the drags touch into one shape whose outline is only the /// merged area's border: no edge between merged regions stays in, as a stray line or a spur. diff --git a/crates/engine/src/tests/charstroke.rs b/crates/engine/src/tests/charstroke.rs index 2c34e697ea..d692becbce 100644 --- a/crates/engine/src/tests/charstroke.rs +++ b/crates/engine/src/tests/charstroke.rs @@ -188,6 +188,77 @@ fn align_stroke_reaches_the_characters_stroke() { assert!(aligns.contains(&StrokeAlign::Inside) && aligns.contains(&StrokeAlign::Outside), "{aligns:?}"); } +/// The bounds of type `t`'s glyph outlines in text space. +fn glyph_bounds(t: &TextObject) -> kurbo::Rect { + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + let mut all = kurbo::BezPath::new(); + for g in &lay.glyphs { + all.extend(g.outline.iter()); + } + kurbo::Shape::bounding_box(&all) +} + +/// Create Outlines on type scaled 300% across and 100% down: the canvas strokes the characters in +/// text space and then scales them, so the outlined stroke is filled art three times as thick +/// across upright stems as across level bars, not a live stroke of one mean weight. +#[test] +fn create_outlines_keeps_the_character_strokes_thickness_under_an_uneven_scale() { + let mut s = session(); + let id = stroked_text(&mut s); + run(&mut s, "stroke.set", json!({"weight": 4, "join": "round", "cap": "round"})); + run(&mut s, "object.scale", json!({"ids": [id.0], "sx": 300, "sy": 100})); + let t = text(&s, id); + let [a, b, c, d, ..] = t.xf.as_coeffs(); + assert!((a - 3.0).abs() < 1e-9 && b.abs() < 1e-9 && c.abs() < 1e-9 && (d - 1.0).abs() < 1e-9, "{:?}", t.xf); + let w = t.runs[0].style.stroke_width; + let gb = glyph_bounds(&t); + run(&mut s, "select.set", json!({ "ids": [id.0] })); + let g = run(&mut s, "type.createOutlines", json!({}))["ids"][0].as_u64().unwrap(); + let doc = &s.doc().unwrap().doc; + let group = doc.node(NodeId(g)).unwrap(); + let mut strokes: Option<kurbo::Rect> = None; + for c in group.children().unwrap() { + assert!(c.appearance.stroke().is_none(), "no live stroke of one weight is left"); + if c.appearance.fill_paint() == Paint::solid(Color::rgb8(255, 0, 0)) { + let cb = c.geometric_bounds().unwrap(); + strokes = Some(strokes.map_or(cb, |s| s.union(cb))); + } + } + // Round joins and caps reach half the weight past the glyphs in text space, then scale. + let want = t.xf.transform_rect_bbox(gb.inflate(w / 2.0, w / 2.0)); + let got = strokes.expect("filled character strokes"); + assert!((got.width() - want.width()).abs() < 0.1 && (got.height() - want.height()).abs() < 0.1, "{got:?} for {want:?}"); + assert!((got.height() - (gb.height() + w)).abs() < 0.1, "level bars keep the weight: {got:?}"); +} + +/// Under a uniform scale and a rotation the outlined characters keep a live stroke, its weight +/// and dashes scaled with them. +#[test] +fn create_outlines_keeps_a_live_character_stroke_under_a_uniform_scale_and_rotation() { + let mut s = session(); + let id = stroked_text(&mut s); + run(&mut s, "stroke.set", json!({"weight": 4, "dash": [6, 2]})); + run(&mut s, "object.scale", json!({"ids": [id.0], "sx": 200, "sy": 200})); + run(&mut s, "object.rotate", json!({"angle": 30})); + let t = text(&s, id); + let k = t.xf.determinant().abs().sqrt(); + assert!((k - 2.0).abs() < 1e-9, "{:?}", t.xf); + let st = t.runs[0].style.clone(); + let dash = st.stroke_dash.as_ref().unwrap().pattern.clone(); + let glyphs = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).glyphs.len(); + run(&mut s, "select.set", json!({ "ids": [id.0] })); + let g = run(&mut s, "type.createOutlines", json!({}))["ids"][0].as_u64().unwrap(); + let doc = &s.doc().unwrap().doc; + let pieces = doc.node(NodeId(g)).unwrap().children().unwrap().to_vec(); + assert_eq!(pieces.len(), glyphs, "one path for each glyph, no filled strokes"); + for p in &pieces { + let ps = p.appearance.stroke().expect("a live stroke"); + assert!((ps.width - st.stroke_width * k).abs() < 1e-6, "{} for {}", ps.width, st.stroke_width * k); + let got = &ps.dash.as_ref().unwrap().pattern; + assert!(got.iter().zip(&dash).all(|(g, d)| (g - d * k).abs() < 1e-6), "{got:?} for {dash:?}"); + } +} + /// Copying type's appearance onto a path keeps its characters' stroke alignment (the Eyedropper's /// own stroke attributes have none, on paths as on type). #[test] diff --git a/crates/engine/src/tests/clipboard.rs b/crates/engine/src/tests/clipboard.rs index 368bc6de10..ffb842bca8 100644 --- a/crates/engine/src/tests/clipboard.rs +++ b/crates/engine/src/tests/clipboard.rs @@ -468,7 +468,7 @@ fn styles_symbols_and_images_of_the_same_name_are_renamed() { assert_eq!(key(&s, img2), src_key); } -/// A graph whose series fill, value labels and legend rows paint with global swatch "Brand" and +/// A graph whose series fill, value labels, legend rows and axis and ring line rows paint with global swatch "Brand" and /// whose value labels are set in character style "Emphasis" and paragraph style "Body", as a /// later redraw would give them to its marks and labels. fn styled_graph(s: &mut Session) -> NodeId { @@ -484,8 +484,9 @@ fn styled_graph(s: &mut Session) -> NodeId { let l = &mut g.label_styles; l.values = Some(vectorcraft_doc::CharStyle { fill: brand.clone(), style_name: Some("Emphasis".into()), ..Default::default() }); l.values_para = Some(vectorcraft_doc::ParaStyle { style_name: Some("Body".into()), ..Default::default() }); - let rows = vectorcraft_doc::SeriesPaint { stroke: Some(brand), ..Default::default() }; - l.legend_rows = Some(vectorcraft_doc::graph::LabelRows { paint: rows, ..Default::default() }); + let paint = vectorcraft_doc::SeriesPaint { stroke: Some(brand), ..Default::default() }; + let rows = vectorcraft_doc::graph::LabelRows { paint, ..Default::default() }; + (l.legend_rows, l.axis_rows, l.ring_rows) = (Some(rows.clone()), Some(rows.clone()), Some(rows)); id } @@ -515,7 +516,7 @@ fn a_pasted_graph_brings_and_follows_its_label_styles_and_paints() { let d = doc(&s); assert!(d.swatch("Brand").is_some(), "{v}"); assert!(d.char_styles.iter().any(|x| x.name == "Emphasis") && d.para_styles.iter().any(|x| x.name == "Body"), "{v}"); - let brand = vec!["Brand".to_string(); 3]; + let brand = vec!["Brand".to_string(); 5]; assert_eq!(graph_links(&s, ids_of(&v)[0]), (brand.clone(), Some("Emphasis".into()), Some("Body".into()))); // Into a document that gives each name something else: they come in renamed. @@ -524,15 +525,15 @@ fn a_pasted_graph_brings_and_follows_its_label_styles_and_paints() { s.execute("charStyle.new", &json!({"name": "Emphasis", "attrs": {"size": 8.0}})).unwrap(); s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {"space_after": 2.0}})).unwrap(); let v = s.execute("edit.pasteInPlace", &json!({"swatchConflict": "add"})).unwrap(); - let brand2 = vec!["Brand 2".to_string(); 3]; + let brand2 = vec!["Brand 2".to_string(); 5]; assert_eq!(graph_links(&s, ids_of(&v)[0]), (brand2, Some("Emphasis 2".into()), Some("Body 2".into())), "{v}"); // Without formatting: the labels' text styles stay behind. new_doc(&mut s); let v = s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap(); assert!(doc(&s).char_styles.is_empty() && doc(&s).para_styles.is_empty(), "{v}"); - // The value labels' red characters stay behind too; the series fill and the legend rows keep Brand. - assert_eq!(graph_links(&s, ids_of(&v)[0]), (vec!["Brand".to_string(); 2], None, None)); + // The value labels' red characters stay behind too; the series fill, the legend rows and the line rows keep Brand. + assert_eq!(graph_links(&s, ids_of(&v)[0]), (vec!["Brand".to_string(); 4], None, None)); } /// Each label of graph `id` (the text of its Axes and Legend groups) with its size and its first paragraph's format. @@ -596,8 +597,8 @@ fn a_graph_pasted_without_formatting_keeps_plain_labels_when_drawn_again() { let r = node(&s, p).extras().graph.as_deref().unwrap().rect; let off = [r.x0 - plot.x0 - 10.0, r.y0 - plot.y0 - 20.0, r.x1 - plot.x1 - 10.0, r.y1 - plot.y1 - 20.0]; assert!(off.iter().all(|d| d.abs() < 1e-6), "the plot moves by the offset and keeps its size: {plot:?} → {r:?}"); - s.execute("graph.setType", &json!({"id": p.0, "type": "column"})).unwrap(); - assert_eq!(graph_label_looks(&s, p), pasted, "a change of type draws them the same way"); + s.execute("graph.setType", &json!({"id": p.0, "type": "column", "dropShadow": true})).unwrap(); + assert_eq!(graph_label_looks(&s, p), pasted, "a change of graph type options draws them the same way"); s.execute("edit.undo", &json!({})).unwrap(); s.execute("edit.undo", &json!({})).unwrap(); @@ -768,6 +769,84 @@ fn a_legend_fill_of_its_own_stays_behind_when_pasted_without_formatting() { assert_eq!(label(&s, p, "North").1, Paint::solid(Color::WHITE), "still white when the pie is drawn again"); } +/// A pie pasted into a document whose swatch of the same name is another color takes that color on its linked wedges +/// (Merge), and its legend labels in those wedges take the contrast a redraw gives them there: white on a wedge that +/// turned dark. Pasting with Add, which keeps the copied color, keeps the labels as they were. +#[test] +fn pie_legend_labels_follow_wedges_that_take_the_documents_swatch() { + let mut s = session(); + let csv = ",North,South\nP,1,1"; + s.execute("swatch.new", &json!({"name": "Brand", "color": "#ffff66", "global": true})).unwrap(); + let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap()); + s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap(); + /// The fill of the legend label of graph `id` that says `name`. + fn label(s: &Session, id: NodeId, name: &str) -> Paint { + let mut out = None; + node(s, id).walk(&mut |n| { + if let NodeKind::Text(t) = &n.kind + && t.plain_text() == name + { + out = Some(t.first_style().fill.clone()); + } + }); + out.unwrap() + } + // The North wedge, black when drawn, takes the light Brand swatch, and a redraw sets its label black. + let mut wedges = vec![]; + for c in node(&s, g).children().unwrap().iter().filter(|c| c.extras().series_index == Some(0)) { + c.walk(&mut |m| { + if matches!(m.kind, NodeKind::Path { .. }) { + wedges.push(m.id.0); + } + }); + } + assert!(!wedges.is_empty()); + s.execute("paint.setFill", &json!({"ids": wedges, "swatch": "Brand"})).unwrap(); + s.execute("graph.setData", &json!({"id": g.0, "csv": csv})).unwrap(); + assert_eq!(label(&s, g, "North"), Paint::solid(Color::BLACK), "black on the light wedge"); + assert_eq!(label(&s, g, "South"), Paint::solid(Color::BLACK)); + copy(&mut s, &[g]); + + for (cmd, choice, north) in [ + ("edit.pasteWithoutFormatting", "merge", Color::WHITE), + ("edit.paste", "merge", Color::WHITE), + ("edit.pasteWithoutFormatting", "add", Color::BLACK), + ("edit.paste", "add", Color::BLACK), + ] { + new_doc(&mut s); + s.execute("swatch.new", &json!({"name": "Brand", "color": "#202020", "global": true})).unwrap(); + let p = ids_of(&s.execute(cmd, &json!({"swatchConflict": choice})).unwrap())[0]; + assert_eq!(label(&s, p, "North"), Paint::solid(north), "{cmd} {choice}"); + assert_eq!(label(&s, p, "South"), Paint::solid(Color::BLACK), "{cmd} {choice}"); + s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap(); + assert_eq!(label(&s, p, "North"), Paint::solid(north), "{cmd} {choice}: as a redraw sets it"); + } + + // A copy of the pie in the opacity mask of a rectangle follows the same way. + s.execute("document.activate", &json!({"index": 0})).unwrap(); + let r = rect(&mut s, 10.0, 10.0, 300.0, 300.0); + let art = { + let d = doc_mut(&mut s); + let pie = d.node(g).unwrap().clone(); + d.reid(&pie) + }; + doc_mut(&mut s).node_mut(r).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true))); + copy(&mut s, &[r]); + new_doc(&mut s); + s.execute("swatch.new", &json!({"name": "Brand", "color": "#202020", "global": true})).unwrap(); + let p = ids_of(&s.execute("edit.paste", &json!({"swatchConflict": "merge"})).unwrap())[0]; + let mask = node(&s, p).extras().mask.as_deref().unwrap().art.clone(); + let mut north = None; + mask.walk(&mut |n| { + if let NodeKind::Text(t) = &n.kind + && t.plain_text() == "North" + { + north = Some(t.first_style().fill.clone()); + } + }); + assert_eq!(north, Some(Paint::solid(Color::WHITE)), "in an opacity mask"); +} + /// A two-line legend label in a narrow dark wedge, whose text sits off the wedge's middle line, stays white when its graph /// is pasted without formatting. #[test] @@ -1034,6 +1113,68 @@ fn a_repainted_wedge_sets_its_label_color_when_pasted_without_formatting() { assert_eq!(pasted, labels(&s, p), "copied as {before:?}"); } +/// Wedges linked to a global swatch that the destination document gives a dark color, merged on Paste without +/// Formatting, give their legend labels white characters, as a redraw does; added under a new name, they keep the +/// copied light color and black labels. +#[test] +fn wedges_merged_into_a_dark_swatch_give_white_labels_when_pasted_without_formatting() { + let csv = ",North,South\nP,1,1"; + fn labels(s: &Session, id: NodeId) -> Vec<(String, Paint)> { + let mut out = vec![]; + node(s, id).walk(&mut |n| { + if let NodeKind::Text(t) = &n.kind + && ["North", "South"].contains(&t.plain_text().as_str()) + { + out.push((t.plain_text(), t.first_style().fill.clone())); + } + }); + out + } + let both = |c: Color| vec![("North".to_string(), Paint::solid(c)), ("South".to_string(), Paint::solid(c))]; + for (conflict, expected) in [("merge", Color::WHITE), ("add", Color::BLACK)] { + let mut s = session(); + let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap()); + s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap(); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#ffffff", "global": true})).unwrap(); + let mut wedges = vec![]; + node(&s, g).walk(&mut |m| { + if let NodeKind::Path { .. } = m.kind { + wedges.push(m.id.0); + } + }); + s.execute("paint.setFill", &json!({"ids": wedges, "swatch": "Ink"})).unwrap(); + s.execute("graph.setData", &json!({"id": g.0, "csv": csv})).unwrap(); + assert_eq!(labels(&s, g), both(Color::BLACK), "light wedges have black labels"); + copy(&mut s, &[g]); + new_doc(&mut s); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#000000", "global": true})).unwrap(); + let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({"swatchConflict": conflict})).unwrap())[0]; + let pasted = labels(&s, p); + assert_eq!(pasted, both(expected), "{conflict}"); + s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap(); + assert_eq!(pasted, labels(&s, p), "{conflict}: as a redraw sets them"); + } +} + +/// An object linked to a graphic style and to a swatch merged with the document's keeps its graphic style link when +/// pasted without formatting, and its color shows the document's swatch. +#[test] +fn a_merged_swatch_keeps_graphic_style_links_when_pasted_without_formatting() { + let mut s = session(); + let r = swatched_rect(&mut s, "Ink", "#ffffff"); + sel(&mut s, &[r]); + s.execute("graphicStyle.new", &json!({"name": "Sun"})).unwrap(); + copy(&mut s, &[r]); + new_doc(&mut s); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#000000", "global": true})).unwrap(); + let v = s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap(); + assert_eq!(v["merged"], 1); + let p = ids_of(&v)[0]; + let style = node(&s, p).extras().graphic_style.and_then(|id| doc(&s).graphic_style_by_id(id)).map(|g| g.name.clone()); + assert_eq!(style.as_deref(), Some("Sun")); + assert_eq!(fill(&s, p), linked(hex("#000000"), "Ink", 1.0)); +} + /// When one pie's wedge of a series is repainted and another pie's wedge of that series is not, each pasted legend label /// takes the contrast of the wedge it is in. #[test] diff --git a/crates/engine/src/tests/clipflavours.rs b/crates/engine/src/tests/clipflavours.rs index 5955389aea..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"<svg xmlns=\"http://www.w3.org/2000/svg\"><rect width=\"4\" height=\"4\"/></svg>"; 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<u8> { }) .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 } @@ -512,3 +681,21 @@ fn keep_plain_text_preference_drops_pasted_formatting() { assert_eq!(paste_copied_range(false), 40.0, "Keep Formatting"); assert_eq!(paste_copied_range(true), 10.0, "Keep Plain Text"); } + +/// #7975: pasted plain text is new type, filled as [Normal Character Style] is, not with the +/// current fill. +#[test] +fn pasted_plain_text_takes_the_normal_character_style_fill() { + use vectorcraft_color::{Color, Paint}; + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "clipboard.importText", json!({"text": "Plain"})); + run(&mut s, "edit.paste", json!({"center": [200, 150]})); + assert_eq!(text_of(&pasted(&s)[0]).runs[0].style.fill, Paint::solid(Color::BLACK)); + let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + let attrs = crate::cmd::textstyles::char_attrs(&vectorcraft_doc::CharStyle { fill: blue.clone(), ..Default::default() }); + run(&mut s, "charStyle.setAttrs", json!({"name": "[Normal Character Style]", "attrs": {"fill": attrs["fill"]}})); + run(&mut s, "clipboard.importText", json!({"text": "Plain"})); + run(&mut s, "edit.paste", json!({"center": [200, 150]})); + assert_eq!(text_of(&pasted(&s)[0]).runs[0].style.fill, blue); +} 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/constrain_new.rs b/crates/engine/src/tests/constrain_new.rs index 49fd29e94b..50797e35e3 100644 --- a/crates/engine/src/tests/constrain_new.rs +++ b/crates/engine/src/tests/constrain_new.rs @@ -253,6 +253,25 @@ fn constrain_angle_turns_shapes_made_by_a_click() { } } +/// An ellipse of another anchor count made by a click turns along the Constrain Angle like the +/// live ellipse: it keeps its anchors and its box runs along the turned axes from the click. +#[test] +fn constrain_angle_turns_an_ellipse_of_six_anchors_made_by_a_click() { + let mut s = new_doc(); + set_angle(&mut s, 90.0); + let p = json!({"x": 10, "y": 200, "width": 100, "height": 50, "anchors": 6}); + let p = constrain_click(&s, "shape.ellipse", p.clone(), corner(&p)); + assert_eq!(p["anchors"], json!(6)); + let id = NodeId(s.execute("shape.ellipse", &p).unwrap()["id"].as_u64().unwrap()); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(n.live_shape().is_none()); + assert_eq!(n.path_data().unwrap().anchor_count(), 6); + let b = bounds(&s, id); + for (got, want) in [(b.x0, 10.0), (b.y0, 100.0), (b.x1, 60.0), (b.y1, 200.0)] { + assert!(close(got, want), "{b:?}"); + } +} + /// The Line Segment tool's Shift steps of 45° count from the Constrain Angle. #[test] fn constrain_angle_steps_the_line_segment_tool() { 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<u8> { 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/distort.rs b/crates/engine/src/tests/distort.rs index 6f56a09b68..36761466ae 100644 --- a/crates/engine/src/tests/distort.rs +++ b/crates/engine/src/tests/distort.rs @@ -265,6 +265,26 @@ fn liquify_without_selection_hits_paths_under_the_brush() { assert!(path(&s, b).bounds().unwrap().width() < 100.0); } +/// The warning about objects under the brush that Liquify leaves as they are names their count +/// with the matching noun and verb. +#[test] +fn liquify_warns_about_one_or_several_skipped_objects() { + let mut s = session(); + let text = + |s: &mut Session, x: i32| s.execute("text.create", &json!({"x": x, "y": 460, "text": "Hi", "size": 24})).unwrap()["id"].as_u64().unwrap(); + let pucker = json!({"tool": "pucker", "points": [[550, 450]], "diameter": 150, "intensity": 1}); + let first = text(&mut s, 520); + s.execute("select.set", &json!({"ids": []})).unwrap(); + let r = s.execute("object.liquify", &pucker).unwrap(); + assert_eq!(r["skipped"], json!([first])); + assert_eq!(r["warning"], "Pucker left 1 object under the brush as it was (type): it reshapes paths only"); + let second = text(&mut s, 560); + s.execute("select.set", &json!({"ids": []})).unwrap(); + let r = s.execute("object.liquify", &pucker).unwrap(); + assert_eq!(r["skipped"], json!([first, second])); + assert_eq!(r["warning"], "Pucker left 2 objects under the brush as they were (type): it reshapes paths only"); +} + /// With nothing selected, a stroke leaves the art on a locked artboard as it is. #[test] fn liquify_without_selection_leaves_the_art_on_a_locked_artboard() { 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/draw2.rs b/crates/engine/src/tests/draw2.rs index 45ff1f84c1..fd2a577795 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -677,16 +677,16 @@ fn the_eraser_tip_varies_with_its_modes() { assert!((upright - 195.0).abs() < 0.3, "the upright tip left {upright} pt of the line"); let level_tip = left_of_line(json!([])); assert!((level_tip - 180.0).abs() < 0.3, "the level tip left {level_tip} pt of the line"); - // A 1500 pt tip on Tilt erases 1500 pt across with a mouse, as it does on Fixed. + // A 1000 pt tip on Tilt erases 1000 pt across with a mouse, as it does on Fixed. let mut s = session(); rect(&mut s, 0.0, 0.0, 4000.0, 4000.0); - let big = json!({"points": [[1000, 2000], [3000, 2000]], "size": 1500, "sizeMode": "tilt", "sizeVariation": 10}); + let big = json!({"points": [[1000, 2000], [3000, 2000]], "size": 1000, "sizeMode": "tilt", "sizeVariation": 10}); s.execute("path.eraseRegion", &big).unwrap(); let filled = |x: f64, y: f64| paths(&s).iter().any(|(_, pd)| vectorcraft_geom::hit::fill_contains(&pd.to_bezpath(), FillRule::NonZero, Point::new(x, y))); - assert_eq!((filled(2000.0, 2740.0), filled(2000.0, 2760.0)), (false, true), "a 1500 pt tip"); + assert_eq!((filled(2000.0, 2490.0), filled(2000.0, 2510.0)), (false, true), "a 1000 pt tip"); // A Size Variation kept while Size is Fixed leaves the size alone. - let kept = with(&on_rotation, json!({"sizeMode": "fixed", "sizeVariation": 1000000})); + let kept = with(&on_rotation, json!({"sizeMode": "fixed", "sizeVariation": 1000})); assert_eq!(erased(kept, json!([]), &probes), [true, false], "Size on Fixed with a Variation"); let mut s = session(); let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0); @@ -1337,6 +1337,84 @@ fn eraser_removes_small_shape_entirely() { assert!(paths(&s).is_empty()); } +/// `path.eraseRegion {rect}` (the Eraser's Alt-drag marquee) erases everything inside the +/// rectangle: a closed shape loses its area, an open path is cut where it crosses the edges, a +/// shape wholly inside goes, and only the selected paths take part when something is selected. One +/// undo step puts everything back, and a rectangle that touches nothing adds no undo step. +#[test] +fn erase_region_rect_erases_everything_inside_it() { + let filled = |s: &Session, x: f64, y: f64| { + paths(s).iter().any(|(_, pd)| pd.is_closed() && vectorcraft_geom::hit::fill_contains(&pd.to_bezpath(), FillRule::NonZero, Point::new(x, y))) + }; + let mut s = session(); + rect(&mut s, 100.0, 100.0, 200.0, 200.0); + rect(&mut s, 180.0, 140.0, 10.0, 10.0); + line(&mut s, 50.0, 150.0, 350.0, 150.0); + s.execute("select.none", &json!({})).unwrap(); + let undo = undo_steps(&s); + let r = s.execute("path.eraseRegion", &json!({"rect": [150, 120, 100, 60]})).unwrap(); + assert!(!r["ids"].as_array().unwrap().is_empty(), "{r}"); + assert_eq!(undo_steps(&s), undo + 1); + assert!(!filled(&s, 200.0, 150.0) && !filled(&s, 185.0, 145.0), "the area inside is erased, the small square with it"); + assert!(filled(&s, 120.0, 150.0) && filled(&s, 200.0, 250.0) && filled(&s, 200.0, 110.0), "the rest stays filled"); + let ps = paths(&s); + assert_eq!(ps.iter().filter(|(_, pd)| pd.is_closed()).count(), 1, "the square keeps the rectangle as a hole: {ps:?}"); + let open: Vec<f64> = ps.iter().filter(|(_, pd)| !pd.is_closed()).map(|(_, pd)| pd.length()).collect(); + assert_eq!(open.len(), 2, "the line is cut in two: {open:?}"); + assert!(open.iter().all(|l| (l - 100.0).abs() < 0.01), "{open:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(paths(&s).len(), 3); + assert!(filled(&s, 200.0, 160.0) && filled(&s, 185.0, 145.0)); + // A rectangle away from the art erases nothing and adds no undo step. + let undo = undo_steps(&s); + assert_eq!(s.execute("path.eraseRegion", &json!({"rect": [500, 500, 10, 10]})).unwrap(), json!({"ids": []})); + assert_eq!(undo_steps(&s), undo); + // With the line selected, only the line is erased. + let ln = paths(&s).into_iter().find(|(_, pd)| !pd.is_closed()).unwrap().0; + s.execute("select.set", &json!({"ids": [ln.0]})).unwrap(); + let closed: Vec<PathData> = paths(&s).into_iter().filter(|(_, pd)| pd.is_closed()).map(|(_, pd)| pd).collect(); + s.execute("path.eraseRegion", &json!({"rect": [90, 100, 30, 100]})).unwrap(); + let after: Vec<PathData> = paths(&s).into_iter().filter(|(_, pd)| pd.is_closed()).map(|(_, pd)| pd).collect(); + assert_eq!(after, closed, "the unselected squares are unchanged"); + let open: Vec<f64> = paths(&s).iter().filter(|(_, pd)| !pd.is_closed()).map(|(_, pd)| pd.length()).collect(); + assert_eq!(open.len(), 2); + assert!((open.iter().sum::<f64>() - 270.0).abs() < 0.01, "{open:?}"); +} + +/// A narrow `path.eraseRegion {rect}` across a long open path cuts it, wherever the rectangle +/// falls between the samples the path's length would give. +#[test] +fn erase_region_rect_cuts_a_long_line_with_a_narrow_rectangle() { + let mut s = session(); + line(&mut s, 0.0, 100.0, 10000.0, 100.0); + s.execute("select.none", &json!({})).unwrap(); + s.execute("path.eraseRegion", &json!({"rect": [5000.3, 90, 1, 20]})).unwrap(); + let mut open: Vec<f64> = paths(&s).iter().map(|(_, pd)| pd.length()).collect(); + open.sort_by(f64::total_cmp); + assert_eq!(open.len(), 2, "{open:?}"); + assert!((open[0] - 4998.7).abs() < 0.01 && (open[1] - 5000.3).abs() < 0.01, "{open:?}"); +} + +/// `path.eraseRegion` refuses a `rect` that is not four finite numbers with a width and a height +/// above 0, and `rect` given with `points`, and changes nothing. +#[test] +fn erase_region_rect_refuses_bad_values() { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let shape = "rect is [x, y, width, height] in points, with a width and a height above 0"; + for p in [ + json!({"rect": [10, 10, 0, 20]}), + json!({"rect": [10, 10, 20, -5]}), + json!({"rect": [10, 10, 20]}), + json!({"rect": [10, "10", 20, 20]}), + json!({"rect": [1e308, 0, 1e308, 20]}), + json!({"rect": {"x": 10, "y": 10, "width": 20, "height": 20}}), + ] { + refuses_with(&mut s, "path.eraseRegion", &p, shape); + } + refuses_with(&mut s, "path.eraseRegion", &json!({"rect": [10, 10, 20, 20], "points": [[0, 0]]}), "give `points` or `rect`, not both"); +} + /// #4495: the Eraser cuts a compound path as one shape: its hole stays empty, the erased area is /// empty, and the rest stays filled, with either fill rule. A notch inside the ring keeps one /// compound path; a drag through the whole ring leaves compound paths whose holes stay holes. @@ -1426,9 +1504,76 @@ fn the_eraser_tip_takes_its_angle_and_roundness() { // At 45°, half axes 10 and 2.5: the band is 2·√((10² + 2.5²) / 2), about 14.58 pt, and the // chord 2 / √(0.5 / 10² + 0.5 / 2.5²), about 6.86 pt. close(erase(json!({"angle": 45, "roundness": 25})), 2.0 * ((100.0f64 + 6.25) / 2.0).sqrt(), 2.0 / (0.5f64 / 100.0 + 0.5 / 6.25).sqrt()); - // A roundness past 100 is kept to 100, and one below 1 to 1. - close(erase(json!({"angle": 90, "roundness": 400})), 20.0, 20.0); - close(erase(json!({"angle": 90, "roundness": 0})), 0.2, 0.2); + // The ends of the Roundness range: 100% is round, and 1% leaves a tip 0.2 pt across. + close(erase(json!({"angle": 90, "roundness": 100})), 20.0, 20.0); + close(erase(json!({"angle": 90, "roundness": 1})), 0.2, 0.2); +} + +/// The Eraser refuses an `angle` outside -180 to 180 degrees and a `roundness` outside 1 to 100%, +/// naming the key and the range, and erases nothing. The ends of each range erase, and a key left +/// out or null takes its default: 0 degrees and 100%. +#[test] +fn the_eraser_refuses_an_angle_or_roundness_outside_its_range() { + let mut s = session(); + rect(&mut s, 100.0, 100.0, 100.0, 100.0); + s.execute("select.none", &json!({})).unwrap(); + let stroke = json!({"points": [[90, 150], [210, 150]], "size": 10}); + for angle in [json!(-181), json!(-180.001), json!(180.001), json!(200), json!(1e300), json!(-1e300)] { + refuses_with(&mut s, "path.eraseRegion", &with(&stroke, json!({"angle": angle})), "`angle` must be from -180 to 180 degrees"); + } + for roundness in [json!(0), json!(0.999), json!(-25), json!(100.001), json!(400), json!(1e300)] { + refuses_with(&mut s, "path.eraseRegion", &with(&stroke, json!({"roundness": roundness})), "`roundness` must be from 1 to 100%"); + } + // A key out of its range is refused when the other key is in range. + refuses_with(&mut s, "path.eraseRegion", &with(&stroke, json!({"angle": 90, "roundness": 400})), "`roundness` must be from 1 to 100%"); + refuses_with(&mut s, "path.eraseRegion", &with(&stroke, json!({"angle": 540, "roundness": 25})), "`angle` must be from -180 to 180 degrees"); + // The pieces a stroke leaves, undone again. + let mut erased = |tip: serde_json::Value| { + let r = s.execute("path.eraseRegion", &with(&stroke, tip.clone())).unwrap(); + assert_eq!(r["ids"].as_array().map(Vec::len), Some(2), "{tip}: the stroke cuts the square in two: {r}"); + let pieces: Vec<PathData> = paths(&s).into_iter().map(|p| p.1).collect(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + pieces + }; + // Both ends of each range are inside it. + for tip in [json!({"angle": -180}), json!({"angle": 180}), json!({"angle": 90, "roundness": 1}), json!({"roundness": 100})] { + erased(tip); + } + let default = erased(json!({})); + assert_eq!(erased(json!({"angle": 0, "roundness": 100})), default, "left out, the tip is round at 0 degrees"); + assert_eq!(erased(json!({"angle": null, "roundness": null})), default, "null is read as a key left out"); + assert!(erased(json!({"angle": 0, "roundness": 25})) != default, "a quarter-round level tip erases a narrower band"); +} + +/// The Scissors command refuses a `t` outside 0 to 1 instead of cutting at the nearer end of the +/// segment, with or without an `anchor` beside it; 0 and 1 cut at the segment's two anchors. +#[test] +fn scissors_refuse_a_t_outside_the_segment() { + let mut s = session(); + let id = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + let before = path(&s, id); + for t in [json!(-0.1), json!(-1e-9), json!(1.000001), json!(1.1), json!(1e300), json!(-1e300)] { + refuses_with(&mut s, "path.split", &json!({"id": id.0, "segment": 0, "t": t}), "`t` must be from 0 to 1"); + refuses_with(&mut s, "path.split", &json!({"id": id.0, "anchor": 1, "t": t}), "`t` must be from 0 to 1"); + } + // 0 opens the square at the segment's first anchor, 1 at its second, and 0.5 at a new anchor + // between them. + for (t, anchors, start) in [ + (json!(0), 5, before.subpaths[0].anchors[0].p), + (json!(1), 5, before.subpaths[0].anchors[1].p), + (json!(0.5), 6, before.subpaths[0].anchors[0].p.midpoint(before.subpaths[0].anchors[1].p)), + ] { + s.execute("path.split", &json!({"id": id.0, "segment": 0, "t": t})).unwrap(); + let cut = path(&s, id); + assert!(!cut.subpaths[0].closed && cut.subpaths[0].anchors.len() == anchors, "t {t}: {cut:?}"); + assert!((cut.subpaths[0].anchors[0].p - start).hypot() < 1e-9, "t {t}: the cut starts at {:?}", cut.subpaths[0].anchors[0].p); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&s, id), before, "t {t}: undo"); + } + // Left out, `t` is 0.5. + s.execute("path.split", &json!({"id": id.0, "segment": 0})).unwrap(); + assert_eq!(path(&s, id).subpaths[0].anchors.len(), 6); } #[test] @@ -2326,6 +2471,39 @@ fn smoothing_keeps_a_corner_between_curves() { } } +/// A Smooth drag over a corner of a path cut into very many short segments keeps it, however many +/// segments twice the reach spans: an open path's 90° corner with legs of 2,000 segments 0.05 pt +/// long at the default reach, and a corner of a 200 pt square cut into 0.25 pt segments with a 40 pt +/// reach. +#[test] +fn smoothing_keeps_corners_on_a_path_of_many_short_segments() { + let mut s = session(); + let (id, v, drag) = smooth_corner_path(&mut s, 90.0, 2000); + smooth_pass(&mut s, &drag); + let at = smooth_turn_at(&path(&s, id).subpaths[0], v); + assert!(at.is_some_and(|t| (t - 90.0).abs() < 0.01), "the open path's corner is kept: {at:?}"); + + let mut s = session(); + let ends = [Point::new(200.0, 200.0), Point::new(400.0, 200.0), Point::new(400.0, 400.0), Point::new(200.0, 400.0)]; + let mut anchors = vec![]; + for k in 0..4 { + let (a, b) = (ends[k], ends[(k + 1) % 4]); + anchors.extend((0..800).map(|j| { + let p = a.lerp(b, f64::from(j) / 800.0); + json!({"x": p.x, "y": p.y}) + })); + } + let id = smooth_test_path(&mut s, &anchors, true); + let v = ends[1]; + let mut drag: Vec<Point> = (0..8).map(|k| v - kurbo::Vec2::new(40.0 - 5.0 * f64::from(k), 0.0)).collect(); + drag.extend((0..=8).map(|k| v + kurbo::Vec2::new(0.0, 5.0 * f64::from(k)))); + let pts: Vec<_> = drag.iter().map(|p| json!([p.x, p.y])).collect(); + s.execute("path.smoothRegion", &json!({"points": pts, "radius": 40, "fidelity": 2.5})).unwrap(); + let sp = &path(&s, id).subpaths[0]; + let at = smooth_turn_at(sp, v); + assert!(sp.closed && at.is_some_and(|t| (t - 90.0).abs() < 0.01), "the square's corner is kept: {at:?}"); +} + /// A corner at the first anchor of the stretch a drag smooths, just out of its reach, keeps its /// place and its turn. #[test] @@ -2771,6 +2949,116 @@ fn drawing_commands_refuse_a_point_or_pressure_given_as_text() { s.execute("path.eraseRegion", &sized).unwrap(); } +/// The drawing tools' commands refuse a pen pressure outside 0 to 1, a tiltX or tiltY outside -90 +/// to 90 and a rotation outside 0 to 360, naming the key, and a point array of more than six +/// numbers, naming the point; the document, the selection and the undo history stay as they were. +/// The ends of each range, null, one tilt axis alone and a mouse point `[x, y]` still draw. +#[test] +fn pen_values_outside_their_ranges_are_refused() { + let mut s = session(); + let id = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let good = [json!([90, 150]), json!([150, 150]), json!([210, 150])]; + let cmds = [ + "path.freehand", + "brush.freehand", + "path.knife", + "path.eraseRegion", + "path.eraseSegments", + "path.smoothRegion", + "path.joinScrub", + "path.blob", + ]; + let pressure = "`pressure` must be from 0 to 1"; + let tilt_x = "`tiltX` must be from -90 to 90"; + let tilt_y = "`tiltY` must be from -90 to 90"; + let rotation = "`rotation` must be from 0 to 360"; + let entries = "`points[3]` must be an array of at most 6 entries"; + for cmd in cmds { + for (bad, want) in [ + (json!([150, 150, -0.01]), pressure), + (json!([150, 150, 1.5]), pressure), + (json!({"x": 150, "y": 150, "pressure": 1e300}), pressure), + (json!([150, 150, 0.5, -90.5]), tilt_x), + (json!([150, 150, 0.5, 91, 0]), tilt_x), + (json!({"x": 150, "y": 150, "tiltX": -1e300}), tilt_x), + (json!([150, 150, null, 0, -1e300]), tilt_y), + (json!({"x": 150, "y": 150, "tiltY": 90.01}), tilt_y), + (json!([150, 150, null, null, null, -1]), rotation), + (json!({"x": 150, "y": 150, "rotation": 360.5}), rotation), + (json!([150, 150, null, null, null, 720]), rotation), + (json!([150, 150, 0.5, 0, 0, 0, 1]), entries), + (json!([150, 150, null, null, null, null, null]), entries), + ] { + let points: Vec<_> = good.iter().cloned().chain([bad]).collect(); + let sel = s.doc().unwrap().selection.clone(); + refuses_with(&mut s, cmd, &json!({"points": points}), want); + assert_eq!(s.doc().unwrap().selection, sel, "{cmd} {points:?} changed the selection"); + } + } + for (row, cmd) in ["path.freehand", "brush.freehand", "path.blob", "path.eraseRegion"].into_iter().enumerate() { + let y = 300.0 + 50.0 * row as f64; + let points = json!([ + [100, y, 0, -90, 90, 0], + [150, y, 1, 90, -90, 360], + [200, y, 0.5, null, 30], + {"x": 250, "y": y, "tiltX": -45, "pressure": null}, + [300, y], + {"x": 350, "y": y, "rotation": 359.99}, + ]); + s.execute(cmd, &json!({"points": points})).unwrap_or_else(|e| panic!("{cmd}: {e}")); + let mouse = json!([[100, y + 20.0], [200, y + 20.0], [300, y + 25.0]]); + s.execute(cmd, &json!({"points": mouse})).unwrap_or_else(|e| panic!("{cmd} with mouse points: {e}")); + } +} + +/// `path.blob` and `path.eraseRegion` refuse a `size` outside 0.1 to 1000 pt and a `sizeVariation` +/// outside 0 to 1000 pt, in every `sizeMode` each takes and with it left out, and a `sizeVariation` +/// that is not a number with Fixed too; nothing changes. The ends of each range and null still draw. +#[test] +fn blob_and_eraser_size_and_variation_outside_their_ranges_are_refused() { + let mut s = session(); + let id = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let stroke = json!({"points": [[90, 150, 0.2, 30, 0, 45], [150, 150, 0.6, 0, 30, 90], [210, 150, 1, -30, 0, 180]]}); + let size = "`size` must be from 0.1 to 1000"; + let variation = "`sizeVariation` must be from 0 to 1000"; + let blob_modes = [json!(null), json!("fixed"), json!("pressure")]; + let eraser_modes = [json!(null), json!("fixed"), json!("random"), json!("pressure"), json!("tilt"), json!("bearing"), json!("rotation")]; + // The Eraser keeps its own message for a negative Size Variation. + for (cmd, modes, negative) in + [("path.blob", &blob_modes[..], variation), ("path.eraseRegion", &eraser_modes[..], "sizeVariation must be 0 or more")] + { + for x in [json!(0.09), json!(0), json!(-1), json!(1000.5), json!(1e300)] { + let sel = s.doc().unwrap().selection.clone(); + refuses_with(&mut s, cmd, &with(&stroke, json!({"size": x})), size); + assert_eq!(s.doc().unwrap().selection, sel, "{cmd} size {x} changed the selection"); + } + for mode in modes { + for (x, want) in [(json!(-0.5), negative), (json!(1000.01), variation), (json!(1e300), variation)] { + let sel = s.doc().unwrap().selection.clone(); + refuses_with(&mut s, cmd, &with(&stroke, json!({"sizeMode": mode, "sizeVariation": x})), want); + assert_eq!(s.doc().unwrap().selection, sel, "{cmd} {mode} sizeVariation {x} changed the selection"); + } + let text = json!({"sizeMode": mode, "sizeVariation": "8"}); + refuses_with(&mut s, cmd, &with(&stroke, text), "`sizeVariation` must be a number, not \"8\""); + } + } + for (row, (cmd, modes)) in [("path.blob", &blob_modes[..]), ("path.eraseRegion", &eraser_modes[..])].into_iter().enumerate() { + let y = 300.0 + 100.0 * row as f64; + let at = |p: serde_json::Value| with(&json!({"points": [[100, y, 0.2, 30, 0, 0], [200, y, 0.6, 0, 30, 90], [300, y, 1, -30, 0, 360]]}), p); + for extra in [json!({"size": 0.1}), json!({"size": 1000}), json!({"size": null, "sizeVariation": null, "sizeMode": null})] { + s.execute(cmd, &at(extra.clone())).unwrap_or_else(|e| panic!("{cmd} {extra}: {e}")); + } + for mode in modes { + for x in [0, 1000] { + let extra = json!({"sizeMode": mode, "sizeVariation": x}); + s.execute(cmd, &at(extra.clone())).unwrap_or_else(|e| panic!("{cmd} {extra}: {e}")); + } + } + } +} + /// The Eraser, Path Eraser, Smooth, Join and Blob Brush commands refuse a size, angle, roundness, /// width, radius, fidelity or tolerance given as text or as another value that is not a number, and change /// nothing; null is read as the key left out. @@ -2931,6 +3219,88 @@ fn split_refuses_a_subpath_anchor_or_segment_that_is_not_a_whole_number() { } } +/// Give `id` a 4 pt round-capped Inside stroke and, above it, a hidden red copy aligned Outside. +/// Returns the appearance it now has. +fn side_strokes(s: &mut Session, id: NodeId) -> vectorcraft_doc::Appearance { + use vectorcraft_doc::{AppearanceItem, LineCap, StrokeAlign}; + s.edit("Side Strokes", |d, _| { + let ap = &mut d.node_mut(id).unwrap().appearance; + let st = ap.stroke_mut().unwrap(); + (st.width, st.cap, st.align) = (4.0, LineCap::Round, StrokeAlign::Inside); + let mut top = st.clone(); + (top.align, top.visible, top.paint) = + (StrokeAlign::Outside, false, vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0))); + ap.items.push(AppearanceItem::Stroke(top)); + Ok(()) + }) + .unwrap(); + appearance(s, id) +} + +fn appearance(s: &Session, id: NodeId) -> vectorcraft_doc::Appearance { + (*s.doc().unwrap().doc.node(id).unwrap().appearance).clone() +} + +/// `ap` with every stroke aligned Center and nothing else changed. +fn centered(ap: &vectorcraft_doc::Appearance) -> vectorcraft_doc::Appearance { + let mut ap = ap.clone(); + for it in &mut ap.items { + if let vectorcraft_doc::AppearanceItem::Stroke(st) = it { + st.align = vectorcraft_doc::StrokeAlign::Center; + } + } + ap +} + +#[test] +fn scissors_cut_paths_have_their_strokes_centered() { + // The paths a Scissors cut makes keep the source's fill and strokes, every stroke centered, + // in the cut's one undo step; redo centers them again. + let mut s = session(); + let r = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + let before = side_strokes(&mut s, r); + assert_ne!(before, centered(&before)); + let undo = undo_steps(&s); + s.execute("path.split", &json!({"id": r.0, "anchor": 2})).unwrap(); + assert_eq!(undo_steps(&s), undo + 1); + assert!(!path(&s, r).subpaths[0].closed); + assert_eq!(appearance(&s, r), centered(&before), "closed path"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(path(&s, r).subpaths[0].closed); + assert_eq!(appearance(&s, r), before, "undo"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(appearance(&s, r), centered(&before), "redo"); + // An open path becomes two, at an anchor or inside a segment, both centered. + let anchors = json!([{"x": 100, "y": 300}, {"x": 200, "y": 300}, {"x": 300, "y": 300}]); + for at in [json!({"anchor": 1}), json!({"segment": 0, "t": 0.5})] { + let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap()); + let before = side_strokes(&mut s, id); + let made = s.execute("path.split", &with(&at, json!({"id": id.0}))).unwrap(); + let ids: Vec<NodeId> = made["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect(); + assert_eq!(ids.len(), 2, "{at}"); + for i in ids { + assert_eq!(appearance(&s, i), centered(&before), "{at}: {i:?}"); + } + } + // A path of several subpaths keeps one node: its other subpath's strokes are centered too. + let id = two_subpaths(&mut s); + let before = side_strokes(&mut s, id); + s.execute("path.split", &json!({"id": id.0, "anchor": 1})).unwrap(); + assert_eq!(path(&s, id).subpaths.len(), 3); + assert_eq!(appearance(&s, id), centered(&before), "several subpaths"); + // A cut that fails, at an open path's end point, changes neither the strokes nor the history. + let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap()); + let before = side_strokes(&mut s, id); + let undo = undo_steps(&s); + assert!(s.execute("path.split", &json!({"id": id.0, "anchor": 0})).is_err()); + assert_eq!((undo_steps(&s), appearance(&s, id)), (undo, before)); + // Strokes already centered stay shared with the undo history's copy. + let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap()); + let shared = s.doc().unwrap().doc.node(id).unwrap().appearance.clone(); + s.execute("path.split", &json!({"id": id.0, "anchor": 1})).unwrap(); + assert!(vectorcraft_doc::Shared::ptr_eq(&s.doc().unwrap().doc.node(id).unwrap().appearance, &shared)); +} + /// A subpath, anchor or segment of 2^32 + k fails, where k names one that exists, and the document /// and the undo history stay as they were. A 32-bit build read the number as k. #[test] @@ -3650,6 +4020,54 @@ fn cut_at_anchors_splits_paths_and_leaves_one_end_selected() { assert_eq!(undo_steps(&s), undo); } +#[test] +fn cut_at_anchors_paths_have_their_strokes_centered() { + // Every path the cut makes keeps the source's fill and strokes, every stroke centered, in one + // undo step; a path whose anchors were not selected keeps its strokes. + let mut s = session(); + let anchors = json!([{"x": 100, "y": 100}, {"x": 200, "y": 100}, {"x": 300, "y": 100}, {"x": 400, "y": 100}]); + let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap()); + let open = side_strokes(&mut s, id); + let r = rect(&mut s, 500.0, 100.0, 100.0, 100.0); + let closed = side_strokes(&mut s, r); + let other = rect(&mut s, 100.0, 300.0, 100.0, 100.0); + let untouched = side_strokes(&mut s, other); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 1], [0, 2]]})).unwrap(); + s.execute("select.anchors", &json!({"id": r.0, "anchors": [[0, 2]], "mode": "add"})).unwrap(); + assert_eq!(s.doc().unwrap().selection.anchors.len(), 2); + let undo = undo_steps(&s); + let made = s.execute("path.cutAtAnchors", &json!({})).unwrap(); + let ids: Vec<NodeId> = made["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect(); + assert_eq!(undo_steps(&s), undo + 1); + assert_eq!(ids.len(), 4, "three pieces and the opened rectangle"); + for i in &ids { + let want = if *i == r { centered(&closed) } else { centered(&open) }; + assert_eq!(appearance(&s, *i), want, "{i:?}"); + } + assert_eq!(appearance(&s, other), untouched); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((appearance(&s, id), appearance(&s, r)), (open.clone(), closed.clone()), "undo"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!((appearance(&s, id), appearance(&s, r)), (centered(&open), centered(&closed)), "redo"); + // A cut member of a compound path: the compound path's strokes, which it shows, are centered. + let a = rect(&mut s, 100.0, 450.0, 100.0, 100.0); + let b = rect(&mut s, 125.0, 475.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = s.doc().unwrap().selection.objects[0]; + let before = side_strokes(&mut s, compound); + let members: Vec<NodeId> = match &s.doc().unwrap().doc.node(compound).unwrap().kind { + NodeKind::Compound { children, .. } => children.iter().map(|c| c.id).collect(), + k => panic!("not a compound path: {k:?}"), + }; + let held = path(&s, members[1]); + s.execute("select.anchors", &json!({"id": members[0].0, "anchors": [[0, 2]]})).unwrap(); + s.execute("path.cutAtAnchors", &json!({})).unwrap(); + assert!(!path(&s, members[0]).subpaths[0].closed); + assert_eq!(path(&s, members[1]), held, "the other member keeps its shape"); + assert_eq!(appearance(&s, compound), centered(&before), "compound path"); +} + #[test] fn direct_segment_delete_keeps_the_other_rectangle_edges_and_one_undo() { for initially_selected in [false, true] { 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<u8> { 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/expand.rs b/crates/engine/src/tests/expand.rs index e4bfa26b2f..0cc0106351 100644 --- a/crates/engine/src/tests/expand.rs +++ b/crates/engine/src/tests/expand.rs @@ -455,10 +455,11 @@ fn a_symbol_instance_fill_shadow_shadows_its_filled_art() { assert!(expandable(&s), "the fill's shadow can be expanded"); run(&mut s, "effect.expandAppearance", json!({})); - let ch = node(&s, id).children().cloned().expect("the instance becomes a group"); + let n = node(&s, id); + let ch = n.children().cloned().expect("the instance becomes a group"); assert!(matches!(ch[0].kind, NodeKind::Image(_)), "the shadow is an image under the art: {}", ch[0].kind_label()); - assert!(matches!(ch[1].kind, NodeKind::SymbolInstance { .. }), "the art stays an instance: {}", ch[1].kind_label()); - no_effects_left(&ch[1]); + n.walk(&mut |part| assert!(!matches!(part.kind, NodeKind::SymbolInstance { .. }), "the art is no longer an instance")); + no_effects_left(&n); let after = render(&s); assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24)); run(&mut s, "edit.undo", json!({})); @@ -508,6 +509,311 @@ fn a_nested_symbol_instance_takes_the_outer_fill_shadow() { assert!(dark(render(&s).pixel(165, 100)), "the inner art casts the shadow: {:?}", render(&s).pixel(165, 100)); } +/// An instance of an Inner symbol of the square, with a new fill without paint on top that `inner` +/// gives effects, placed in the art of an Outer symbol; the Outer instance is selected, with a new +/// fill without paint on top. Returns the Outer instance and its new row's index. +fn nested_with_row(s: &mut Session, inner: impl FnOnce(&mut Session, NodeId, usize)) -> (NodeId, usize) { + let (inner_id, inner_row) = instance_with_row(s, "Inner", true); + inner(s, inner_id, inner_row); + let id = NodeId(run(s, "symbol.new", json!({"name": "Outer"}))["id"].as_u64().unwrap()); + run(s, "appearance.addFill", json!({"ids": [id.0]})); + let row = node(s, id).appearance.items.len() - 1; + run(s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + (id, row) +} + +/// The symbol instances and the images in `n`. +fn instances_and_images(n: &Node) -> (usize, usize) { + let mut found = (0, 0); + n.walk(&mut |part| match part.kind { + NodeKind::SymbolInstance { .. } => found.0 += 1, + NodeKind::Image(_) => found.1 += 1, + _ => {} + }); + found +} + +/// Replace the art of every symbol with an empty group. +fn empty_symbols(s: &mut Session) { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + for (i, sym) in d.symbols.iter_mut().enumerate() { + sym.art = std::sync::Arc::new(Node::group(NodeId(91_000 + i as u64), vec![])); + } +} + +/// When the outer instance's art expands, an instance in it whose own fill has a shadow becomes art +/// too, the shadow an image under it: no instance or effect is left, the look stays, and the result +/// no longer follows either symbol. +#[test] +fn a_nested_instance_fill_shadow_becomes_an_image_when_the_outer_art_expands() { + let mut s = session(); + let (id, row) = nested_with_row(&mut s, shadow_row); + offset_row(&mut s, id, row, 10.0); + let before = render(&s); + assert!(dark(before.pixel(175, 100)), "the inner art casts its shadow: {:?}", before.pixel(175, 100)); + + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + let (instances, images) = instances_and_images(&n); + assert_eq!(instances, 0, "the outer and inner instances become art"); + assert!(images >= 1, "the inner shadow is an image"); + no_effects_left(&n); + let after = render(&s); + assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24)); + empty_symbols(&mut s); + assert_eq!(differing(&after, &render(&s), 0), 0, "the expanded art no longer follows the symbols"); +} + +/// A shadow on the outer instance's fill alone: the instance becomes its art over the shadow's +/// image, and an instance in that art with a shadow of its own becomes art and an image in turn, in +/// one undo step. +#[test] +fn an_outer_fill_shadow_expands_the_instance_and_reaches_the_nested_art() { + let mut s = session(); + let (id, row) = nested_with_row(&mut s, shadow_row); + shadow_row(&mut s, id, row); + let before = render(&s); + assert!(expandable(&s)); + + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + let (instances, images) = instances_and_images(&n); + assert_eq!(instances, 0, "the outer and inner instances become art"); + assert!(images >= 2, "the outer and inner shadows are images: {images}"); + no_effects_left(&n); + let after = render(&s); + assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24)); + + run(&mut s, "edit.undo", json!({})); + assert!(matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. }), "one undo gives the instance back"); + run(&mut s, "edit.redo", json!({})); + empty_symbols(&mut s); + assert_eq!(differing(&after, &render(&s), 0), 0, "the expanded art no longer follows the symbols"); +} + +/// A blur on the nested instance's fill: the nested instance becomes the image. +#[test] +fn a_nested_instance_fill_blur_becomes_an_image_when_the_outer_art_expands() { + let mut s = session(); + let blur = |s: &mut Session, id: NodeId, row: usize| { + run(s, "effect.apply", json!({"ids": [id.0], "item": row, "effect": "blur.gaussian", "params": {"radius": 3}})); + }; + let (id, row) = nested_with_row(&mut s, blur); + offset_row(&mut s, id, row, 10.0); + let before = render(&s); + + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + let (instances, images) = instances_and_images(&n); + assert_eq!(instances, 0, "the outer and inner instances become art"); + assert_eq!(images, 1, "the blurred inner art is one image"); + no_effects_left(&n); + let after = render(&s); + assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24)); +} + +/// A blue rectangle from x 140 to 200, drawn first, so a shadow right of the square falls on it. +fn blue_backdrop(s: &mut Session) { + run(s, "shape.rectangle", json!({"x": 140, "y": 0, "width": 60, "height": 200})); + run(s, "paint.setFill", json!({"color": "#0000ff"})); +} + +/// A red Drop Shadow 20 pt to the right on row `row` of instance `id`, with no blur, painting with `mode`. +fn red_shadow_row(s: &mut Session, id: NodeId, row: usize, mode: &str) { + let params = json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": mode, "color": "#ff0000"}); + run(s, "effect.apply", json!({"ids": [id.0], "item": row, "effect": "stylize.dropShadow", "params": params})); +} + +/// The blend modes of the images in `n`, in the order the walk visits them. +fn image_modes(n: &Node) -> Vec<BlendMode> { + let mut modes = vec![]; + n.walk(&mut |part| { + if matches!(part.kind, NodeKind::Image(_)) { + modes.push(part.blend); + } + }); + modes +} + +/// A Multiply shadow on the nested instance's fill: its image multiplies with the blue art below +/// as the shadow did, rather than painting red over it. +#[test] +fn a_nested_instance_multiply_shadow_image_keeps_its_mode() { + let mut s = session(); + blue_backdrop(&mut s); + let (id, row) = nested_with_row(&mut s, |s, id, row| red_shadow_row(s, id, row, "multiply")); + offset_row(&mut s, id, row, 10.0); + let before = render(&s); + assert!(dark(before.pixel(170, 100)), "red multiplied with blue is dark: {:?}", before.pixel(170, 100)); + + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + assert_eq!(instances_and_images(&n).0, 0, "the outer and inner instances become art"); + assert_eq!(image_modes(&n), [BlendMode::Multiply]); + no_effects_left(&n); + let after = render(&s); + assert!(dark(after.pixel(170, 100)), "the image multiplies with the blue art: {:?}", after.pixel(170, 100)); + assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24)); +} + +/// A Multiply shadow on an instance's own fill: the image under its art paints with Multiply. +#[test] +fn an_instance_multiply_shadow_image_keeps_its_mode() { + let mut s = session(); + blue_backdrop(&mut s); + let (id, row) = instance_with_row(&mut s, "Square", true); + red_shadow_row(&mut s, id, row, "multiply"); + let before = render(&s); + assert!(dark(before.pixel(160, 100)), "red multiplied with blue is dark: {:?}", before.pixel(160, 100)); + + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + assert_eq!(image_modes(&n), [BlendMode::Multiply]); + let after = render(&s); + assert!(dark(after.pixel(160, 100)), "the image multiplies with the blue art: {:?}", after.pixel(160, 100)); + assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24)); +} + +/// A shadow on a hidden fill of the nested instance draws nothing, and expanding makes no image of it. +#[test] +fn a_hidden_nested_instance_fill_shadow_makes_no_image() { + let mut s = session(); + let hidden = |s: &mut Session, id: NodeId, row: usize| { + shadow_row(s, id, row); + run(s, "appearance.setItem", json!({"ids": [id.0], "index": row, "visible": false})); + }; + let (id, row) = nested_with_row(&mut s, hidden); + offset_row(&mut s, id, row, 10.0); + assert!(!dark(render(&s).pixel(175, 100)), "the hidden fill casts no shadow"); + + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + assert_eq!(instances_and_images(&n), (0, 0), "the instances become art without an image"); + no_effects_left(&n); +} + +/// A nested instance with a shadow whose symbol is missing stays as it is while the outer art +/// expands around it. +#[test] +fn a_nested_instance_of_a_missing_symbol_stays_an_instance() { + let mut s = session(); + let (id, row) = nested_with_row(&mut s, shadow_row); + offset_row(&mut s, id, row, 10.0); + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + d.symbols.retain(|sym| sym.name != "Inner"); + } + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + assert_eq!(instances_and_images(&n), (1, 0), "the inner instance stays, without an image"); +} + +/// 1,100 blurred instances in the outer art, far fewer objects than the symbol limit: one Expand +/// Appearance makes 1,024 images of them, and the other 76 stay instances with their blur, which +/// the result reports. +#[test] +fn nested_instance_raster_effects_stop_at_the_image_limit() { + let mut s = session(); + // Images of a pixel or two each. + run(&mut s, "document.rasterEffectsSettings", json!({"resolution": 1})); + let blur = |s: &mut Session, id: NodeId, row: usize| { + run(s, "effect.apply", json!({"ids": [id.0], "item": row, "effect": "blur.gaussian", "params": {"radius": 3}})); + }; + let (id, row) = nested_with_row(&mut s, blur); + offset_row(&mut s, id, row, 10.0); + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let outer = d.symbols.iter().position(|sym| sym.name == "Outer").unwrap(); + let inner = (*d.symbols[outer].art).clone(); + assert!(matches!(inner.kind, NodeKind::SymbolInstance { .. }), "the outer art is the inner instance"); + let copies = (0..1_100) + .map(|_| { + let mut copy = inner.clone(); + copy.id = d.alloc_id(); + std::sync::Arc::new(copy) + }) + .collect(); + d.symbols[outer].art = std::sync::Arc::new(Node::group(d.alloc_id(), copies)); + } + + let r = run(&mut s, "effect.expandAppearance", json!({})); + assert_eq!(r["rasterLeft"], 76, "{r}"); + assert!(r["warning"].as_str().is_some_and(|w| w.contains("1,024 images")), "{r}"); + let n = node(&s, id); + assert_eq!(instances_and_images(&n), (76, 1_024), "1,024 instances become images and the rest stay"); + n.walk(&mut |part| { + if matches!(part.kind, NodeKind::SymbolInstance { .. }) { + assert!(part.appearance.items.iter().any(|i| i.effects().iter().any(|e| e.id == "blur.gaussian")), "a left instance keeps its blur"); + } + }); +} + +/// Gives `id` a color adjustment and a blur, puts it in a group above 1,024 blurred squares, which +/// take every image one Expand Appearance makes, and expands the group. Returns `id` as it was +/// before expanding. +fn adjusted_and_left_by_the_image_limit(s: &mut Session, id: NodeId) -> Node { + // Images of a pixel or two each. + run(s, "document.rasterEffectsSettings", json!({"resolution": 1})); + run(s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "adjust.hueSaturation", "params": {"hue": 120}})); + run(s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "blur.gaussian", "params": {"radius": 3}})); + let sq = NodeId(run(s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].as_u64().unwrap()); + run(s, "effect.apply", json!({"ids": [sq.0], "item": null, "effect": "blur.gaussian", "params": {"radius": 3}})); + let before = node(s, id); + let group = { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let blurred = d.node(sq).unwrap().clone(); + d.remove(sq).unwrap(); + let mut members: Vec<_> = (0..1_024) + .map(|_| { + let mut copy = blurred.clone(); + copy.id = d.alloc_id(); + std::sync::Arc::new(copy) + }) + .collect(); + members.push(std::sync::Arc::new(before.clone())); + let group = d.alloc_id(); + *d.node_mut(id).unwrap() = Node::group(group, members); + group + }; + + let r = run(s, "effect.expandAppearance", json!({"ids": [group.0]})); + assert_eq!(r["rasterLeft"], 1, "{r}"); + before +} + +/// A symbol instance with a color adjustment and a blur, left by the image limit, stays an instance +/// of its symbol, with both effects. +#[test] +fn a_color_adjusted_instance_left_by_the_image_limit_stays_an_instance() { + let mut s = session(); + run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Adjusted Square"}))["id"].as_u64().unwrap()); + let before = adjusted_and_left_by_the_image_limit(&mut s, id); + assert!(matches!(before.kind, NodeKind::SymbolInstance { .. })); + assert_eq!(node(&s, id), before, "the instance stays as it is, with its adjustment and blur"); +} + +/// An embedded image with a color adjustment and a blur, left by the image limit, stays as it is, +/// and the document keeps no recolored copy of its pixels. +#[test] +fn a_color_adjusted_image_left_by_the_image_limit_adds_no_pixels() { + 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 r = run(&mut s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100]})); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let images: Vec<String> = s.doc().unwrap().doc.images.keys().cloned().collect(); + let before = adjusted_and_left_by_the_image_limit(&mut s, id); + assert!(matches!(before.kind, NodeKind::Image(_))); + assert_eq!(node(&s, id), before, "the image stays as it is, with its adjustment and blur"); + // Besides the squares' images, the document holds the image's pixels alone. + let after: Vec<String> = s.doc().unwrap().doc.images.keys().filter(|k| !k.starts_with("raster-effect-")).cloned().collect(); + assert_eq!(after, images, "no recolored copy stays in the document"); +} + /// Export draws a symbol instance's fill shadow on the filled shapes of its art: baking leaves the /// shadow on the art's fill, not its stroke, and PDF export makes an image of it. #[test] 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<f64> = 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<f64> = 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 8a152cd44e..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] @@ -582,3 +601,233 @@ fn an_untitled_document_saved_to_a_file_exports_titled_after_it() { } let _ = std::fs::remove_dir_all(dir); } + +/// A session whose metadata templates folder is `dir/Metadata Templates`, with a document titled +/// Poster. +fn template_session(dir: &std::path::Path) -> Session { + let mut s = session(); + s.attach_metadata_templates_dir(dir.join("Metadata Templates")); + s +} + +#[test] +fn a_saved_metadata_template_is_listed_and_applies_to_another_document() { + let dir = vectorcraft_testkit::TempDir::new("fileinfo-template"); + let mut s = template_session(&dir); + assert_eq!(s.execute("file.info.templates", &json!({})).unwrap()["templates"], json!([]), "no folder yet"); + s.execute("file.info", &info()).unwrap(); + let r = s.execute("file.info.saveTemplate", &json!({"name": " Studio "})).unwrap(); + assert_eq!(r["name"], "Studio"); + let path = dir.join("Metadata Templates").join("Studio.xmp"); + assert!(path.is_file(), "saved into the folder: {r}"); + let listed = s.execute("file.info.templates", &json!({})).unwrap(); + assert_eq!(listed["templates"][0]["name"], "Studio"); + assert_eq!(listed["templates"].as_array().map(Vec::len), Some(1)); + // A name that isn't a usable file name as it is is refused, so `a/b` and `a?b` never share a file. + for name in ["a/b", "a?b", "CON", "Studio.", "x\u{1}"] { + assert!(s.execute("file.info.saveTemplate", &json!({"name": name})).is_err(), "{name}"); + } + assert_eq!(s.execute("file.info.templates", &json!({})).unwrap()["templates"].as_array().map(Vec::len), Some(1)); + // Saving is not an edit of the document. + assert_eq!(s.doc().unwrap().history.undo.len(), 1); + // Into a new document, by name, in one undo step. + s.execute("file.new", &json!({"width": 100, "height": 80})).unwrap(); + let r = s.execute("file.info.applyTemplate", &json!({"name": "Studio", "mode": "keep"})).unwrap(); + assert_eq!(r["changed"], true); + let m = &s.doc().unwrap().doc.metadata; + assert_eq!((m.author.as_str(), m.author_title.as_str(), m.rating), ("Ada Lovelace", "Designer", 4)); + assert_eq!(m.keywords, ["fair", "Poster", "print"]); + assert_eq!((m.copyright_status, m.copyright_notice.as_str()), (CopyrightStatus::Copyrighted, "(c) 2026 Ada")); + assert_eq!(m.description, "A poster\nfor the fair"); + assert_eq!(r["title"], "Poster", "the template carries the title of its own"); + assert_eq!(s.doc().unwrap().history.undo.len(), 1); + // Applied again, nothing changes and nothing is recorded. + let r = s.execute("file.info.applyTemplate", &json!({"path": path.to_str().unwrap(), "mode": "keep"})).unwrap(); + assert_eq!(r["changed"], false); + assert_eq!(s.doc().unwrap().history.undo.len(), 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.metadata.author, ""); + // The same name replaces the template. + s.execute("file.info.saveTemplate", &json!({"name": "Studio", "fields": {"author": "Grace"}})).unwrap(); + let back = vectorcraft_pdf::read_template(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(back.author.as_deref(), Some("Grace")); + assert_eq!(back.title, None, "an Untitled-N title is not written"); +} + +#[test] +fn a_metadata_template_merges_in_three_modes() { + let mut s = session(); + s.execute("file.info", &json!({"author": "Ada", "keywords": ["fair"], "rating": 2, "copyrightUrl": "https://example.com/a"})).unwrap(); + let template = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { + author: Some("Grace".into()), + description: Some("From the template".into()), + keywords: Some(vec!["print".into(), "Fair".into()]), + rating: Some(5), + copyrighted: Some(false), + ..Default::default() + }); + let merged = + |s: &mut Session, mode: &str| s.execute("file.info.applyTemplate", &json!({"data": template, "mode": mode, "apply": false})).unwrap(); + // Clear and replace: the fields the template lacks are cleared; the title stays. + let r = merged(&mut s, "replace"); + assert_eq!((r["author"].as_str(), r["description"].as_str(), r["rating"].as_u64()), (Some("Grace"), Some("From the template"), Some(5))); + assert_eq!( + (r["keywords"].clone(), r["copyrightUrl"].as_str(), r["copyrightStatus"].as_str()), + (json!(["print", "Fair"]), Some(""), Some("publicDomain")) + ); + assert_eq!(r["title"], "Poster"); + // Keep and replace: the template's fields replace those it has; the others stay. + let r = merged(&mut s, "keep"); + assert_eq!((r["author"].as_str(), r["rating"].as_u64(), r["copyrightUrl"].as_str()), (Some("Grace"), Some(5), Some("https://example.com/a"))); + assert_eq!(r["keywords"], json!(["print", "Fair"])); + // Keep and append: keywords are added (each once), and only empty fields are filled. + let r = merged(&mut s, "append"); + assert_eq!((r["author"].as_str(), r["rating"].as_u64(), r["description"].as_str()), (Some("Ada"), Some(2), Some("From the template"))); + assert_eq!((r["keywords"].clone(), r["copyrightStatus"].as_str()), (json!(["fair", "print"]), Some("publicDomain"))); + // `apply: false` changed nothing; `base` merges into the given fields instead. + assert_eq!(s.doc().unwrap().history.undo.len(), 1); + assert_eq!(s.doc().unwrap().doc.metadata.author, "Ada"); + let r = s.execute("file.info.applyTemplate", &json!({"data": template, "mode": "append", "apply": false, "base": {"author": ""}})).unwrap(); + assert_eq!(r["author"], "Grace"); + // Applied: one undo step. + s.execute("file.info.applyTemplate", &json!({"data": template, "mode": "replace"})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), 2); + assert_eq!(s.doc().unwrap().doc.metadata.copyright_url, ""); +} + +#[test] +fn metadata_template_errors() { + let dir = vectorcraft_testkit::TempDir::new("fileinfo-template-errors"); + let mut s = template_session(&dir); + let xmp = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Ada".into()), ..Default::default() }); + let not_xmp = dir.join("note.xmp"); + std::fs::write(¬_xmp, "<note>not metadata</note>").unwrap(); + let big = dir.join("big.xmp"); + std::fs::write(&big, vec![b' '; vectorcraft_pdf::MAX_TEMPLATE_BYTES + 1]).unwrap(); + let e = s.execute("file.info.applyTemplate", &json!({"path": big.to_str().unwrap(), "mode": "keep"})).unwrap_err(); + assert!(e.to_string().contains("larger than 8 MB"), "{e}"); + let e = s.execute("file.info.applyTemplate", &json!({"data": " ".repeat(vectorcraft_pdf::MAX_TEMPLATE_BYTES + 1), "mode": "keep"})).unwrap_err(); + assert!(e.to_string().contains("larger than 8 MB"), "{e}"); + for bad in [ + json!({"data": xmp, "mode": "merge"}), + json!({"data": xmp}), + json!({"data": xmp, "mode": 3}), + json!({"mode": "keep"}), + json!({"data": xmp, "path": not_xmp.to_str().unwrap(), "mode": "keep"}), + json!({"path": dir.join("missing.xmp").to_str().unwrap(), "mode": "keep"}), + json!({"path": not_xmp.to_str().unwrap(), "mode": "keep"}), + json!({"path": big.to_str().unwrap(), "mode": "keep"}), + json!({"name": "missing", "mode": "keep"}), + json!({"data": "Ada Lovelace", "mode": "keep"}), + json!({"data": xmp, "mode": "keep", "apply": "yes"}), + json!({"data": xmp, "mode": "keep", "base": [1]}), + json!({"data": xmp, "mode": "keep", "base": {"rating": 9}}), + ] { + assert!(s.execute("file.info.applyTemplate", &bad).is_err(), "{bad}"); + } + for bad in [json!({"name": "a", "path": "b.xmp"}), json!({"name": " "}), json!({"fields": {"rating": 9}}), json!({"fields": "x"})] { + assert!(s.execute("file.info.saveTemplate", &bad).is_err(), "{bad}"); + } + assert_eq!(s.doc().unwrap().history.undo.len(), 0); + assert!(!dir.join("Metadata Templates").exists(), "no failed save made the folder"); + // A link in the folder is not followed, by its name or its file name. + #[cfg(unix)] + { + let outside = dir.join("outside.xmp"); + std::fs::write(&outside, &xmp).unwrap(); + std::fs::create_dir_all(dir.join("Metadata Templates")).unwrap(); + std::os::unix::fs::symlink(&outside, dir.join("Metadata Templates").join("Linked.xmp")).unwrap(); + for name in ["Linked", "Linked.xmp"] { + assert!(s.execute("file.info.applyTemplate", &json!({"name": name, "mode": "keep"})).is_err(), "{name}"); + } + let e = s.execute("file.info.applyTemplate", &json!({"name": "Linked", "mode": "keep"})).unwrap_err(); + assert!(e.to_string().contains("not a file"), "{e}"); + assert_eq!(s.execute("file.info.templates", &json!({})).unwrap()["templates"], json!([])); + // A save by that name leaves the linked file as it was. + let e = s.execute("file.info.saveTemplate", &json!({"name": "Linked", "fields": {"author": "Grace"}})).unwrap_err(); + assert!(e.to_string().contains("not a file"), "{e}"); + assert_eq!(std::fs::read_to_string(&outside).unwrap(), xmp); + std::fs::remove_dir_all(dir.join("Metadata Templates")).unwrap(); + } + // Without a folder (runs without preferences), a name is an error, the data comes back, and + // the list is empty. + let mut s = session(); + assert!(s.execute("file.info.saveTemplate", &json!({"name": "Studio"})).is_err()); + let data = s.execute("file.info.saveTemplate", &json!({"fields": {"author": "Ada"}})).unwrap()["data"].as_str().unwrap().to_string(); + assert_eq!(vectorcraft_pdf::read_template(data.as_bytes()).unwrap().author.as_deref(), Some("Ada")); + assert_eq!(s.execute("file.info.templates", &json!({"create": true})).unwrap(), json!({"templates": []})); +} + +#[test] +fn the_templates_folder_lists_only_xmp_files_and_can_be_made() { + let dir = vectorcraft_testkit::TempDir::new("fileinfo-template-list"); + let mut s = template_session(&dir); + let r = s.execute("file.info.templates", &json!({"create": true})).unwrap(); + let folder = dir.join("Metadata Templates"); + assert!(folder.is_dir()); + assert_eq!(r["folder"], folder.to_str().unwrap()); + for f in ["b.XMP", "a.xmp", "notes.txt", ".xmp"] { + std::fs::write(folder.join(f), "x").unwrap(); + } + std::fs::create_dir(folder.join("c.xmp")).unwrap(); + // Other files, however many, leave the templates listed. + for i in 0..1000 { + std::fs::write(folder.join(format!("{i:04}.txt")), "").unwrap(); + } + let names: Vec<String> = s.execute("file.info.templates", &json!({})).unwrap()["templates"] + .as_array() + .unwrap() + .iter() + .map(|t| t["name"].as_str().unwrap().to_string()) + .collect(); + assert_eq!(names, ["a", "b"]); + // A listed name opens whatever the case of its extension. + let xmp = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Grace".into()), ..Default::default() }); + std::fs::write(folder.join("b.XMP"), xmp).unwrap(); + let r = s.execute("file.info.applyTemplate", &json!({"name": "b", "mode": "keep"})).unwrap(); + assert_eq!(r["author"], "Grace"); + // Its listed file name opens it too. + let listed = s.execute("file.info.templates", &json!({})).unwrap(); + assert_eq!(listed["templates"][1]["file"], "b.XMP"); + let r = s.execute("file.info.applyTemplate", &json!({"name": "b.XMP", "mode": "replace", "apply": false})).unwrap(); + assert_eq!(r["author"], "Grace"); + // A listed file name is taken before the name with `.xmp` added. + let ada = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Ada".into()), ..Default::default() }); + std::fs::write(folder.join("b.XMP.xmp"), ada).unwrap(); + let r = s.execute("file.info.applyTemplate", &json!({"name": "b.XMP", "mode": "replace", "apply": false})).unwrap(); + assert_eq!(r["author"], "Grace"); + let r = s.execute("file.info.applyTemplate", &json!({"name": "b.XMP.xmp", "mode": "replace", "apply": false})).unwrap(); + assert_eq!(r["author"], "Ada"); + // A name that is not a file name never opens the template its safe form names. + let grace = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Grace".into()), ..Default::default() }); + std::fs::write(folder.join("a-b.xmp"), grace).unwrap(); + let r = s.execute("file.info.applyTemplate", &json!({"name": "a-b", "mode": "replace", "apply": false})).unwrap(); + assert_eq!(r["author"], "Grace"); + for name in ["a/b", "a\\b", "a:b"] { + let e = s.execute("file.info.applyTemplate", &json!({"name": name, "mode": "replace", "apply": false})).unwrap_err(); + assert!(e.to_string().contains("isn't usable as a file name"), "{name}: {e}"); + } +} + +#[test] +fn the_largest_file_info_saves_a_template_that_imports() { + let mut s = session(); + let text = "\"&".repeat(32_768); + let keywords: Vec<String> = (0..1000).map(|i| format!("{i:04}{}", "\"".repeat(252))).collect(); + let fields = json!({ + "author": text, "authorTitle": text, "description": text, "copyrightNotice": text, + "copyrightUrl": format!("https://example.com/{}", "&".repeat(2000)), "keywords": keywords, "rating": 5, "copyrightStatus": "copyrighted", + }); + let data = s.execute("file.info.saveTemplate", &json!({"fields": fields})).unwrap()["data"].as_str().unwrap().to_string(); + assert!(data.len() > 1 << 20, "{} bytes", data.len()); + let r = s.execute("file.info.applyTemplate", &json!({"data": data, "mode": "replace"})).unwrap(); + assert_eq!((r["author"].as_str(), r["keywords"].as_array().map(Vec::len)), (Some(text.as_str()), Some(1000))); +} + +#[test] +fn a_pdf_opens_with_the_rating_and_author_title_its_packet_gives() { + let mut m = DocMetadata::default(); + let f = vectorcraft_pdf::FileInfo { author_title: Some("Editor".into()), rating: Some(3), ..Default::default() }; + crate::cmd::fileinfo::read_pdf(&mut m, f); + assert_eq!((m.author_title.as_str(), m.rating), ("Editor", 3)); +} diff --git a/crates/engine/src/tests/fontlist.rs b/crates/engine/src/tests/fontlist.rs index 6202a8ce70..62110be5a2 100644 --- a/crates/engine/src/tests/fontlist.rs +++ b/crates/engine/src/tests/fontlist.rs @@ -34,6 +34,59 @@ fn the_font_list_names_every_available_family_with_its_styles() { assert!(s.execute("text.fontList", &json!({"family": "No Such Font"})).is_err()); } +/// Show Similar Fonts (`text.similarFonts`): every listed family, the asked one first, in the +/// order the font menus show; bad params are refused. +#[test] +fn similar_fonts_lists_every_family_by_likeness() { + let mut s = Session::new(); + let db = FontDb::global(); + let r = s.execute("text.similarFonts", &json!({"family": "source sans 3"})).unwrap(); + assert_eq!(r["family"], "Source Sans 3"); + let order = names(&r["families"]); + assert_eq!(order.first().map(String::as_str), Some("Source Sans 3")); + let mut sorted = order.clone(); + sorted.sort(); + let mut listed = db.menu_family_list().to_vec(); + listed.sort(); + // Other tests running at the same time add and remove composite fonts; the installed families are compared. + let installed_only = |list: &[String]| list.iter().filter(|f| db.has_installed_family(f)).cloned().collect::<Vec<_>>(); + assert_eq!(installed_only(&sorted), installed_only(&listed), "every family once"); + // The two answers are compared whole when the available fonts did not change while both were + // made (the same `FontDb::generation`), and by their installed families when they changed + // during every try. + let mut answers = (vec![], vec![], false); + for _ in 0..20 { + let generation = db.generation(); + let all = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3"})).unwrap()["families"]); + let two = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3", "limit": 2})).unwrap()["families"]); + let unchanged = db.generation() == generation; + answers = (all, two, unchanged); + if unchanged { + break; + } + } + let (all, two, unchanged) = answers; + assert_eq!(two.len(), 2); + if unchanged { + assert_eq!(two, all[..2], "the first families, in order"); + } else { + let (two, all) = (installed_only(&two), installed_only(&all)); + assert_eq!(two[..], all[..two.len()], "the first installed families, in order"); + } + for (params, error) in [ + (json!({}), "`family` is required"), + (json!({"family": " "}), "`family` is required"), + (json!({"family": 3}), "`family` must be a string"), + (json!({"family": "No Such Font"}), "font family `No Such Font` is not available"), + (json!({"family": "Inter", "limit": 0}), "`limit` must be a whole number from 1 to 100000"), + (json!({"family": "Inter", "limit": 2.5}), "`limit` must be a whole number from 1 to 100000"), + (json!({"family": "Inter", "limit": "2"}), "`limit` must be a whole number from 1 to 100000"), + ] { + let e = s.execute("text.similarFonts", ¶ms).unwrap_err().to_string(); + assert!(e.contains(error), "{params}: {e}"); + } +} + #[test] fn refreshing_the_font_list_redraws_type_without_editing_the_document() { let mut s = Session::new(); @@ -49,6 +102,41 @@ fn refreshing_the_font_list_redraws_type_without_editing_the_document() { assert!(!d.is_dirty(), "nothing to save"); } +/// `text.glyphCategories` lists the kinds of glyph a font's OpenType features give, with a +/// stylistic set's name, and refuses a font that isn't available and params that aren't strings. +#[test] +fn glyph_categories_list_the_glyphs_of_each_kind_of_feature() { + use vectorcraft_text::test_fonts::{CATEGORIES_FAMILY, categories_font, source_sans_gid}; + FontDb::global().add_font(categories_font().expect("the test font builds")); + let mut s = Session::new(); + let g = |c| u32::from(source_sans_gid(c).expect("a glyph")); + let mut figures = vec![g('7'), g('8')]; + figures.sort_unstable(); + let r = s.execute("text.glyphCategories", &json!({"family": CATEGORIES_FAMILY})).unwrap(); + assert_eq!(r["family"], CATEGORIES_FAMILY); + assert_eq!(r["style"], "Regular"); + assert_eq!( + r["categories"], + json!([ + {"id": "ligatures", "glyphs": [g('L')]}, + {"id": "ss02", "name": "Round Dots", "glyphs": [g('G')]}, + {"id": "smallCaps", "glyphs": [g('B')]}, + {"id": "figures", "glyphs": figures}, + ]) + ); + assert_eq!(s.execute("text.glyphCategories", &json!({"family": CATEGORIES_FAMILY, "style": "regular"})).unwrap(), r); + for (p, says) in [ + (json!({}), "missing `family`"), + (json!({"family": 3}), "`family` must be a string"), + (json!({"family": "No Such Font"}), "is not available"), + (json!({"family": CATEGORIES_FAMILY, "style": "Black"}), "is not available"), + (json!({"family": CATEGORIES_FAMILY, "style": true}), "`style` must be a string"), + ] { + let e = s.execute("text.glyphCategories", &p).unwrap_err().to_string(); + assert!(e.contains(says), "{p}: {e}"); + } +} + /// Refreshing the font list while a background save writes the file leaves the document saved /// once the file is written. #[test] diff --git a/crates/engine/src/tests/gradient.rs b/crates/engine/src/tests/gradient.rs index 9f404b050d..14cdb653b5 100644 --- a/crates/engine/src/tests/gradient.rs +++ b/crates/engine/src/tests/gradient.rs @@ -377,14 +377,15 @@ fn annotator_gestures_edit_the_gradient_as_single_undo_steps() { assert_eq!(stops.len(), 3); assert!((stops[1].offset - 0.3).abs() < 1e-6); assert_eq!(s.selected_stop(), Some(1)); - // Dragging the end handle changes only the end, as one undo step. + // Dragging the end handle changes only the length (the end stays on the bar's line), as one + // undo step. let undo = s.doc().unwrap().history.undo.len(); gesture( &mut s, &[(PointerKind::Down, 200.0, 150.0), (PointerKind::Drag, 210.0, 160.0), (PointerKind::Drag, 220.0, 170.0), (PointerKind::Up, 220.0, 170.0)], ); let g = fill_geom(&s, id); - assert_eq!((g.start, g.end), (Point::new(100.0, 150.0), Point::new(220.0, 170.0))); + assert_eq!((g.start, g.end), (Point::new(100.0, 150.0), Point::new(220.0, 150.0))); assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); s.execute("edit.undo", &json!({})).unwrap(); // The selected stop takes Delete ahead of edit.clear; the object stays. diff --git a/crates/engine/src/tests/gradspan.rs b/crates/engine/src/tests/gradspan.rs index 9674204642..664afdbdb6 100644 --- a/crates/engine/src/tests/gradspan.rs +++ b/crates/engine/src/tests/gradspan.rs @@ -119,6 +119,28 @@ fn strokes_span_the_targets_too() { assert!(ga.start.x < 0.0 && ga.end.x > 400.0, "the stroke's box, half its weight out: {ga:?}"); } +#[test] +fn a_lower_stroke_row_spans_the_box_that_row_paints() { + let mut s = session(); + let a = rect(&mut s, 0.0, 50.0, 100.0, 100.0); + let b = rect(&mut s, 300.0, 50.0, 100.0, 100.0); + // [Fill, Stroke 40 pt, Stroke 1 pt] on both. + s.execute("appearance.addStroke", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("stroke.set", &json!({"ids": [a.0, b.0], "item": 1, "weight": 40})).unwrap(); + for aligned in [false, true] { + s.execute("paint.setStroke", &json!({"ids": [a.0, b.0], "item": 1, "aligned": aligned, "gradient": black_to_white(), "span": "selection"})) + .unwrap(); + for id in [a, b] { + let Paint::Gradient(g) = &s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_at(Some(1)).unwrap().paint else { + panic!("expected a gradient on stroke row 1") + }; + // The 40 pt row reaches 20 pt past the union 0..400, not the 1 pt topmost stroke's 0.5 pt. + let geom = g.geom.expect("placed in document coordinates"); + assert!(near(geom.start, Point::new(-20.0, 100.0)) && near(geom.end, Point::new(420.0, 100.0)), "aligned {aligned}, {id:?}: {geom:?}"); + } + } +} + #[test] fn the_new_art_default_stays_unplaced() { let mut s = session(); diff --git a/crates/engine/src/tests/interactivity.rs b/crates/engine/src/tests/interactivity.rs index dadc4c21c6..98feeedcbb 100644 --- a/crates/engine/src/tests/interactivity.rs +++ b/crates/engine/src/tests/interactivity.rs @@ -341,3 +341,139 @@ fn svg_output_keeps_linked_javascript_files_a_caller_may_read() { let text = run(&mut s, "document.serialize", json!({"format": "svg"}))["text"].as_str().unwrap().to_string(); assert!(text.contains(&format!("<script xlink:href=\"{outside}\"/>")), "{text}"); } + +/// The JavaScript files that the native document a `document.serialize` reply carries links. +fn carried_scripts(r: &Value) -> Vec<String> { + let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + let native = if bytes.starts_with(b"%PDF") { vectorcraft_pdf::editing(&bytes).expect("editing data").data } else { bytes }; + vectorcraft_format::load(&native).unwrap().svg_scripts +} + +/// A caller confined to read roots: every output that carries the native document (a native file +/// or template, a `.ai` or EPS file, a PDF with Preserve Editing, a package) of a document that +/// links a JavaScript file outside them is refused before a file or folder is written, with an +/// error that names no file or folder, and the document keeps the link. +#[test] +fn confined_native_output_refuses_a_linked_javascript_file_outside_the_read_roots() { + let away = Folder::new("native-script-away"); + let home = Folder::new("native-script-home"); + let script = away.file("menu.js"); + let mut s = session(); + let a = rect(&mut s, 10.0); + run(&mut s, "svgInteractivity.addFile", json!({"file": script})); + run(&mut s, "assets.add", json!({"ids": [a.0]})); + let own = home.file("own.vectorcraft"); + run(&mut s, "file.saveAs", json!({"path": own})); + let before = std::fs::read(&own).unwrap(); + rect(&mut s, 50.0); + let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[&home.0]).unwrap().unwrap(); + let hidden = [away.0.to_string_lossy().into_owned(), home.0.to_string_lossy().into_owned(), "menu.js".to_string()]; + let refused = |s: &mut Session, cmd: &str, p: Value| { + let e = crate::file_access::confine(Some(&roots), || s.execute(cmd, &p)).expect_err(cmd); + assert!(matches!(e, EngineError::BadParams { .. }), "{cmd} {p}: {e:?}"); + let e = e.to_string(); + assert!(e.contains("a linked JavaScript file is outside the read roots"), "{cmd} {p}: {e}"); + for h in &hidden { + assert!(!e.contains(h.as_str()), "{cmd} {p} names {h}: {e}"); + } + }; + let file = |name: &str| home.file(name); + let out = file("out"); + refused(&mut s, "document.serialize", json!({})); + for format in ["vectorcraft", "template", "pdf", "ai", "eps"] { + refused(&mut s, "document.serialize", json!({"format": format})); + refused(&mut s, "document.export", json!({"format": format})); + refused(&mut s, "document.export", json!({"format": format, "selectedOnly": true})); + refused(&mut s, "document.exportSelection", json!({"format": format})); + } + // Every artboard picked, and Preserve Editing asked for. + refused(&mut s, "document.serialize", json!({"format": "pdf", "range": "1", "preserveEditing": true})); + refused(&mut s, "document.serialize", json!({"format": "ai", "artboards": [0], "pdfCompatible": false})); + refused(&mut s, "document.export", json!({"format": "pdf", "path": file("export.pdf")})); + refused(&mut s, "document.export", json!({"format": "ai", "path": file("export.ai")})); + refused(&mut s, "document.export", json!({"format": "eps", "path": file("export.eps")})); + refused(&mut s, "document.export", json!({"format": "vectorcraft", "path": file("export.vectorcraft")})); + refused(&mut s, "document.exportPdf", json!({})); + refused(&mut s, "document.exportPdf", json!({"path": file("direct.pdf")})); + refused(&mut s, "document.exportEps", json!({"path": file("direct.eps")})); + refused(&mut s, "document.save", json!({})); + refused(&mut s, "document.save", json!({"path": file("save.pdf")})); + refused(&mut s, "file.saveAs", json!({"path": file("save-as.ai")})); + // A saved `.ai` file has the artboards as its pages, whatever `useArtboards` says. + refused(&mut s, "file.saveAs", json!({"path": file("save-as-art.ai"), "useArtboards": false})); + refused(&mut s, "file.saveAs", json!({"path": file("save-as.eps")})); + refused(&mut s, "file.saveCopy", json!({"path": file("copy.vectorcraft")})); + refused(&mut s, "file.saveAsTemplate", json!({})); + refused(&mut s, "file.saveAsTemplate", json!({"format": "ait"})); + refused(&mut s, "document.exportForScreens", json!({"folder": out, "formats": [{"format": "png"}, {"format": "vectorcraft"}]})); + refused(&mut s, "document.exportForScreens", json!({"zip": true, "formats": [{"format": "pdf", "preserveEditing": true}]})); + refused(&mut s, "assets.export", json!({"folder": out, "formats": [{"format": "ai"}]})); + refused(&mut s, "assets.export", json!({"folder": out, "formats": [{"format": "eps"}]})); + refused(&mut s, "file.package", json!({"folder": out})); + refused(&mut s, "file.package", json!({})); + assert_eq!(std::fs::read(&own).unwrap(), before, "the document's own file is left as it was"); + let written: Vec<_> = std::fs::read_dir(&home.0).unwrap().map(|e| e.unwrap().file_name()).collect(); + assert_eq!(written, ["own.vectorcraft"]); + assert_eq!(s.doc().unwrap().doc.svg_scripts, [script]); +} + +/// A confined caller still writes the outputs that carry no native document (a PDF without +/// Preserve Editing, a PDF or `.ai` file of the art's bounds or of some artboards, a legacy `.ai` +/// file, an image), and +/// native outputs that link only JavaScript files it may read keep them as stored. A caller without +/// roots writes a file outside them too. +#[test] +fn confined_output_without_the_document_or_with_scripts_the_caller_may_read_is_written() { + let away = Folder::new("native-script-kept-away"); + let home = Folder::new("native-script-kept-home"); + let outside = away.file("menu.js"); + let mut s = session(); + rect(&mut s, 10.0); + run(&mut s, "artboard.new", json!({"x": 200, "y": 0, "width": 100, "height": 100})); + run(&mut s, "svgInteractivity.addFile", json!({"file": outside})); + let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[&home.0]).unwrap().unwrap(); + let written = |s: &mut Session, cmd: &str, p: Value| { + crate::file_access::confine(Some(&roots), || s.execute(cmd, &p)).unwrap_or_else(|e| panic!("{cmd} {p}: {e}")) + }; + for p in [ + json!({"format": "pdf", "preserveEditing": false}), + json!({"format": "pdf", "useArtboards": false}), + json!({"format": "pdf", "range": "2"}), + json!({"format": "ai", "artboards": [1]}), + json!({"format": "ai", "useArtboards": false}), + json!({"format": "ai", "aiVersion": "7"}), + json!({"format": "png"}), + ] { + written(&mut s, "document.serialize", p); + } + written(&mut s, "document.exportPdf", json!({"preserveEditing": false})); + written(&mut s, "document.exportForScreens", json!({"zip": true, "formats": [{"format": "pdf"}]})); + // A PDF of each artboard leaves the editing data out: it holds one of the two. + written(&mut s, "document.exportForScreens", json!({"zip": true, "formats": [{"format": "pdf", "preserveEditing": true}]})); + let refused = |s: &mut Session, p: Value| { + let e = crate::file_access::confine(Some(&roots), || s.execute("document.exportForScreens", &p)).expect_err("refused").to_string(); + assert!(e.contains("a linked JavaScript file is outside the read roots"), "{p}: {e}"); + }; + // One PDF of both artboards, and Full Document's PDF of every artboard, carry it. + refused(&mut s, json!({"zip": true, "pdfs": "single", "formats": [{"format": "pdf", "preserveEditing": true}]})); + refused(&mut s, json!({"zip": true, "fullDocument": true, "formats": [{"format": "pdf", "preserveEditing": true}]})); + // Without roots, the native document keeps a file outside them. + let r = run(&mut s, "document.serialize", json!({})); + assert_eq!(carried_scripts(&r), [outside.as_str()]); + // Files the caller may read: inside the read roots, relative to the document's folder, a URL. + let inside = home.file("menu.js"); + let url = "https://example.com/scripts/menu.js"; + let kept = [inside.as_str(), "lib/tools.js", url]; + let mut s = session(); + rect(&mut s, 10.0); + for file in kept { + run(&mut s, "svgInteractivity.addFile", json!({"file": file})); + } + run(&mut s, "file.saveAs", json!({"path": home.file("doc.vectorcraft")})); + for format in ["vectorcraft", "pdf"] { + let r = written(&mut s, "document.serialize", json!({"format": format})); + assert_eq!(carried_scripts(&r), kept, "{format}"); + } + written(&mut s, "document.exportPdf", json!({"path": home.file("doc.pdf")})); + written(&mut s, "file.package", json!({})); +} diff --git a/crates/engine/src/tests/keyanchor.rs b/crates/engine/src/tests/keyanchor.rs index 0dc6675f2a..fb5e319bb9 100644 --- a/crates/engine/src/tests/keyanchor.rs +++ b/crates/engine/src/tests/keyanchor.rs @@ -1,6 +1,7 @@ -//! #1636: the key anchor. With Direct Selection, the point a Shift-click adds to two or more -//! selected anchor points is the key anchor; Align moves the other points to it, Distribute with a -//! spacing places them from it, and it stays in place. +//! #1636: the key anchor. When multiple anchors are selected with Direct Selection, +//! clicking an already-selected anchor point without modifiers designates it as the key anchor; +//! Align moves the other points to it, Distribute with a spacing places them from it, and it stays in place. +//! Deselecting, pressing Escape, or clicking canvas clears the key anchor designation. use serde_json::json; use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; @@ -34,56 +35,148 @@ fn click(s: &mut Session, x: f64, y: f64, shift: bool) { } #[test] -fn a_shift_click_makes_the_key_anchor_and_a_plain_click_narrows_the_selection() { +fn clicking_an_already_selected_anchor_makes_it_the_key_anchor() { let mut s = session(); let id = path(&mut s, "M100 40 L200 60 L150 160 Z"); s.select_tool("directSelection", ViewInfo::default()).unwrap(); + // 1st click selects point (0, 0) alone. click(&mut s, 100.0, 40.0, false); assert_eq!(key_anchor(&s), None, "one point: no key anchor"); + // Shift-click adds point (0, 2) to selection. No key anchor yet. click(&mut s, 150.0, 160.0, true); - assert_eq!(key_anchor(&s), Some((id, (0, 2))), "the point the Shift-click added"); + assert_eq!(key_anchor(&s), None, "Shift-click only adds to selection"); + // Shift-click adds point (0, 1) to selection. No key anchor yet. click(&mut s, 200.0, 60.0, true); - assert_eq!(key_anchor(&s), Some((id, (0, 1))), "the last point added"); + assert_eq!(key_anchor(&s), None, "Shift-click only adds to selection"); + + // Clicking an already-selected anchor without modifiers designates it as the Key Anchor. + click(&mut s, 200.0, 60.0, false); + assert_eq!(key_anchor(&s), Some((id, (0, 1))), "clicking selected anchor designates key anchor"); let inspect = s.execute("document.inspect", &json!({})).unwrap(); assert_eq!(inspect["keyAnchor"], json!({"id": id.0, "anchor": [0, 1]})); - // A Shift-click on the key anchor deselects it, and there is no key anchor. - click(&mut s, 200.0, 60.0, true); - assert_eq!(key_anchor(&s), None); - click(&mut s, 200.0, 60.0, true); - // A plain click on one of the selected points selects that point alone. - click(&mut s, 100.0, 40.0, false); + + // Clicking the key anchor again cancels the key anchor. + click(&mut s, 200.0, 60.0, false); + assert_eq!(key_anchor(&s), None, "clicking key anchor again cancels it"); + let inspect = s.execute("document.inspect", &json!({})).unwrap(); + assert!(inspect["keyAnchor"].is_null()); + + // Clicking another selected anchor designates that one as the key anchor. + click(&mut s, 150.0, 160.0, false); + assert_eq!(key_anchor(&s), Some((id, (0, 2)))); + + // Pressing Escape cancels the key anchor designation while keeping points selected. + s.tool_key(vectorcraft_tools::ToolKey::Escape, Mods::default(), ViewInfo::default()).unwrap(); + assert_eq!(key_anchor(&s), None, "Escape cancels key anchor"); let sel = &s.doc().unwrap().selection; - assert_eq!(sel.anchors.get(&id).map(|a| a.iter().copied().collect::<Vec<_>>()), Some(vec![(0, 0)])); - assert_eq!(sel.key_anchor, None); + assert_eq!(sel.anchors.get(&id).map(|a| a.len()), Some(3), "points remain selected"); + + // Designate key anchor: + click(&mut s, 150.0, 160.0, false); + assert_eq!(key_anchor(&s), Some((id, (0, 2)))); + + // Canvas click clears selection and key anchor. + click(&mut s, 500.0, 500.0, false); // canvas click + assert_eq!(key_anchor(&s), None, "canvas click clears key anchor"); + assert!(s.doc().unwrap().selection.is_empty(), "canvas click clears selection"); + + // Re-select multiple anchors: + click(&mut s, 100.0, 40.0, false); // select (0, 0) + click(&mut s, 200.0, 60.0, true); // add (0, 1) + assert_eq!(key_anchor(&s), None); + click(&mut s, 200.0, 60.0, false); // make (0, 1) key anchor + assert_eq!(key_anchor(&s), Some((id, (0, 1)))); + + // Shift-click on the key anchor deselects it, clearing the key anchor. + click(&mut s, 200.0, 60.0, true); + assert_eq!(key_anchor(&s), None, "deselecting key anchor clears it"); } #[test] fn align_moves_the_other_points_to_the_key_anchor() { let mut s = session(); let id = path(&mut s, "M100 40 L200 60 L150 160 L60 120 Z"); - s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); - assert_eq!(key_anchor(&s), None, "a set selects no key anchor"); - s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 2]], "mode": "add"})).unwrap(); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap(); + assert_eq!(key_anchor(&s), None, "set selects no key anchor"); + s.execute("select.key", &json!({"id": id.0, "anchor": [0, 2]})).unwrap(); assert_eq!(key_anchor(&s), Some((id, (0, 2)))); + + // Horizontal Left aligns other selected points to key anchor's x (150). s.execute("object.align", &json!({"horizontal": "left"})).unwrap(); assert_eq!(pts(&s, id), [(150.0, 40.0), (150.0, 60.0), (150.0, 160.0), (60.0, 120.0)], "to the key anchor's x"); + + // Vertical Bottom aligns other selected points to key anchor's y (160). s.execute("object.align", &json!({"vertical": "bottom"})).unwrap(); assert_eq!(pts(&s, id), [(150.0, 160.0), (150.0, 160.0), (150.0, 160.0), (60.0, 120.0)], "the key anchor stays"); + let steps = super::history(&s); s.execute("object.align", &json!({"vertical": "top"})).unwrap(); assert_eq!(super::history(&s), steps, "nothing moved: no undo step"); - // `to: "selection"` aligns to the points' bounds instead. + + // `to: "selection"` aligns to the points' collective bounds instead. s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 3]], "mode": "add"})).unwrap(); s.execute("object.align", &json!({"horizontal": "left", "to": "selection"})).unwrap(); assert_eq!(pts(&s, id).iter().map(|p| p.0).collect::<Vec<_>>(), [60.0; 4]); } +#[test] +fn align_commands_across_paths_without_moving_key_anchor() { + let mut s = session(); + let a = path(&mut s, "M100 100 L200 100 L200 200 Z"); + let b = path(&mut s, "M300 300 L400 350 Z"); + // Select point (0, 1) on path a (at 200, 100) and point (0, 0) on path b (at 300, 300). + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + // Set point (0, 1) of a as the key anchor. + s.execute("select.key", &json!({"id": a.0, "anchor": [0, 1]})).unwrap(); + assert_eq!(key_anchor(&s), Some((a, (0, 1)))); + + // Align Horizontal Center: point (0, 0) of b moves to x=200, while point on a does not move! + s.execute("object.align", &json!({"horizontal": "center"})).unwrap(); + assert_eq!(pts(&s, a)[1], (200.0, 100.0), "key anchor on a does not move"); + assert_eq!(pts(&s, b)[0].0, 200.0, "survivor point on b aligned to key anchor x"); + assert_eq!(pts(&s, b)[1], (400.0, 350.0), "unselected point on b was not moved"); + + // Align Vertical Center / Middle: point (0, 0) of b moves to y=100. + s.execute("object.align", &json!({"vertical": "center"})).unwrap(); + assert_eq!(pts(&s, a)[1], (200.0, 100.0), "key anchor on a still did not move"); + assert_eq!(pts(&s, b)[0].1, 100.0, "survivor point on b aligned to key anchor y"); +} + +#[test] +fn single_step_undo_redo_for_key_anchor_alignment() { + let mut s = session(); + let a = path(&mut s, "M100 100 L200 150 Z"); + let b = path(&mut s, "M300 300 L400 350 Z"); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]], "mode": "set"})).unwrap(); + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + s.execute("select.key", &json!({"id": a.0, "anchor": [0, 0]})).unwrap(); + + let initial_a = pts(&s, a); + let initial_b = pts(&s, b); + + // Run align: + s.execute("object.align", &json!({"horizontal": "right"})).unwrap(); + assert_eq!(pts(&s, a)[0], (100.0, 100.0), "key anchor did not move"); + assert_eq!(pts(&s, b)[0].0, 100.0, "survivor moved to key anchor x"); + + // Undo reverts to initial in one step: + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(pts(&s, a), initial_a, "undo restored a"); + assert_eq!(pts(&s, b), initial_b, "undo restored b"); + + // Redo re-aligns in one step: + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(pts(&s, a)[0], (100.0, 100.0)); + assert_eq!(pts(&s, b)[0].0, 100.0); +} + #[test] fn distribute_with_a_spacing_places_the_points_from_the_key_anchor() { let mut s = session(); let id = path(&mut s, "M10 10 L20 50 L100 30 L60 90"); - s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); - s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 2]], "mode": "toggle"})).unwrap(); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap(); + s.execute("select.key", &json!({"id": id.0, "anchor": [0, 2]})).unwrap(); s.execute("object.distributeSpacing", &json!({"axis": "horizontal", "spacing": 20})).unwrap(); assert_eq!(pts(&s, id), [(60.0, 10.0), (80.0, 50.0), (100.0, 30.0), (60.0, 90.0)], "20 apart, outward from the key anchor"); s.execute("object.distribute", &json!({"vertical": "center", "spacing": 5})).unwrap(); @@ -100,6 +193,7 @@ fn the_key_anchor_goes_when_it_can_no_longer_be_one() { let b = path(&mut s, "M300 300 L400 300"); s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]], "mode": "set"})).unwrap(); s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "add"})).unwrap(); + s.execute("select.key", &json!({"id": b.0, "anchor": [0, 1]})).unwrap(); assert_eq!(key_anchor(&s), Some((b, (0, 1))), "a point of another path"); assert!(s.doc().unwrap().selection.has_key()); let r = s.execute("select.key", &json!({})).unwrap(); @@ -114,6 +208,7 @@ fn the_key_anchor_goes_when_it_can_no_longer_be_one() { let c = path(&mut s, "M500 500 L600 500"); s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "add"})).unwrap(); + s.execute("select.key", &json!({"id": a.0, "anchor": [0, 1]})).unwrap(); assert_eq!(key_anchor(&s), Some((a, (0, 1))), "beside a path selected whole"); s.execute("select.key", &json!({"id": c.0})).unwrap(); let sel = &s.doc().unwrap().selection; @@ -154,6 +249,7 @@ fn a_rejected_select_key_keeps_the_key_anchor() { let a = path(&mut s, "M100 40 L200 60 L150 160 Z"); s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 9]], "mode": "set"})).unwrap(); s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "add"})).unwrap(); + s.execute("select.key", &json!({"id": a.0, "anchor": [0, 1]})).unwrap(); assert_eq!(key_anchor(&s), Some((a, (0, 1)))); // [0, 9] is in the selection but not on the path. let err = s.execute("select.key", &json!({"id": a.0, "anchor": [0, 9]})).expect_err("a point the path does not have").to_string(); 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<u8> { 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<u8> { 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<u8>) { 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<u8> { 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 57bb9e278e..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<u8> { 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<u8> { 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)); @@ -2117,6 +2268,35 @@ fn confined_clipboard_svg_refuses_a_linked_image_file_outside_the_read_roots() { assert!(svg.contains(&format!("xlink:href=\"{photo}\"")), "{svg}"); } +/// `clipboard.flavours` and the session's flavors leave out the SVG, and its markup as text, that +/// `clipboard.exportSvg` withholds from a confined caller; the PNG is still listed. The SVG is listed +/// while its image's pixels are held, and for a caller with no read roots. +#[test] +fn confined_clipboard_flavours_leave_out_a_withheld_svg() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("clip-flavours-away"); + let home = Folder::new("clip-flavours-home"); + let photo = away.file("photo.png"); + write(&photo, &png(60, 30, RED)); + let mut s = session(); + let a = place(&mut s, &photo); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + let (text, svg, png) = ("text/plain", "image/svg+xml", "image/png"); + let listed = |s: &mut Session| confine(roots.as_ref(), || s.execute("clipboard.flavours", &json!({}))).unwrap()["flavours"].clone(); + assert_eq!(listed(&mut s), json!([text, svg, png])); + + without_pixels(&mut s, a); + s.execute("edit.copy", &json!({})).unwrap(); + assert_eq!(listed(&mut s), json!([png])); + let made = confine(roots.as_ref(), || s.clipboard_flavours()); + assert!(made.iter().all(|f| f.mime != svg && f.mime != text), "{:?}", made.iter().map(|f| f.mime).collect::<Vec<_>>()); + assert_eq!(confine(roots.as_ref(), || s.clipboard_flavour_types()), [png]); + assert_eq!(s.execute("clipboard.flavours", &json!({})).unwrap()["flavours"], json!([text, svg, png])); +} + /// A confined caller's SVG with Preserve Editing Capabilities is refused while the stored brush /// library holds an entry that does not read as a brush, or is not a list: the native document /// carries it as it is, and its links cannot be checked. Without Preserve Editing the SVG is written. @@ -2138,3 +2318,199 @@ fn confined_preserve_editing_svg_refuses_a_brush_library_entry_it_cannot_read() confine(roots.as_ref(), || s.execute("document.serialize", &json!({"format": "svg"}))).unwrap(); } } + +/// A confined caller's SVG and SVGZ with Preserve Editing Capabilities carry a native document +/// without the Export for Screens folder when it is outside the read roots, with the other export +/// settings and the art; the open document keeps the folder. A folder inside the roots, and any +/// folder without roots, stays in the attachment. +#[test] +fn confined_preserve_editing_svg_leaves_out_an_export_folder_outside_the_read_roots() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("svg-export-folder-away"); + let home = Folder::new("svg-export-folder-home"); + let outside = away.0.to_string_lossy().into_owned(); + let inside = home.file("screens"); + let mut s = session(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + let rect: vectorcraft_doc::NodeId = serde_json::from_value(r["id"].clone()).unwrap(); + let set_folder = |s: &mut Session, folder: &str| { + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + doc.export_settings = serde_json::from_value(json!({"folder": folder, "prefix": "web-"})).unwrap(); + }; + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + // The native document an SVG's text carries. + let attached = |text: &str| { + let data = vectorcraft_svg::editing_data(text).expect("editing data"); + vectorcraft_format::load(&vectorcraft_format::base64_decode(&data).unwrap()).unwrap() + }; + let check = |d: &Document, folder: Option<&str>, what: &str| { + assert_eq!(d.export_settings.get("folder").and_then(Value::as_str), folder, "{what}"); + assert_eq!(d.export_settings.get("prefix").and_then(Value::as_str), Some("web-"), "{what}"); + assert!(d.node(rect).is_some(), "{what}: no art"); + }; + // Every way an SVG is asked for with Preserve Editing, its text and its native document. + let every = |s: &mut Session, confined: bool, folder: Option<&str>| { + let run = |s: &mut Session, cmd: &str, p: Value| { + let r = if confined { confine(roots.as_ref(), || s.execute(cmd, &p)) } else { s.execute(cmd, &p) }; + r.unwrap() + }; + for format in ["svg", "svgz"] { + let r = run(s, "document.serialize", json!({"format": format, "preserveEditing": true})); + check(&attached(&svg_text(&r)), folder, &format!("{format} serialize")); + let r = run(s, "document.serialize", json!({"format": format, "svg": {"preserveEditing": true}})); + check(&attached(&svg_text(&r)), folder, &format!("{format} options object")); + let path = home.file(&format!("export.{format}")); + run(s, "document.export", json!({"format": format, "path": path, "preserveEditing": true})); + let bytes = std::fs::read(&path).unwrap(); + check(&attached(&vectorcraft_svg::text_of(&bytes).unwrap()), folder, &format!("{format} export")); + } + }; + set_folder(&mut s, &outside); + every(&mut s, true, None); + assert_eq!(s.doc().unwrap().doc.export_settings.get("folder").and_then(Value::as_str), Some(outside.as_str())); + every(&mut s, false, Some(&outside)); + // Without Preserve Editing the SVG carries no native document. + let r = confine(roots.as_ref(), || s.execute("document.serialize", &json!({"format": "svg"}))).unwrap(); + assert!(vectorcraft_svg::editing_data(&svg_text(&r)).is_none(), "{r}"); + set_folder(&mut s, &inside); + every(&mut s, true, Some(&inside)); +} + +/// A confined caller's SVG of a placed document whose art links an image: the file draws that art +/// and names the image's file, so a file outside the read roots refuses it and one inside them is +/// written. Any output that names no file is written. +#[test] +fn confined_svg_output_checks_the_images_of_placed_documents() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("svg-placed-away"); + let home = Folder::new("svg-placed-home"); + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + for (photo, outside) in [(away.file("photo.png"), true), (home.file("photo.png"), false)] { + write(&photo, &png(60, 30, RED)); + let src = home.file("src.vectorcraft"); + let mut inner = session(); + place(&mut inner, &photo); + save(&mut inner, &src); + let mut s = session(); + place(&mut s, &src); + let link = json!({"format": "svg", "images": "link"}); + assert!(svg_text(&s.execute("document.serialize", &link).unwrap()).contains(&photo), "the file names the placed art's image"); + for format in ["svg", "svgz"] { + for images in ["link", "embed"] { + let p = json!({"format": format, "images": images}); + // Embed writes the pixels the placed file holds. + let names = svg_text(&s.execute("document.serialize", &p).unwrap()).contains(&photo); + assert_eq!(names, images == "link", "{p}"); + match confine(roots.as_ref(), || s.execute("document.serialize", &p)) { + Ok(r) => assert!(!outside || !svg_text(&r).contains(&photo), "{p}: {}", svg_text(&r)), + Err(e) => { + assert!(outside && names, "{p}: {e}"); + assert!(e.to_string().contains("a linked image file is outside the read roots"), "{p}: {e}"); + } + } + } + } + if outside { + let e = confine(roots.as_ref(), || s.execute("document.serialize", &link)).unwrap_err().to_string(); + assert!(e.contains("a linked image file is outside the read roots") && !e.contains("photo.png"), "{e}"); + } + } +} + +/// A confined caller's SVG of a symbol holding a visible rectangle and a hidden linked image outside +/// the read roots: the file leaves the hidden image out of the symbol and is written, unless hidden +/// layers are kept, which writes the image and refuses the file. +#[test] +fn confined_svg_output_leaves_hidden_symbol_art_unchecked() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("svg-symbol-hidden-away"); + let home = Folder::new("svg-symbol-hidden-home"); + let photo = away.file("photo.png"); + write(&photo, &png(60, 30, RED)); + let mut s = session(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap()["id"].clone(); + let a = place(&mut s, &photo); + s.execute("object.hide", &json!({"ids": [a.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [r, a.0]})).unwrap(); + s.execute("symbol.new", &json!({"name": "Mixed"})).unwrap(); + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + for format in ["svg", "svgz"] { + let p = json!({"format": format, "images": "link"}); + assert!(!svg_text(&s.execute("document.serialize", &p).unwrap()).contains(&photo), "{p}"); + let text = svg_text(&confine(roots.as_ref(), || s.execute("document.serialize", &p)).unwrap()); + assert!(!text.contains(&photo), "{p}: {text}"); + let kept = json!({"format": format, "images": "link", "hiddenLayers": true}); + assert!(svg_text(&s.execute("document.serialize", &kept).unwrap()).contains(&photo), "{kept}"); + let e = confine(roots.as_ref(), || s.execute("document.serialize", &kept)).unwrap_err().to_string(); + assert!(e.contains("a linked image file is outside the read roots"), "{kept}: {e}"); + } +} + +/// A confined caller's SVG Tiny 1.2 of an object whose opacity mask is a linked image outside the +/// read roots: the Tiny file leaves the mask out and is written; SVG 1.1 writes the mask and is +/// refused. +#[test] +fn confined_svg_tiny_output_leaves_opacity_mask_images_unchecked() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("svg-tiny-mask-away"); + let home = Folder::new("svg-tiny-mask-home"); + let photo = away.file("photo.png"); + write(&photo, &png(60, 30, RED)); + let mut s = session(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap()["id"].clone(); + let a = place(&mut s, &photo); + s.execute("select.set", &json!({"ids": [r, a.0]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + for format in ["svg", "svgz"] { + let tiny = json!({"format": format, "images": "link", "profile": "tiny12"}); + assert!(!svg_text(&s.execute("document.serialize", &tiny).unwrap()).contains(&photo), "{tiny}"); + let text = svg_text(&confine(roots.as_ref(), || s.execute("document.serialize", &tiny)).unwrap()); + assert!(!text.contains(&photo), "{tiny}: {text}"); + let full = json!({"format": format, "images": "link"}); + assert!(svg_text(&s.execute("document.serialize", &full).unwrap()).contains(&photo), "{full}"); + let e = confine(roots.as_ref(), || s.execute("document.serialize", &full)).unwrap_err().to_string(); + assert!(e.contains("a linked image file is outside the read roots"), "{full}: {e}"); + } +} + +/// A confined caller's SVG of a linked image outside the read roots, without pixels in the +/// document, under Radial Blur: the file and the clipboard draw the rendered image in its place, +/// name no file, and are written. +#[test] +fn confined_svg_output_checks_the_images_drawn_for_pixel_effects() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("svg-flat-away"); + let home = Folder::new("svg-flat-home"); + let photo = away.file("photo.png"); + write(&photo, &png(60, 30, RED)); + let mut s = session(); + let a = place(&mut s, &photo); + s.execute("effect.apply", &json!({"effect": "blur.radial", "ids": [a.0], "params": {"amount": 30, "quality": "draft"}})).unwrap(); + without_pixels(&mut s, a); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + let clip = + |s: &mut Session| confine(roots.as_ref(), || s.execute("clipboard.exportSvg", &json!({}))).unwrap()["svg"].as_str().unwrap().to_string(); + assert!(!clip(&mut s).contains(&photo)); + assert!(confine(roots.as_ref(), || s.clipboard_svg()).is_some_and(|svg| !svg.contains(&photo))); + for format in ["svg", "svgz"] { + for images in ["link", "embed"] { + let p = json!({"format": format, "images": images}); + let text = svg_text(&confine(roots.as_ref(), || s.execute("document.serialize", &p)).unwrap()); + assert!(!text.contains(&photo), "{p}: {text}"); + } + } + // Without the effect, the image names its file. + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("effect.remove", &json!({"index": 0})).unwrap(); + assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects.is_empty()); + let e = confine(roots.as_ref(), || s.execute("document.serialize", &json!({"format": "svg"}))).unwrap_err().to_string(); + assert!(e.contains("a linked image file is outside the read roots"), "{e}"); +} 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/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 1db3ffa34e..fb836e9099 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -1588,6 +1588,235 @@ fn crop_image_to_a_rect_between_pixels_keeps_the_rect() { assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}"); } +/// Crop Image's `ppi` resamples the cut pixels to that resolution; the image keeps the box's size. +#[test] +fn crop_image_resamples_the_cut_to_the_resolution_asked_for() { + let (mut s, img, px) = busy_image_at_two_points_a_pixel(); + // The image is 36 ppi (2 pt a pixel); 18 ppi halves the cut's 30 × 20 pixels. + let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 18})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (15, 10), "{r}"); + let b = bounds(&s, img); + assert!(close(b.x0, 20.0) && close(b.y0, 10.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}"); + let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") }; + let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8(); + let cut = image::imageops::crop_imm(&px, 10, 5, 30, 20).to_image(); + // Resampled in 16 bits a channel: within a level of the 8-bit resampling. + let want = image::imageops::resize(&cut, 15, 10, image::imageops::FilterType::Lanczos3); + assert_eq!(out.dimensions(), want.dimensions()); + assert!(out.as_raw().iter().zip(want.as_raw()).all(|(a, b)| a.abs_diff(*b) <= 1)); +} + +/// Resampling weights colors by their alpha: the color hidden in fully transparent pixels does not +/// tint the partly transparent edge of what is opaque. +#[test] +fn crop_image_resampling_keeps_hidden_colors_out_of_the_edges() { + // Opaque white on the left half, fully transparent red on the right. + let px = image::RgbaImage::from_fn(40, 20, |x, _| if x < 20 { image::Rgba([255, 255, 255, 255]) } else { image::Rgba([255, 0, 0, 0]) }); + let mut png = Vec::new(); + px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "edge.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + let img = selected(&s)[0]; + s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap(); + // 36 ppi to 15 ppi over pixels 5 to 35 across: the edge pixels mix white and clear. + s.execute("object.cropImage", &json!({"rect": [10, 0, 60, 40], "ppi": 15})).unwrap(); + let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") }; + let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8(); + assert!(out.pixels().any(|p| p[3] > 0 && p[3] < 255), "the edge is partly transparent"); + for p in out.pixels().filter(|p| p[3] > 0) { + assert!(p[1] >= 250 && p[2] >= 250, "white, not tinted red: {p:?}"); + } +} + +/// Resampling keeps the color of pixels that are nearly transparent: a uniform color at the lowest +/// alpha comes out as that color, not black. +#[test] +fn crop_image_resampling_keeps_the_color_of_nearly_transparent_pixels() { + let px = image::RgbaImage::from_pixel(100, 80, image::Rgba([100, 50, 25, 1])); + let mut png = Vec::new(); + px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "faint.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + let img = selected(&s)[0]; + s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap(); + s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 18})).unwrap(); + let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") }; + let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8(); + for p in out.pixels() { + let near = |a: u8, b: u8| a.abs_diff(b) <= 1; + assert!(p[3] == 1 && near(p[0], 100) && near(p[1], 50) && near(p[2], 25), "{p:?}"); + } +} + +/// A box between pixels drawn at a resolution asked for holds what is inside the box only, at its +/// place: the edge of the image's content lands where it was in the box. +#[test] +fn crop_image_between_pixels_keeps_the_content_at_its_place() { + // White pixels 0 to 49 across, black from 50: at 2 pt a pixel, the edge is at x = 100 pt. + let px = image::RgbaImage::from_fn(100, 80, |x, _| if x < 50 { image::Rgba([255, 255, 255, 255]) } else { image::Rgba([0, 0, 0, 255]) }); + let mut png = Vec::new(); + px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "edge.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + let img = selected(&s)[0]; + s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap(); + // 101 × 31 pt from (21, 11), off the pixel grid, at 35 ppi: 49 × 15 px. The edge is 79 pt into + // the 101 pt box, so each row holds 49 × 79 / 101 pixels' worth of white. + let r = s.execute("object.cropImage", &json!({"rect": [21, 11, 101, 31], "ppi": 35})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (49, 15), "{r}"); + let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") }; + let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8(); + let white: f64 = out.pixels().map(|p| f64::from(p[1]) / 255.0).sum::<f64>() / f64::from(out.height()); + let want = 49.0 * 79.0 / 101.0; + assert!((white - want).abs() < 0.1, "{white} pixels of white a row, want {want}"); + let b = bounds(&s, img); + assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 101.0) && close(b.height(), 31.0), "{b:?}"); +} + +/// A box between pixels is drawn at the resolution asked for, and lands on the box. +#[test] +fn crop_image_between_pixels_draws_at_the_resolution_asked_for() { + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + let r = s.execute("object.cropImage", &json!({"rect": [21, 11, 60, 40], "ppi": 18})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (15, 10), "{r}"); + let b = bounds(&s, img); + assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}"); + // 100 × 30 pt at 20 ppi is 27.8 × 8.3 px: the 28 × 8 px drawn are fitted to the box. + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + let r = s.execute("object.cropImage", &json!({"rect": [21, 11, 100, 30], "ppi": 20})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (28, 8), "{r}"); + let b = bounds(&s, img); + assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 100.0) && close(b.height(), 30.0), "{b:?}"); +} + +/// A box over the whole image with a new resolution resamples it; with the image's own there is +/// nothing to do. +#[test] +fn crop_image_over_the_whole_image_only_resamples_it() { + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + let before = undo_len(&s); + let r = s.execute("object.cropImage", &json!({"rect": [0, 0, 200, 160], "ppi": 36})); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "nothing to crop"), "{r:?}"); + assert_eq!(undo_len(&s), before); + let r = s.execute("object.cropImage", &json!({"rect": [0, 0, 200, 160], "ppi": 9})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (25, 20), "{r}"); + assert_eq!(undo_len(&s), before + 1, "one undo step"); + let b = bounds(&s, img); + assert!(close(b.x0, 0.0) && close(b.y0, 0.0) && close(b.width(), 200.0) && close(b.height(), 160.0), "{b:?}"); +} + +/// An image scaled more down than across is resampled on both sides at the resolution of its denser +/// side, so its pixels come out square. +#[test] +fn crop_image_resamples_pixels_that_are_not_square() { + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + // 2 pt a pixel across (36 ppi) and 1 pt a pixel down (72 ppi), 200 × 80 pt. + s.execute("object.scale", &json!({"sx": 100, "sy": 50, "origin": [0, 0]})).unwrap(); + let r = s.execute("object.cropImage", &json!({"rect": [0, 0, 200, 80], "ppi": 72})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (200, 80), "{r}"); + let b = bounds(&s, img); + assert!(close(b.x0, 0.0) && close(b.y0, 0.0) && close(b.width(), 200.0) && close(b.height(), 80.0), "{b:?}"); +} + +/// Crop Image refuses a resolution that isn't a positive number, one above the image's own, and one +/// with trim; the image stays as it was. +#[test] +fn crop_image_refuses_a_resolution_it_cannot_give() { + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + let before = (undo_len(&s), node(&s, img)); + let refused = |s: &mut Session, p: Value, want: &str| { + let r = s.execute("object.cropImage", &p); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == want), "{p}: {r:?}"); + }; + for v in [json!(0), json!(-72), json!("high"), json!(true)] { + refused(&mut s, json!({"rect": [20, 10, 60, 40], "ppi": v}), &format!("ppi must be a positive number, not {v}")); + } + for v in [0.5, 1e-310, 2401.0] { + refused(&mut s, json!({"rect": [20, 10, 60, 40], "ppi": v}), "ppi must be between 1 and 2400"); + } + refused(&mut s, json!({"rect": [20, 10, 60, 40], "ppi": 72}), "ppi can't be more than 36 for this image"); + refused(&mut s, json!({"trim": true, "ppi": 18}), "trim keeps the image's pixels as they are: leave out ppi"); + assert_eq!((undo_len(&s), node(&s, img)), before); + // A null ppi keeps the image's own, as a missing one does. + let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": null})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (30, 20), "{r}"); +} + +/// A turned image keeps its own resolution as the limit (not the density across its bounding box), +/// and its drawn cut is resampled to the box's size at the resolution asked for. +#[test] +fn crop_image_of_a_turned_image_resamples_its_drawing() { + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + let b = bounds(&s, img); + let r = s.execute("object.cropImage", &json!({"rect": [b.x0 + 40.0, b.y0 + 40.0, 72, 36], "ppi": 37})); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "ppi can't be more than 36 for this image"), "{r:?}"); + let r = s.execute("object.cropImage", &json!({"rect": [b.x0 + 40.0, b.y0 + 40.0, 72, 36], "ppi": 18})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (18, 9), "{r}"); + let c = bounds(&s, img); + assert!(close(c.x0, b.x0 + 40.0) && close(c.y0, b.y0 + 40.0) && close(c.width(), 72.0) && close(c.height(), 36.0), "{c:?}"); +} + +/// A turned image cropped at its own resolution, asked for, gets that resolution, not the lower +/// density of the box around it. +#[test] +fn crop_image_of_a_turned_image_at_its_own_resolution_keeps_it() { + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + s.execute("object.rotate", &json!({"angle": 45})).unwrap(); + let b = bounds(&s, img); + let r = s.execute("object.cropImage", &json!({"rect": [b.x0 + 40.0, b.y0 + 40.0, 72, 36], "ppi": 36})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (36, 18), "{r}"); + // Over the whole box around it, its own resolution draws it square to the page. + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + s.execute("object.rotate", &json!({"angle": 45})).unwrap(); + let b = bounds(&s, img); + let r = s.execute("object.cropImage", &json!({"rect": [b.x0, b.y0, b.width(), b.height()], "ppi": 36})).unwrap(); + assert_eq!(r["width"].as_u64().unwrap(), (b.width() / 2.0).round() as u64, "{r}"); + let r = s.execute("object.cropImage", &json!({"rect": [b.x0, b.y0, b.width(), b.height()]})); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "nothing to crop"), "{r:?}"); +} + +/// A linked image can be cropped to up to 300 ppi, even above its own; the crop embeds it. +#[test] +fn crop_image_takes_a_linked_image_up_to_300_ppi() { + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + s.edit("Link", |d, _| { + let NodeKind::Image(im) = &mut d.node_mut(img).unwrap().kind else { panic!("not an image") }; + im.link = Some(vectorcraft_doc::LinkInfo::new("art.png")); + Ok(()) + }) + .unwrap(); + let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 301})); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "ppi can't be more than 300 for this image"), "{r:?}"); + // 72 ppi: a pixel a point. + let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 72})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (60, 40), "{r}"); + let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") }; + assert!(im.link.is_none()); +} + +/// `tool.setOption` refuses a Crop Image resolution, reference point or link it can't use, and +/// changes nothing. +#[test] +fn crop_image_tool_options_refuse_values_they_cannot_use() { + let (mut s, _, _) = busy_image_at_two_points_a_pixel(); + s.select_tool("cropImage", ViewInfo::default()).unwrap(); + s.set_tool_option_cmd(&json!({"values": {"ppi": 18, "reference": 0, "linked": true}})).unwrap(); + // 72 ppi is above the selected 36 ppi image's own. + for (key, value) in + [("ppi", json!("high")), ("ppi", json!(-1)), ("ppi", json!(0.5)), ("ppi", json!(72)), ("reference", json!(9)), ("linked", json!(1))] + { + assert!(s.set_tool_option_cmd(&json!({"key": key, "value": value})).is_err(), "{key}: {value}"); + } + let o = s.tool_options(); + assert_eq!((o["ppi"].clone(), o["reference"].clone(), o["linked"].clone()), (json!(18.0), json!(0), json!(true)), "{o}"); + s.set_tool_option_cmd(&json!({"key": "ppi", "value": null})).unwrap(); + assert!(s.tool_options().get("ppi").is_none()); +} + /// Crop Image refuses a `rect` that is not an array, such as text, and the image stays as it was; a /// null `rect` crops to the artboard as a missing one does. #[test] @@ -5331,6 +5560,22 @@ fn crop_image_trim_checks_the_rgba_size_before_decoding() { assert!(within.contains("the image's pixels can't be read"), "{within}"); } +#[test] +fn crop_image_resampling_is_held_to_the_raster_allowance() { + use crate::cmd::menucmds::check_resample_size; + let max = crate::cmd::fileio::MAX_RASTER_ALLOC; + // 40 bytes a pixel resampled to the same size (12 + 16 + 12). + let side = ((max / 40) as f64).sqrt() as u32; + assert!(check_resample_size(side, side, side, side).is_ok()); + let e = check_resample_size(side + 1, side + 1, side + 1, side + 1).unwrap_err().to_string(); + assert!(e.contains(&format!("an image of {0} × {0} pixels is too large to resample", side + 1)), "{e}"); + // A large source counts even when the result is small. + let wide = ((max / 12) as f64).sqrt() as u32 + 1; + assert!(check_resample_size(wide, wide, 1, 1).is_err()); + assert!(check_resample_size(u32::MAX, u32::MAX, u32::MAX, u32::MAX).is_err()); + assert!(check_resample_size(100, 100, 50, 50).is_ok()); +} + #[test] fn crop_image_trim_leaves_a_cmyk_image_alone() { // CMYK images keep their ink amounts and have no alpha: nothing to cut, and not an error. 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/objexpand.rs b/crates/engine/src/tests/objexpand.rs index 494c070a66..05da523ced 100644 --- a/crates/engine/src/tests/objexpand.rs +++ b/crates/engine/src/tests/objexpand.rs @@ -278,6 +278,59 @@ fn each_copys_shadow_expands_as_the_canvas_draws_it() { assert_eq!(diff, 0, "{diff} pixels differ"); } +/// Each copy of a fill's own Transform effect, and each copy of its object's Transform effect, +/// draws the fill's drop shadow under itself, scaled with it, and Expand Appearance keeps those +/// shadows: the copy (10..50 across, 90..130 down) has its own shadow 40 pt to its right. +#[test] +fn each_copys_fill_shadow_expands_as_the_canvas_draws_it() { + let shadow = json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"}); + let copies = json!({"scaleH": 200, "scaleV": 200, "moveV": 80, "copies": 1}); + for own in [true, false] { + let mut s = session(); + run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 20, "height": 20})); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "paint.setStroke", json!({"none": true})); + run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": shadow, "item": 0})); + let item = if own { json!(0) } else { json!(null) }; + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": copies, "item": item})); + let before = render(&s); + assert_eq!(before.pixel(80, 110), [0, 255, 0, 255], "own {own}: the copy's shadow"); + run(&mut s, "effect.expandAppearance", json!({})); + let after = render(&s); + let diff = differing(&before, &after, 64); + assert_eq!(diff, 0, "own {own}: {diff} pixels differ"); + } +} + +/// Each copy of type's Transform effect draws the drop shadow listed before the effect under +/// itself, scaled with it, and Expand Appearance keeps those shadows: the type's copy, scaled 200 % +/// and moved 80 pt down, has its shadow 40 pt to the right of its letters rather than the type's +/// own 20 pt. +#[test] +fn each_copys_shadow_on_type_expands_as_the_canvas_draws_it() { + let mut s = session(); + let t = run(&mut s, "text.create", json!({"x": 20, "y": 60, "text": "I", "size": 40}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids": [t]})); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + let shadow = json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"}); + run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": shadow})); + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"scaleH": 200, "scaleV": 200, "moveV": 80, "copies": 1}})); + let before = render(&s); + if !(0..100u32).any(|y| (0..200u32).any(|x| before.pixel(x, y) == [255, 0, 0, 255])) { + eprintln!("skipped: built without a font that draws the type"); + return; + } + // The rightmost red pixel of the copy, below the type, and 38 pt right of it the copy's shadow. + let red = + (100..200u32).flat_map(|y| (0..200u32).map(move |x| (x, y))).filter(|&(x, y)| before.pixel(x, y) == [255, 0, 0, 255]).max_by_key(|p| p.0); + let (x, y) = red.expect("the copy"); + assert_eq!(before.pixel(x + 38, y), [0, 255, 0, 255], "the copy's shadow, 40 pt to the right of ({x}, {y})"); + run(&mut s, "effect.expandAppearance", json!({})); + let after = render(&s); + let diff = differing(&before, &after, 64); + assert_eq!(diff, 0, "{diff} pixels differ"); +} + /// A group's Transform effect runs after its member's own Offset Path in Expand Appearance as on /// the canvas: the 100 pt square offset to 120 pt and scaled by half expands 60 pt wide. #[test] @@ -717,6 +770,29 @@ fn type_reports_a_gradient_when_any_glyph_expands() { assert_eq!(gradients_and_type(&s), (1, 0), "the large glyph keeps its gradient"); } +/// Type scaled unevenly outlines its characters' stroke as a filled path, so a gradient on that +/// stroke becomes a gradient fill: the query reports it, and Expand turns it into art. +#[test] +fn type_reports_a_stroke_gradient_its_uneven_scale_turns_into_a_fill() { + let mut s = session(); + let t = run(&mut s, "text.create", json!({"x": 50, "y": 100, "text": "Hi", "size": 48}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids": [t]})); + run( + &mut s, + "paint.setStroke", + json!({"gradient": {"kind": "linear", "spread": "repeat", "repeats": 100, "start": [50, 100], "end": [70, 100], + "stops": [{"offset": 0, "color": "#ffff00"}, {"offset": 1, "color": "#004080"}]}}), + ); + run(&mut s, "stroke.set", json!({"weight": 4})); + let info = run(&mut s, "object.expand.info", json!({})); + assert_eq!(info["gradient"], json!(false), "a live stroke's gradient is not a fill"); + run(&mut s, "object.scale", json!({"ids": [t], "sx": 300, "sy": 100})); + let info = run(&mut s, "object.expand.info", json!({})); + assert_eq!((info["gradient"].clone(), info["fill"].clone()), (json!(true), json!(true))); + run(&mut s, "object.expand", json!({})); + assert_eq!(gradients_and_type(&s), (0, 0), "the filled strokes' gradients became art"); +} + /// The same rule for type in the art of a symbol instance that Object expands. The symbol's art /// is the type scaled down (its "i" about 2.5 pt wide), so its glyphs need more runs than are /// written with 0.002 pt runs (over a 0.2 pt vector). diff --git a/crates/engine/src/tests/overprint.rs b/crates/engine/src/tests/overprint.rs index 15fbb721e2..3f18ddf644 100644 --- a/crates/engine/src/tests/overprint.rs +++ b/crates/engine/src/tests/overprint.rs @@ -276,3 +276,61 @@ fn overprint_black_covers_type_gradients_spots_and_groups() { s.execute("edit.colors.overprintBlack", &json!({"includeCmyBlacks": true, "includeSpotBlacks": true})).unwrap(); assert!(fill(&s, g) && fill(&s, spot)); } + +/// The plate `plate` of `doc`, drawn as Separations Preview draws one plate, as one gray value per +/// pixel (0 full ink, 255 none). +fn plate(doc: &Document, plate: &str) -> Vec<u8> { + let mut r = Renderer::new(); + r.threads = 0; + let seps = vectorcraft_render::proof::ProofSetup { separations: Some(vec![plate.into()]), ..Default::default() }; + let opts = RenderOptions { background: Some([255, 255, 255, 255]), proof: Some(seps), ..Default::default() }; + let image = r.render(doc, 100, 100, Affine::IDENTITY, &opts); + (0..100 * 100).map(|i| image.pixel(i % 100, i / 100)[0]).collect() +} + +/// 3D (Classic) with the shading color Black Overprint puts the shading on the black plate, shows +/// it as the cyan darkened, and writes it to PDF as overprinting fills. +#[test] +fn classic_3d_black_overprint_shades_on_the_black_plate() { + let doc = |params: Value| { + let mut s = session(); + rect(&mut s, [30.0, 30.0, 40.0, 40.0], cyan_ink(), None, 0.0); + s.execute("effect.apply", &json!({"effect": "threeD.classicExtrude", "item": null, "params": params})).unwrap(); + s + }; + let over = doc(json!({"surface": "diffuse", "depth": 20, "shadingColor": "blackOverprint"})); + let flat = doc(json!({"surface": "none", "depth": 20, "shadingColor": "blackOverprint"})); + let black = doc(json!({"surface": "diffuse", "depth": 20})); + let (over_doc, flat_doc) = (&over.doc().unwrap().doc, &flat.doc().unwrap().doc); + let inked = |p: &[u8]| p.iter().filter(|v| **v < 250).count(); + assert!(inked(&plate(over_doc, "Cyan")) > 1000, "the solid is drawn"); + assert!(inked(&plate(over_doc, "Black")) > 100, "the shading is on the black plate"); + assert_eq!(inked(&plate(flat_doc, "Black")), 0, "No Shading adds no black"); + // On screen a shaded face is the cyan darkened, not gray: the black multiplies the cyan. + let image = |d: &Document| { + let mut r = Renderer::new(); + r.threads = 0; + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + r.render(d, 100, 100, Affine::IDENTITY, &opts) + }; + let (shaded, unshaded) = (image(over_doc), image(flat_doc)); + let mut darker = 0; + for (x, y) in (0..100u32).flat_map(|y| (0..100u32).map(move |x| (x, y))) { + let (s, u) = (shaded.pixel(x, y), unshaded.pixel(x, y)); + // Inside the solid (no white mixed in at an antialiased edge) where the shading darkens it. + if u[0] < 30 && (s[1] as i32) + 20 < u[1] as i32 { + darker += 1; + assert!(s[2] as i32 > s[0] as i32 + 20, "a shaded face keeps its cyan at ({x}, {y}): {s:?}"); + } + } + assert!(darker > 100, "the faces turned from the light are darker"); + + let pdf_overprints = |s: &mut Session| { + let v = s.execute("document.exportPdf", &json!({"compression": {"compressText": false}, "preserveEditing": false})).unwrap(); + let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap(); + String::from_utf8_lossy(&bytes).matches("/OP true/op true/OPM 1").count() + }; + let (mut over, mut black) = (over, black); + assert!(pdf_overprints(&mut over) > 0, "the black is written overprinting"); + assert_eq!(pdf_overprints(&mut black), 0); +} diff --git a/crates/engine/src/tests/package.rs b/crates/engine/src/tests/package.rs index 952693d7c1..218434eb8a 100644 --- a/crates/engine/src/tests/package.rs +++ b/crates/engine/src/tests/package.rs @@ -351,6 +351,60 @@ fn a_confined_package_names_files_outside_the_read_root_by_name() { assert!(info.to_string().contains(&dir.file("art/red.png")), "the person's: {info}"); } +/// A confined request packages no document that links, or places a native document or a PDF with +/// Preserve Editing that links, a JavaScript file outside its read roots: the package is refused +/// before anything is written, with an error that names no file or folder. A JavaScript file inside +/// them is packaged, and so is one outside them when the person packages. +#[test] +fn a_confined_package_refuses_a_linked_javascript_file_outside_the_read_root() { + let away = Folder::new("package-script-away"); + let home = Folder::new("package-script-home"); + let script = away.file("menu.js"); + let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[&home.0]).unwrap().unwrap(); + let hidden = [away.0.to_string_lossy().into_owned(), home.0.to_string_lossy().into_owned(), "menu.js".to_string()]; + let refused = |s: &mut Session, p: Value| { + let e = crate::file_access::confine(Some(&roots), || s.execute("file.package", &p)).expect_err("refused"); + assert!(matches!(e, EngineError::BadParams { .. }), "{p}: {e:?}"); + let e = e.to_string(); + assert!(e.contains("a linked JavaScript file is outside the read roots"), "{p}: {e}"); + for h in &hidden { + assert!(!e.contains(h.as_str()), "{p} names {h}: {e}"); + } + }; + let mut part = session(); + run(&mut part, "shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30})); + run(&mut part, "svgInteractivity.addFile", json!({"file": script})); + std::fs::create_dir_all(home.0.join("art")).unwrap(); + let native = home.file("art/part.vectorcraft"); + save(&mut part, &native); + let r = run(&mut part, "document.serialize", json!({"format": "pdf"})); + let pdf = home.file("art/part.pdf"); + write(&pdf, &vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()); + let out = home.file("out"); + refused(&mut part, json!({"folder": out})); + refused(&mut part, json!({})); + for placed in [&native, &pdf] { + let mut s = session(); + let r = run(&mut s, "file.place", json!({"path": placed, "link": true})); + assert_eq!(r["linked"], true, "{r}"); + save(&mut s, &home.file("poster.vectorcraft")); + refused(&mut s, json!({"folder": out})); + refused(&mut s, json!({})); + assert!(!std::path::Path::new(&out).exists(), "{placed}"); + // The person's package copies it. + assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "{placed}"); + } + // A JavaScript file inside the read roots. + run(&mut part, "svgInteractivity.removeFile", json!({"file": script})); + run(&mut part, "svgInteractivity.addFile", json!({"file": home.file("menu.js")})); + save(&mut part, &native); + let mut s = session(); + run(&mut s, "file.place", json!({"path": native, "link": true})); + save(&mut s, &home.file("poster.vectorcraft")); + let r = crate::file_access::confine(Some(&roots), || s.execute("file.package", &json!({"folder": out}))).unwrap(); + assert_eq!(r["links"], 1, "{r}"); +} + /// A missing link stored as a path relative to the document names a file inside a confined /// request's read root: the package report and Document Info give its stored path. #[test] diff --git a/crates/engine/src/tests/paintproxy.rs b/crates/engine/src/tests/paintproxy.rs index b270826e7a..e10f2df6d8 100644 --- a/crates/engine/src/tests/paintproxy.rs +++ b/crates/engine/src/tests/paintproxy.rs @@ -706,3 +706,16 @@ fn a_marker_designs_art_in_a_series_keeps_its_paint() { s.execute("addon.color.fillToStroke", &json!({"ids": [series.id.0]})).unwrap(); assert_eq!(design_strokes(&s), before, "the design's art keeps its paint"); } + +/// Invert given a member of a compound path inverts the compound path's fill, which the member stands for. +#[test] +fn invert_of_a_compound_member_inverts_the_compound_path() { + let mut s = session(); + let (a, b) = (rect(&mut s), rect(&mut s)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let comp = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [comp.0], "color": "#ff0000"})).unwrap(); + let member = node(&s, comp).children().into_iter().flatten().next().unwrap().id; + s.execute("paint.invert", &json!({"ids": [member.0]})).unwrap(); + assert_eq!(node(&s, comp).appearance.fill_paint().color().unwrap().to_hex(), "#00ffff"); +} 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<u8> { 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/persp_text.rs b/crates/engine/src/tests/persp_text.rs index b5dc5e7a53..443913a635 100644 --- a/crates/engine/src/tests/persp_text.rs +++ b/crates/engine/src/tests/persp_text.rs @@ -399,6 +399,22 @@ fn click_to_size_dialogs_draw_on_the_active_plane_in_plane_units() { assert!(crate::perspective_click(&s, "shape.rectangle", &json!({}), at).is_none()); } +/// The Ellipse dialog's anchor count reaches the ellipse drawn on the active plane. +#[test] +fn an_ellipse_of_six_anchors_made_by_a_click_draws_on_the_active_plane() { + let (mut s, _) = persp_session(); + s.execute("perspective.grid.show", &json!({"visible": true})).unwrap(); + s.execute("perspective.plane.set", &json!({"plane": "right"})).unwrap(); + let at = Point::new(470.0, 300.0); + let p = json!({"x": at.x, "y": at.y, "width": 50, "height": 30, "anchors": 6}); + let (cmd, p) = crate::perspective_click(&s, "shape.ellipse", &p, at).unwrap(); + let n = undo_len(&s); + let id = NodeId(s.execute(&cmd, &p).unwrap()["id"].as_u64().unwrap()); + assert_eq!(undo_len(&s), n + 1); + assert_eq!(attached(&s, id).map(|a| a.0), Some(Plane::Right)); + assert_eq!(node(&s, id).path_data().unwrap().anchor_count(), 6); +} + #[test] fn the_canvas_draws_type_in_perspective_foreshortened() { let (mut s, rect) = persp_session(); diff --git a/crates/engine/src/tests/pixelalign.rs b/crates/engine/src/tests/pixelalign.rs index 06057d1fc0..00b4cce694 100644 --- a/crates/engine/src/tests/pixelalign.rs +++ b/crates/engine/src/tests/pixelalign.rs @@ -1158,3 +1158,384 @@ fn not_aligned_to_pixel_grid_takes_a_compound_path_by_its_own_property() { assert!(!aligned(&s, off)); assert_eq!(not_aligned(&mut s, &[compound]), vec![other]); } + +/// The anchors of the paths in the art of symbol instance `inst`, where its transform places them. +fn placed_points(s: &Session, inst: u64) -> Vec<(f64, f64)> { + let d = &s.doc().unwrap().doc; + let NodeKind::SymbolInstance { symbol, xf } = &d.node(NodeId(inst)).unwrap().kind else { panic!("{inst} is not a symbol instance") }; + let art = &d.symbols.iter().find(|x| &x.name == symbol).unwrap().art; + let mut out = vec![]; + art.walk(&mut |n| { + if let Some(p) = n.path_data() { + out.extend(p.anchors().map(|(_, _, a)| { + let q = *xf * a.p; + (q.x, q.y) + })); + } + }); + out +} + +/// The transform of symbol instance `inst`. +fn instance_xf(s: &Session, inst: u64) -> vectorcraft_geom::Affine { + match &s.doc().unwrap().doc.node(NodeId(inst)).unwrap().kind { + NodeKind::SymbolInstance { xf, .. } => *xf, + _ => panic!("{inst} is not a symbol instance"), + } +} + +/// Symbol Options › Align to Pixel Grid on a new symbol: the instance that replaces the selection +/// draws its art's edges on whole points, and goes back to them after a move by a fraction of a +/// point; a symbol made without it keeps the art where it was drawn. +#[test] +fn a_pixel_aligned_symbol_keeps_its_instance_on_whole_points() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let r = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap(); + assert_eq!(r["alignToPixelGrid"], true); + let inst = r["id"].as_u64().unwrap(); + let pts = placed_points(&s, inst); + assert_eq!(pts.len(), 4); + assert!(whole(&pts), "{pts:?}"); + s.execute("object.move", &json!({"dx": 0.3, "dy": 0.45})).unwrap(); + let pts = placed_points(&s, inst); + assert!(whole(&pts), "{pts:?}"); + let list = s.execute("symbol.list", &json!({})).unwrap(); + assert_eq!(list["symbols"][0]["alignToPixelGrid"], true); + + path(&mut s, "M100.3 20.6 L140.7 20.6 L140.7 30.3 L100.3 30.3 Z", 2.0); + let plain = s.execute("symbol.new", &json!({"name": "Plain"})).unwrap(); + assert_eq!(plain["alignToPixelGrid"], false); + let pts = placed_points(&s, plain["id"].as_u64().unwrap()); + assert!(!whole(&pts), "{pts:?}"); +} + +/// A centered stroke of odd weight puts the art's edges on half points, so the stroke's own edges +/// fall on the grid. +#[test] +fn a_pixel_aligned_symbol_with_an_odd_stroke_goes_to_half_points() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 1.0); + let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap(); + let pts = placed_points(&s, inst); + assert!(halves(&pts), "{pts:?}"); +} + +/// Turning it on in Symbol Options snaps the instances placed at actual size and leaves a scaled +/// one where it is; instances placed later land on whole points; asking again for the value the +/// symbol has adds no undo step; a duplicate and a rename keep it, a delete clears it, and a value +/// that is not true or false is refused. +#[test] +fn symbol_options_align_to_pixel_grid_snaps_instances_at_actual_size() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let a = s.execute("symbol.new", &json!({"name": "Px"})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("symbol.place", &json!({"name": "Px", "x": 100.3, "y": 200.7})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [b]})).unwrap(); + s.execute("object.scale", &json!({"sx": 150, "sy": 150})).unwrap(); + let scaled = instance_xf(&s, b); + assert!(!whole(&placed_points(&s, a))); + + let r = s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap(); + assert_eq!(r["alignToPixelGrid"], true); + let pts = placed_points(&s, a); + assert!(whole(&pts), "{pts:?}"); + assert_eq!(instance_xf(&s, b), scaled); + let c = s.execute("symbol.place", &json!({"name": "Px", "x": 50.3, "y": 60.6})).unwrap()["id"].as_u64().unwrap(); + let pts = placed_points(&s, c); + assert!(whole(&pts), "{pts:?}"); + + let steps = undo_len(&s); + s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap(); + assert_eq!(undo_len(&s), steps); + + assert_eq!(s.execute("symbol.duplicate", &json!({"name": "Px"})).unwrap()["name"], "Px copy"); + assert!(s.doc().unwrap().doc.symbol_pixel_aligned("Px copy")); + s.execute("symbol.options", &json!({"name": "Px", "newName": "Grid"})).unwrap(); + assert!(s.doc().unwrap().doc.symbol_pixel_aligned("Grid")); + assert!(!s.doc().unwrap().doc.symbol_pixel_aligned("Px")); + s.execute("symbol.delete", &json!({"names": ["Grid", "Px copy"]})).unwrap(); + assert!(s.doc().unwrap().doc.unknown.get(vectorcraft_doc::SYMBOL_PIXEL_ALIGNED).is_none()); + + path(&mut s, "M10 10 L20 10 L20 20 L10 20 Z", 1.0); + assert!(s.execute("symbol.new", &json!({"alignToPixelGrid": "yes"})).is_err()); + assert!(s.execute("symbol.new", &json!({"alignToPixelGrid": null})).is_err()); + s.execute("symbol.new", &json!({"name": "Q"})).unwrap(); + assert!(s.execute("symbol.options", &json!({"name": "Q", "alignToPixelGrid": 1})).is_err()); + assert!(s.execute("symbol.options", &json!({"name": "Q", "alignToPixelGrid": null})).is_err()); +} + +/// An instance reflected across one axis goes back to whole points after a move; one turned a half +/// turn counts as rotated and moves by exactly the amount asked. +#[test] +fn a_reflected_instance_snaps_and_a_half_turned_one_does_not() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap(); + s.execute("object.move", &json!({"dx": 0.3, "dy": 0.45})).unwrap(); + let [.., e, f] = instance_xf(&s, inst).as_coeffs(); + assert!(whole(&[(e, f)]), "{e} {f}"); + s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap(); + s.execute("object.rotate", &json!({"angle": 180})).unwrap(); + let [.., e0, f0] = instance_xf(&s, inst).as_coeffs(); + s.execute("object.move", &json!({"dx": 0.3, "dy": 0.45})).unwrap(); + let [.., e1, f1] = instance_xf(&s, inst).as_coeffs(); + assert!((e1 - e0 - 0.3).abs() < 1e-9 && (f1 - f0 - 0.45).abs() < 1e-9, "{e0} {f0} -> {e1} {f1}"); +} + +/// An instance of a pixel-aligned symbol attached to a path goes back to whole points each time the +/// path places it. +#[test] +fn an_instance_on_a_path_stays_on_whole_points() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap(); + let spine = s.execute("path.create", &json!({"d": "M 0.3 100.4 L 300.3 100.4"})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.objectsOnPath.attach", &json!({"path": spine, "ids": [inst]})).unwrap(); + let pts = placed_points(&s, inst); + assert!(whole(&pts), "attached: {pts:?}"); + let anchors = json!([{"x": 0.6, "y": 120.7}, {"x": 300.6, "y": 120.7}]); + s.execute("path.setAnchors", &json!({"id": spine, "subpaths": [{"anchors": anchors, "closed": false}]})).unwrap(); + let pts = placed_points(&s, inst); + assert!(whole(&pts), "path edited: {pts:?}"); +} + +/// A path in the art of an opacity mask in a pixel-aligned symbol's art snaps with the rest of +/// the art. +#[test] +fn mask_art_in_a_pixel_aligned_symbol_snaps() { + let mut s = new_doc(); + let r = path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let m = path(&mut s, "M12.3 22.6 L30.7 22.6 L30.7 28.3 L12.3 28.3 Z", 2.0); + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let art = d.remove(NodeId(m)).unwrap(); + d.node_mut(NodeId(r)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true))); + } + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let xf = instance_xf(&s, inst); + let art = &d.symbols.iter().find(|x| x.name == "Px").unwrap().art; + let mut pts = vec![]; + art.walk(&mut |n| { + if let Some(mask) = n.extras().mask.as_ref() { + mask.art.walk(&mut |c| { + if let Some(p) = c.path_data() { + pts.extend(p.anchors().map(|(_, _, a)| { + let q = xf * a.p; + (q.x, q.y) + })); + } + }); + } + }); + assert_eq!(pts.len(), 4); + assert!(whole(&pts), "{pts:?}"); +} + +/// A path in the art of an unlinked opacity mask in a pixel-aligned symbol's art snaps as the mask +/// is drawn at the symbol's natural size. +#[test] +fn unlinked_mask_art_in_a_pixel_aligned_symbol_snaps_at_natural_size() { + let mut s = new_doc(); + let r = path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let m = path(&mut s, "M12.3 22.6 L30.7 22.6 L30.7 28.3 L12.3 28.3 Z", 2.0); + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let art = d.remove(NodeId(m)).unwrap(); + d.node_mut(NodeId(r)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), false))); + } + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + let inst = s.execute("symbol.new", &json!({"name": "Px"})).unwrap()["id"].as_u64().unwrap(); + assert_ne!(s.doc().unwrap().doc.symbol_natural_xf("Px"), vectorcraft_geom::Affine::IDENTITY); + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let sym = d.symbols.iter_mut().find(|x| x.name == "Px").unwrap(); + std::sync::Arc::make_mut(&mut sym.art).extras_mut().mask.as_mut().unwrap().linked = false; + } + s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap(); + let d = &s.doc().unwrap().doc; + let xf = instance_xf(&s, inst); + let art = &d.symbols.iter().find(|x| x.name == "Px").unwrap().art; + let mut pts = vec![]; + art.walk(&mut |n| { + if let Some(mask) = n.extras().mask.as_ref() { + mask.art.walk(&mut |c| { + if let Some(p) = c.path_data() { + pts.extend(p.anchors().map(|(_, _, a)| { + let q = xf * a.p; + (q.x, q.y) + })); + } + }); + } + }); + assert_eq!(pts.len(), 4); + assert!(whole(&pts), "{pts:?}"); +} + +/// A path in the art of an opacity mask on a path of a compound path in a pixel-aligned symbol's +/// art snaps with the rest of the art. +#[test] +fn mask_art_on_a_compound_paths_path_in_a_pixel_aligned_symbol_snaps() { + let mut s = new_doc(); + let a = path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let b = path(&mut s, "M50.3 20.6 L60.7 20.6 L60.7 30.3 L50.3 30.3 Z", 2.0); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + let m = path(&mut s, "M12.3 22.6 L30.7 22.6 L30.7 28.3 L12.3 28.3 Z", 2.0); + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let art = d.remove(NodeId(m)).unwrap(); + let first = d.node(NodeId(c)).unwrap().children().unwrap()[0].id; + d.node_mut(first).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true))); + } + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let xf = instance_xf(&s, inst); + let art = &d.symbols.iter().find(|x| x.name == "Px").unwrap().art; + let mut pts = vec![]; + art.walk(&mut |n| { + if let Some(mask) = n.extras().mask.as_ref() { + mask.art.walk(&mut |c| { + if let Some(p) = c.path_data() { + pts.extend(p.anchors().map(|(_, _, a)| { + let q = xf * a.p; + (q.x, q.y) + })); + } + }); + } + }); + assert_eq!(pts.len(), 4); + assert!(whole(&pts), "{pts:?}"); +} + +/// An instance in the art of an object's opacity mask goes to whole points when its symbol is made +/// pixel-aligned. +#[test] +fn an_instance_in_an_opacity_mask_snaps_with_its_symbol() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + s.execute("symbol.new", &json!({"name": "Px"})).unwrap(); + let b = s.execute("symbol.place", &json!({"name": "Px", "x": 100.3, "y": 200.7})).unwrap()["id"].as_u64().unwrap(); + let r = path(&mut s, "M80 180 L160 180 L160 240 L80 240 Z", 1.0); + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let inst = d.remove(NodeId(b)).unwrap(); + d.node_mut(NodeId(r)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*inst).clone(), true))); + } + s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap(); + let d = &s.doc().unwrap().doc; + let mask = d.node(NodeId(r)).unwrap().extras().mask.clone().unwrap(); + let NodeKind::SymbolInstance { xf, .. } = &mask.art.kind else { panic!("the mask art is not the instance") }; + let [.., e, f] = xf.as_coeffs(); + assert!(whole(&[(e, f)]), "{e} {f}"); +} + +/// An instance snapped to whole points takes the art of its linked opacity mask along by the same +/// amount, as a move does; the art of an unlinked mask stays where it is. +#[test] +fn an_instance_snapped_to_the_grid_moves_its_linked_mask() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + s.execute("symbol.new", &json!({"name": "Px"})).unwrap(); + let place = |s: &mut Session, x: f64, linked: bool| { + let inst = s.execute("symbol.place", &json!({"name": "Px", "x": x, "y": 200.7})).unwrap()["id"].as_u64().unwrap(); + let m = path(s, "M80.25 180.5 L160.25 180.5 L160.25 240.5 L80.25 240.5 Z", 1.0); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let art = d.remove(NodeId(m)).unwrap(); + let mask = vectorcraft_doc::OpacityMask { linked, ..vectorcraft_doc::OpacityMask::new((*art).clone(), true) }; + d.node_mut(NodeId(inst)).unwrap().extras_mut().mask = Some(Box::new(mask)); + inst + }; + let (linked, unlinked) = (place(&mut s, 100.3, true), place(&mut s, 300.3, false)); + let mask_points = |s: &Session, inst: u64| { + let d = &s.doc().unwrap().doc; + let mask = d.node(NodeId(inst)).unwrap().extras().mask.clone().unwrap(); + mask.art.path_data().unwrap().anchors().map(|(_, _, a)| (a.p.x, a.p.y)).collect::<Vec<_>>() + }; + let (xf_before, mask_before, unlinked_before) = (instance_xf(&s, linked), mask_points(&s, linked), mask_points(&s, unlinked)); + s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap(); + let [.., e0, f0] = xf_before.as_coeffs(); + let [.., e, f] = instance_xf(&s, linked).as_coeffs(); + assert!(whole(&[(e, f)]) && (e, f) != (e0, f0), "{e} {f}"); + let moved: Vec<_> = mask_before.iter().map(|(x, y)| (x + e - e0, y + f - f0)).collect(); + let after = mask_points(&s, linked); + assert!(moved.iter().zip(&after).all(|(a, b)| close(*a, *b)), "{after:?} != {moved:?}"); + assert!(whole(&placed_points(&s, unlinked))); + assert_eq!(mask_points(&s, unlinked), unlinked_before); +} + +/// While a pixel-aligned symbol is edited, the art written back from the editing layer is stored +/// on the pixel grid, so its instances stay on it. +#[test] +fn art_edited_in_symbol_editing_mode_stays_on_the_pixel_grid() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap(); + s.execute("symbol.edit", &json!({"ids": [inst]})).unwrap(); + let st = s.doc().unwrap(); + let layer = st.doc.symbol_edit.as_ref().unwrap().layer; + let part = st.doc.node(layer).unwrap().children().unwrap()[0].id.0; + s.execute("select.set", &json!({"ids": [part]})).unwrap(); + s.execute("object.move", &json!({"dx": 0.3, "dy": 0.45})).unwrap(); + assert!(s.doc().unwrap().doc.symbol_edit.is_some()); + let pts = placed_points(&s, inst); + assert!(whole(&pts), "{pts:?}"); + // The editing layer shows the art as it is stored. + let shown = points(&s, part); + assert!(whole(&shown), "{shown:?}"); + s.execute("symbol.exitEditing", &json!({})).unwrap(); + let pts = placed_points(&s, inst); + assert!(whole(&pts), "{pts:?}"); +} + +/// Turning it on while the symbol is open in symbol editing mode shows its art on the pixel grid +/// on the editing layer at once, and its instance stays on it after editing ends. +#[test] +fn turning_it_on_in_symbol_editing_mode_snaps_the_editing_layer() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let inst = s.execute("symbol.new", &json!({"name": "Px"})).unwrap()["id"].as_u64().unwrap(); + s.execute("symbol.edit", &json!({"ids": [inst]})).unwrap(); + let st = s.doc().unwrap(); + let layer = st.doc.symbol_edit.as_ref().unwrap().layer; + let part = st.doc.node(layer).unwrap().children().unwrap()[0].id.0; + let before = points(&s, part); + s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap(); + let d = &s.doc().unwrap().doc; + let xf = d.symbol_edit.as_ref().unwrap().xf; + let art = &d.symbols.iter().find(|x| x.name == "Px").unwrap().art; + let stored: Vec<_> = art.path_data().unwrap().anchors().map(|(_, _, a)| xf * a.p).map(|p| (p.x, p.y)).collect(); + let shown = points(&s, part); + assert!(shown.iter().zip(&stored).all(|(a, b)| close(*a, *b)) && shown != before, "{shown:?} != {stored:?}"); + s.execute("symbol.exitEditing", &json!({})).unwrap(); + let pts = placed_points(&s, inst); + assert!(whole(&pts), "{pts:?}"); +} + +/// An instance of a pixel-aligned symbol on the editing layer of another symbol is part of that +/// symbol's art, so turning it on leaves the instance and the other symbol's art where they are. +#[test] +fn an_instance_on_another_symbols_editing_layer_is_left_as_it_is() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let a = s.execute("symbol.new", &json!({"name": "Px"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + let b = s.execute("symbol.new", &json!({"name": "Outer"})).unwrap()["id"].as_u64().unwrap(); + s.execute("symbol.edit", &json!({"ids": [b]})).unwrap(); + let st = s.doc().unwrap(); + let layer = st.doc.symbol_edit.as_ref().unwrap().layer; + let inner = st.doc.node(layer).unwrap().children().unwrap()[0].id.0; + let outer_art = st.doc.symbols.iter().find(|x| x.name == "Outer").unwrap().art.clone(); + let shown = instance_xf(&s, inner); + assert!(!whole(&placed_points(&s, inner))); + s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap(); + assert_eq!(instance_xf(&s, inner), shown); + let d = &s.doc().unwrap().doc; + assert!(std::sync::Arc::ptr_eq(&d.symbols.iter().find(|x| x.name == "Outer").unwrap().art, &outer_art)); +} diff --git a/crates/engine/src/tests/place.rs b/crates/engine/src/tests/place.rs index 8dbe06f349..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<f64>) -> Vec<u8> { 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<u8> { +fn noise(w: u32, h: u32, format: craft_image_codecs::Format) -> Vec<u8> { 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<u8> { /// 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()); @@ -1101,6 +1252,35 @@ fn the_place_queue_skips_an_image_whose_pixels_cant_be_read() { assert_eq!(b.place_queue_read(read).unwrap(), r); } +/// An encrypted PDF stays in the place cursor's queue, read with the session or apart from it, at +/// a letter page's size with `needsPassword`, so that a click in the app can ask for its password; +/// headless, a click on it places nothing. +#[test] +fn the_place_queue_keeps_an_encrypted_pdf() { + use vectorcraft_testkit::pdf::{PdfPage, pdf}; + let locked = pdf(&[PdfPage::new(100.0, 50.0, "0 g 0 0 10 10 re f")], Some("pw")); + let p = json!({"files": [file("locked.pdf", &locked), file("a.png", &png(40, 20, [9, 9, 9, 255], None))], "thumbnail": 8}); + let (mut a, mut b) = (session(), session()); + let r = a.execute("file.place.queue", &p).unwrap(); + assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}"); + assert_eq!(r["files"][0], json!({"name": "locked.pdf", "format": "pdf", "width": 612.0, "height": 792.0, "needsPassword": true})); + assert!(r["files"][1].get("needsPassword").is_none()); + let read = b.prepare_place_queue(&p).unwrap().read().unwrap(); + assert_eq!(b.place_queue_read(read).unwrap(), r); + let view = ViewInfo::default(); + assert_eq!(a.tool_options()["name"], "locked.pdf"); + let _ = a.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0), view); + let _ = a.pointer(&PointerEvent::new(PointerKind::Up, 10.0, 10.0), view); + assert_eq!((top_children(&a).len(), a.doc().unwrap().history.undo.len()), (0, 0), "nothing placed without the password"); + // An encrypted PDF with a bad option is refused for the option, not kept. + let e = a.execute("file.place.queue", &json!({"files": [file("locked.pdf", &locked)], "page": 0})).unwrap_err().to_string(); + assert!(e.contains("page must be a whole number from 1"), "{e}"); + // A PDF that can't be read for another reason is still skipped. + let broken = file("broken.pdf", b"%PDF-1.7\nnot a PDF body\n"); + let r = a.execute("file.place.queue", &json!({"files": [broken, file("b.png", &png(4, 4, [0; 4], None))]})).unwrap(); + assert_eq!((&r["count"], &r["skipped"][0]["name"]), (&json!(1), &json!("broken.pdf")), "{r}"); +} + /// The place queue's thumbnail of an image is drawn from the pixels its check decoded, so each /// image is decoded once. #[test] @@ -1108,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<u8> { 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 390248f2a9..4bb0bdf3fe 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -359,6 +359,35 @@ fn an_empty_row_adds_no_swatch_and_no_group_color() { assert_eq!(hexes, ["#ff0000", "#0000ff"]); } +/// An empty row with `added` (a color the Add Color tool added) recolors nothing, and without +/// `groupColors` gives a rewritten group its new color after the colors of the rows with current +/// colors; randomize keeps the flag, and an `added` that is not true or false is refused. +#[test] +fn an_added_empty_row_gives_the_group_its_color_after_the_others() { + let mut s = session(); + let red = rect(&mut s, json!("#ff0000")); + let blue = rect(&mut s, json!("#0000ff")); + run(&mut s, "swatch.newGroup", json!({"name": "Pair", "colors": ["#ff0000", "#0000ff"]})); + select_all(&mut s); + let map = json!([ + {"from": [], "to": "rgb 0 255 0", "added": true}, + {"from": [], "to": "rgb 9 9 9"}, + {"from": ["rgb 255 0 0"], "to": "rgb 255 0 0"}, + {"from": ["rgb 0 0 255"], "to": "rgb 0 0 255"}, + ]); + let shuffled = run(&mut s, "recolor.randomize", json!({"map": map, "seed": 1})); + assert_eq!(shuffled["map"][0]["added"], json!(true), "{shuffled}"); + assert_eq!(shuffled["map"][1].get("added"), None, "{shuffled}"); + run(&mut s, "recolor.apply", json!({"map": map, "group": "Pair"})); + let d = &s.doc().unwrap().doc; + let g = d.swatch_groups.iter().find(|g| g.name == "Pair").unwrap(); + let hexes: Vec<String> = g.swatches.iter().map(|w| w.paint.color().unwrap().to_hex()).collect(); + assert_eq!(hexes, ["#ff0000", "#0000ff", "#00ff00"]); + assert_eq!((fill(&s, red).to_hex(), fill(&s, blue).to_hex()), ("#ff0000".into(), "#0000ff".into()), "no art is recolored"); + let bad = json!([{"from": [], "to": "rgb 0 255 0", "added": "yes"}]); + assert!(s.execute("recolor.apply", &json!({"map": bad})).is_err()); +} + #[test] fn randomize_shuffles_new_colours_and_skips_excluded_rows() { let mut s = session(); @@ -380,6 +409,27 @@ fn randomize_shuffles_new_colours_and_skips_excluded_rows() { assert!((hue(&sb["map"][0]["to"]) - 0.0).abs() < 1.0 && (hue(&sb["map"][1]["to"]) - 120.0).abs() < 1.0, "hue kept"); } +/// A row with no current colors (New Row) keeps its new color through Randomize, and its color +/// goes to no row that holds current colors: the other rows shuffle their own colors only. +#[test] +fn randomize_leaves_an_empty_row_out() { + let mut s = session(); + let map = json!([ + {"from": [], "to": "rgb 0 255 0"}, + {"from": ["rgb 255 0 0"], "to": "rgb 255 0 0"}, + {"from": ["rgb 0 0 255"], "to": "rgb 0 0 255"}, + ]); + for seed in 0..16 { + let r = run(&mut s, "recolor.randomize", json!({"map": map, "seed": seed})); + assert_eq!(r["map"][0], map[0], "seed {seed}: the empty row keeps its color"); + let mut tos: Vec<String> = [1, 2].iter().map(|i| r["map"][*i]["to"].as_str().unwrap().to_string()).collect(); + tos.sort(); + assert_eq!(tos, ["rgb 0 0 255", "rgb 255 0 0"], "seed {seed}: a permutation of the filled rows' colors"); + } + let sb = run(&mut s, "recolor.randomize", json!({"map": map, "order": false, "saturationBrightness": true, "seed": 3})); + assert_eq!(sb["map"][0], map[0], "the empty row keeps its saturation and brightness"); +} + #[test] fn edit_group_rewrites_in_order_as_one_undo_step() { let mut s = session(); @@ -744,6 +794,65 @@ fn recolor_of_everything_counts_locked_art_that_only_loses_its_group_swatch_link assert_eq!(r["notChanged"], json!({"locked": 1, "hidden": 0}), "{r}"); } +#[test] +fn a_null_in_group_colors_removes_that_swatch_and_the_ones_after_it_keep_their_places() { + let mut s = session(); + run(&mut s, "swatch.newGroup", json!({"name": "Brand", "colors": ["#2878f0", "#ff0000", "#00ff00"]})); + let group = |s: &Session| -> Vec<(String, String)> { + let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Brand").unwrap().swatches.clone(); + g.iter().map(|w| (w.name.clone(), w.paint.color().unwrap().to_hex())).collect() + }; + let names: Vec<String> = group(&s).into_iter().map(|(n, _)| n).collect(); + for name in &names { + run(&mut s, "swatch.edit", json!({"name": name, "global": true})); + } + let red = rect(&mut s, json!("#000000")); + let green = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [red.0], "swatch": names[1]})); + run(&mut s, "paint.setFill", json!({"ids": [green.0], "swatch": names[2]})); + select_all(&mut s); + // The middle swatch goes; the last keeps its name and color, and a color added after them is new. + run(&mut s, "recolor.apply", json!({"map": [], "group": "Brand", "groupColors": ["#2878f0", null, "#00ff00", "#123456"]})); + let g = group(&s); + assert_eq!(g.len(), 3, "{g:?}"); + assert_eq!(g[..2], [(names[0].clone(), "#2878f0".into()), (names[2].clone(), "#00ff00".into())]); + assert_eq!(g[2].1, "#123456"); + let link = |s: &Session, id: NodeId| match s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint() { + vectorcraft_color::Paint::Solid { color, swatch, .. } => (color.to_hex(), swatch), + p => panic!("{p:?}"), + }; + assert_eq!(link(&s, red), ("#ff0000".into(), None), "art linked to the removed swatch keeps its color, unlinked"); + assert_eq!(link(&s, green), ("#00ff00".into(), Some(names[2].clone())), "art linked to a swatch that stays keeps its link"); +} + +/// A row whose new color was removed keeps its art's colors: art in it linked to another swatch of +/// the group, which the rewrite gives another color, loses the link instead of following it. +#[test] +fn art_of_a_row_without_a_new_color_keeps_its_color_when_its_swatch_takes_another() { + let mut s = session(); + run(&mut s, "swatch.newGroup", json!({"name": "Brand", "colors": ["#ff0000", "#0000ff", "#00ff00"]})); + let names: Vec<String> = + s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Brand").unwrap().swatches.iter().map(|w| w.name.clone()).collect(); + for name in &names { + run(&mut s, "swatch.edit", json!({"name": name, "global": true})); + } + let blue = rect(&mut s, json!("#000000")); + let green = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [blue.0], "swatch": names[1]})); + run(&mut s, "paint.setFill", json!({"ids": [green.0], "swatch": names[2]})); + select_all(&mut s); + // The rows are blue, red and green; the blue row's new color is removed, so the group's first + // swatch goes and its second takes the red row's new color. + let map = json!([{"from": ["#0000ff"], "to": null}, {"from": ["#ff0000"], "to": "#ff0000"}, {"from": ["#00ff00"], "to": "#00ff00"}]); + run(&mut s, "recolor.apply", json!({"map": map, "group": "Brand", "groupColors": [null, "#ff0000", "#00ff00"]})); + let link = |s: &Session, id: NodeId| match s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint() { + vectorcraft_color::Paint::Solid { color, swatch, .. } => (color.to_hex(), swatch), + p => panic!("{p:?}"), + }; + assert_eq!(link(&s, blue), ("#0000ff".into(), None), "the art keeps its color, unlinked"); + assert_eq!(link(&s, green), ("#00ff00".into(), Some(names[2].clone())), "art of another row keeps its link"); +} + #[test] fn recolor_of_everything_does_not_count_locked_art_whose_pattern_the_group_rewrite_recolors() { let mut s = session(); @@ -1141,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(); @@ -1266,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(); @@ -1321,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/script_dialogs.rs b/crates/engine/src/tests/script_dialogs.rs index f955a6fdb3..baa8989208 100644 --- a/crates/engine/src/tests/script_dialogs.rs +++ b/crates/engine/src/tests/script_dialogs.rs @@ -120,6 +120,18 @@ fn missing_or_mismatched_answer_rolls_back() { assert_eq!(s.script_report().unwrap()["dialogs"][0]["answer"], "missing"); } +/// The error about answers left over names their count with the matching noun. +#[test] +fn unused_answers_are_counted_in_the_singular_and_the_plural() { + let mut s = one_doc(); + let ok = json!({"kind": "alert", "value": "ok"}); + for (extra, says) in [(1, "`answers` has 1 answer the script did not use"), (2, "`answers` has 2 answers the script did not use")] { + let given = Value::Array(vec![ok.clone(); extra + 1]); + let e = headless(&mut s, "alert('x');", given).unwrap_err().to_string(); + assert!(e.contains(says), "{e}"); + } +} + #[test] fn invalid_answers_are_rejected_before_run() { let mut s = one_doc(); diff --git a/crates/engine/src/tests/select_effects.rs b/crates/engine/src/tests/select_effects.rs index d2160fba34..f52ad14481 100644 --- a/crates/engine/src/tests/select_effects.rs +++ b/crates/engine/src/tests/select_effects.rs @@ -1,6 +1,6 @@ //! Clicks, hovers and marquees with the selection tools leave out the area that raster effects //! (drop shadows, glows, blurs) paint beyond an object: there they reach the object under the -//! effect, or nothing. +//! effect, or nothing. Clicks and marquees take art where its geometry effects draw it. use serde_json::{Value, json}; use vectorcraft_doc::NodeId; @@ -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. @@ -391,3 +423,107 @@ fn group_selection_hover_over_a_drop_shadow_marks_nothing() { } assert_eq!(press(&mut s, "groupSelection", (110.0, 50.0), (110.0, 50.0), Mods::default()), [b]); } + +/// A rectangle that a Transform effect moves 100 pt to the right is selected by a click and by a +/// marquee where it is drawn, and not at its own place, which it no longer paints. The same holds +/// for a group whose own Transform effect moves it. +#[test] +fn a_click_and_a_marquee_select_art_where_its_transform_effect_draws_it() { + let mut s = session(); + let a = rect(&mut s, 20.0, 20.0, 40.0, 40.0, "#ff0000"); + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "ids": [a.0], "params": {"moveH": 100}, "item": null})); + assert_eq!(pixel(&s, 140, 40), [255, 0, 0, 255], "drawn where it moved"); + assert_eq!(pixel(&s, 40, 40), WHITE, "not drawn at its own place"); + run(&mut s, "select.none", json!({})); + assert!(click(&mut s, 40.0, 40.0).is_empty()); + assert_eq!(click(&mut s, 140.0, 40.0), [a]); + assert_eq!(press(&mut s, "selection", (110.0, 10.0), (130.0, 30.0), Mods::default()), [a], "a marquee across its drawn corner"); + run(&mut s, "select.none", json!({})); + assert!(press(&mut s, "selection", (10.0, 10.0), (30.0, 30.0), Mods::default()).is_empty(), "a marquee across its own corner"); + + let mut s = session(); + let b = rect(&mut s, 20.0, 120.0, 40.0, 40.0, "#0000ff"); + run(&mut s, "select.set", json!({"ids": [b.0]})); + let g = id_of(&run(&mut s, "object.group", json!({}))); + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "ids": [g.0], "params": {"moveH": 100}, "item": null})); + assert_eq!(pixel(&s, 140, 140), BLUE, "the group drawn where it moved"); + run(&mut s, "select.none", json!({})); + assert!(click(&mut s, 40.0, 140.0).is_empty()); + assert_eq!(click(&mut s, 140.0, 140.0), [g]); + assert_eq!(press(&mut s, "selection", (110.0, 110.0), (130.0, 130.0), Mods::default()), [g]); + run(&mut s, "select.none", json!({})); + assert!(press(&mut s, "selection", (10.0, 110.0), (30.0, 130.0), Mods::default()).is_empty()); +} + +/// A group's own fill paints its member's shape before the member's own Transform effect moves the +/// member: a click there selects the group, and a click on the moved member selects it too. A +/// Direct Selection marquee takes the group there and the member where it moved. +#[test] +fn a_click_selects_a_group_where_its_own_fill_paints_a_moved_member() { + let mut s = session(); + let b = rect(&mut s, 20.0, 120.0, 40.0, 40.0, "#0000ff"); + run(&mut s, "select.set", json!({"ids": [b.0]})); + let g = id_of(&run(&mut s, "object.group", json!({}))); + run(&mut s, "appearance.addFill", json!({})); + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "ids": [b.0], "params": {"moveH": 100}, "item": null})); + assert_eq!(pixel(&s, 40, 140), [255, 0, 0, 255], "the group's fill at the member's own place"); + assert_eq!(pixel(&s, 140, 140), BLUE, "the member where it moved"); + run(&mut s, "select.none", json!({})); + assert_eq!(click(&mut s, 40.0, 140.0), [g]); + run(&mut s, "select.none", json!({})); + assert_eq!(click(&mut s, 140.0, 140.0), [g]); + // A marquee across the edge of the group's fill takes the group, and one across the moved + // member's edge takes the member. + let doc = &s.doc().unwrap().doc; + assert_eq!(vectorcraft_doc::hit::marquee(doc, Rect::new(10.0, 130.0, 30.0, 150.0), None, true), [g]); + assert_eq!(vectorcraft_doc::hit::marquee(doc, Rect::new(110.0, 130.0, 130.0, 150.0), None, true), [b]); +} + +/// An inner group's own fill paints its member's shape before the member's own Transform effect +/// moves the member, and so does an outer group's own fill around it: a Direct Selection marquee +/// across the edge of those fills takes both groups, and one across the moved member takes it. +#[test] +fn a_marquee_takes_an_inner_groups_own_fill_inside_a_painted_group() { + let mut s = session(); + let b = rect(&mut s, 20.0, 120.0, 40.0, 40.0, "#0000ff"); + run(&mut s, "select.set", json!({"ids": [b.0]})); + let g = id_of(&run(&mut s, "object.group", json!({}))); + run(&mut s, "appearance.addFill", json!({})); + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "ids": [b.0], "params": {"moveV": -100}, "item": null})); + run(&mut s, "select.set", json!({"ids": [g.0]})); + let o = id_of(&run(&mut s, "object.group", json!({}))); + run(&mut s, "appearance.addFill", json!({})); + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); + run(&mut s, "paint.setFill", json!({"color": "#00ff00"})); + assert_eq!(pixel(&s, 40, 140), [0, 255, 0, 255], "the outer group's fill at the member's own place"); + assert_eq!(pixel(&s, 40, 40), BLUE, "the member where it moved"); + let doc = &s.doc().unwrap().doc; + assert_eq!(vectorcraft_doc::hit::marquee(doc, Rect::new(10.0, 130.0, 30.0, 150.0), None, true), [o, g]); + assert_eq!(vectorcraft_doc::hit::marquee(doc, Rect::new(10.0, 30.0, 30.0, 50.0), None, true), [b]); +} + +/// A group's own fill paints its member's shape before the member's own Transform effect moves +/// the member, and so does its layer's own fill around it: a Direct Selection marquee across the +/// edge of the group's fill takes the group, and one across the moved member takes it. +#[test] +fn a_marquee_takes_a_groups_own_fill_inside_a_painted_layer() { + let mut s = session(); + let b = rect(&mut s, 20.0, 120.0, 40.0, 40.0, "#0000ff"); + run(&mut s, "select.set", json!({"ids": [b.0]})); + let g = id_of(&run(&mut s, "object.group", json!({}))); + run(&mut s, "appearance.addFill", json!({})); + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "ids": [b.0], "params": {"moveV": -100}, "item": null})); + let l = s.doc().unwrap().doc.layers[0].id; + run(&mut s, "appearance.addFill", json!({"ids": [l.0]})); + assert!(!s.doc().unwrap().doc.layers[0].appearance.items.is_empty(), "the layer has a fill of its own"); + assert_eq!(pixel(&s, 40, 40), BLUE, "the member where it moved"); + let doc = &s.doc().unwrap().doc; + assert_eq!(vectorcraft_doc::hit::marquee(doc, Rect::new(10.0, 130.0, 30.0, 150.0), None, true), [g]); + assert_eq!(vectorcraft_doc::hit::marquee(doc, Rect::new(10.0, 30.0, 30.0, 50.0), None, true), [b]); +} diff --git a/crates/engine/src/tests/shapetools.rs b/crates/engine/src/tests/shapetools.rs index 3c7d34a4fe..572c637dd5 100644 --- a/crates/engine/src/tests/shapetools.rs +++ b/crates/engine/src/tests/shapetools.rs @@ -149,6 +149,72 @@ fn a_shape_tool_turns_the_shape_from_just_outside_a_corner() { assert_eq!(angle(&s, id), 0.0, "rounding does not turn it"); } +/// How many objects the first layer holds. +fn objects(s: &Session) -> usize { + s.doc().unwrap().doc.layers[0].children().map(|c| c.len()).unwrap_or_default() +} + +/// Feed the pointer events `(kind, x, y, backtick held)` to the active tool, with no modifier. +fn quote_gesture(s: &mut Session, events: &[(PointerKind, f64, f64, bool)]) { + for (k, x, y, held) in events { + s.pointer(&PointerEvent { backquote: *held, ..PointerEvent::new(*k, *x, *y) }, view()).unwrap(); + } +} + +/// A Rectangle tool drag from (50, 50) with Backtick held from (100, 100) to (140, 100), let go +/// before (160, 120), all moved by `o` along both axes: two copies, 70 × 50 and 90 × 50 pt, and +/// the 110 × 70 pt rectangle it ends with. With `release`, the drag is let go; without, it is +/// still in progress. +fn trail(s: &mut Session, o: f64, release: bool) { + use PointerKind::{Down, Drag, Up}; + quote_gesture( + s, + &[ + (Down, 50.0 + o, 50.0 + o, false), + (Drag, 100.0 + o, 100.0 + o, true), + (Drag, 120.0 + o, 100.0 + o, true), + (Drag, 140.0 + o, 100.0 + o, true), + ], + ); + quote_gesture(s, &[(Drag, 160.0 + o, 120.0 + o, false)]); + if release { + quote_gesture(s, &[(Up, 160.0 + o, 120.0 + o, false)]); + } +} + +/// The sizes of the first layer's objects, back to front. +fn sizes(s: &Session) -> Vec<(f64, f64)> { + let ids: Vec<NodeId> = s.doc().unwrap().doc.layers[0].children().map(|c| c.iter().map(|n| n.id).collect()).unwrap_or_default(); + ids.into_iter().map(|id| bounds(s, id)).map(|r| (r.width(), r.height())).collect() +} + +/// Backtick held while a rectangle is dragged out leaves copies of it along the drag: each its own +/// object, and the release keeps them with the last rectangle as one undo step, with Real-time +/// Drawing and Editing on or off. Escape takes the copies back with the shape being drawn. +#[test] +fn a_backtick_drag_leaves_copies_of_the_shape_as_one_undo_step() { + for real_time in [true, false] { + let mut s = new_doc(); + s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": real_time})).unwrap(); + s.select_tool("rectangle", view()).unwrap(); + let steps = undo_steps(&s); + trail(&mut s, 0.0, true); + assert_eq!(sizes(&s), vec![(70.0, 50.0), (90.0, 50.0), (110.0, 70.0)], "real time {real_time}"); + assert_eq!(undo_steps(&s), steps + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(objects(&s), 0, "Undo takes all three back"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(objects(&s), 3, "Redo puts all three back"); + // Escape takes back the copies and the shape being drawn, away from the selection. + let steps = undo_steps(&s); + trail(&mut s, 200.0, false); + s.tool_key(ToolKey::Escape, NONE, view()).unwrap(); + quote_gesture(&mut s, &[(PointerKind::Up, 360.0, 320.0, false)]); + assert_eq!(objects(&s), 3, "real time {real_time}: nothing new"); + assert_eq!(undo_steps(&s), steps, "no step"); + } +} + /// The Selection tool takes the centre point of an unfilled shape too: a drag there moves it /// instead of starting a marquee. #[test] diff --git a/crates/engine/src/tests/spelling.rs b/crates/engine/src/tests/spelling.rs index dd10df1597..107c8b0418 100644 --- a/crates/engine/src/tests/spelling.rs +++ b/crates/engine/src/tests/spelling.rs @@ -345,6 +345,134 @@ fn misspellings_of_one_object_are_what_the_check_lists() { assert_eq!(found.iter().map(|m| m.range.clone()).collect::<Vec<_>>(), [listed[0].clone(), listed[2].clone()]); } +/// The (id, start, word) of each word a check lists, and its `more`. +fn listed(s: &mut Session, p: Value) -> (Vec<(u64, u64, String)>, bool) { + let r = run(s, "text.spelling.check", p); + let words = r["words"] + .as_array() + .unwrap() + .iter() + .map(|w| (w["id"].as_u64().unwrap(), w["start"].as_u64().unwrap(), w["word"].as_str().unwrap().to_string())) + .collect(); + (words, r["more"].as_bool().unwrap()) +} + +/// A check cut short at `max` goes on with `from` at the end of the last word listed: the rest of +/// that type object first, then the objects after it, and nothing listed twice. +#[test] +fn a_check_goes_on_from_where_the_last_one_stopped() { + let mut s = session(); + let a = text(&mut s, 50.0, "qzxvw one wvxzq two\nthree qqzzx"); + let b = text(&mut s, 100.0, "zzqqx"); + let (first, more) = listed(&mut s, json!({"max": 2})); + assert_eq!((first.clone(), more), (vec![(a.0, 0, "qzxvw".into()), (a.0, 10, "wvxzq".into())], true)); + // From the end of the second word: the third, in the next paragraph of the same object, not + // the start of the next object. + let (rest, more) = listed(&mut s, json!({"from": {"id": a.0, "byte": 15}, "max": 2})); + assert_eq!((rest, more), (vec![(a.0, 26, "qqzzx".into()), (b.0, 0, "zzqqx".into())], false)); + // A byte inside a word starts from the next word. + let (rest, _) = listed(&mut s, json!({"from": {"id": a.0, "byte": 1}})); + assert_eq!(rest.first(), Some(&(a.0, 10, "wvxzq".to_string()))); + // `from` follows the ids given, groups' type included. + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + let g = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap(); + let (rest, more) = listed(&mut s, json!({"ids": [g], "from": {"id": a.0, "byte": 26}, "max": 1})); + assert_eq!((rest, more), (vec![(a.0, 26, "qqzzx".into())], true)); + let (rest, more) = listed(&mut s, json!({"ids": [g], "from": {"id": a.0, "byte": 31}, "max": 1})); + assert_eq!((rest, more), (vec![(b.0, 0, "zzqqx".into())], false)); + let bad = [ + json!({"from": {"id": a.0}}), + json!({"from": {"id": a.0, "byte": -1}}), + json!({"from": {"id": a.0, "byte": 1000}}), + json!({"from": {"id": a.0, "byte": 0, "x": 1}}), + json!({"from": a.0}), + json!({"ids": [b.0], "from": {"id": a.0, "byte": 0}}), + json!({"max": 0}), + json!({"max": 10_001}), + json!({"max": "2"}), + ]; + for p in bad { + assert!(s.execute("text.spelling.check", &p).is_err(), "{p} is refused"); + } +} + +/// One type object with one unknown word more than a check lists: going on from the last word +/// listed reaches the last one. +#[test] +fn a_check_past_the_limit_in_one_object_goes_on_to_its_last_word() { + use crate::cmd::spelling::MAX_WORDS; + let mut s = session(); + let t = text(&mut s, 50.0, &vec!["qzxvw"; MAX_WORDS + 1].join(" ")); + let r = run(&mut s, "text.spelling.check", json!({})); + let words = r["words"].as_array().unwrap(); + assert_eq!((words.len(), &r["more"]), (MAX_WORDS, &json!(true))); + let end = words.last().unwrap()["end"].as_u64().unwrap(); + let (rest, more) = listed(&mut s, json!({"from": {"id": t.0, "byte": end}})); + assert_eq!((rest, more), (vec![(t.0, end + 1, "qzxvw".into())], false)); +} + +/// The plain text of type object `id`. +fn plain(s: &Session, id: NodeId) -> String { + match &s.doc().unwrap().doc.node(id).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not type"), + } +} + +/// Change All's command replaces every word listed, in several objects, as one undo step, and +/// refuses a list with any word not in its object's text, changing nothing. +#[test] +fn change_all_replaces_every_word_listed_in_one_undo_step() { + let mut s = session(); + let a = text(&mut s, 50.0, "qzxvw one qzxvw\nqzxvw"); + let b = text(&mut s, 100.0, "é qzxvw"); + let depth = s.doc().unwrap().history.undo.len(); + let words = json!([{"id": a.0, "start": 16, "end": 21}, {"id": a.0, "start": 0, "end": 5}, {"id": b.0, "start": 3, "end": 8}, {"id": a.0, "start": 10, "end": 15}]); + let r = run(&mut s, "text.spelling.change", json!({"to": "fixed", "words": words})); + assert_eq!(r["changed"], 4); + assert_eq!((plain(&s, a), plain(&s, b)), ("fixed one fixed\nfixed".to_string(), "é fixed".to_string())); + assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1); + run(&mut s, "edit.undo", json!({})); + assert_eq!((plain(&s, a), plain(&s, b)), ("qzxvw one qzxvw\nqzxvw".to_string(), "é qzxvw".to_string())); + let bad = [ + json!({"to": "x", "words": [{"id": a.0, "start": 0, "end": 5}, {"id": a.0, "start": 3, "end": 8}]}), + json!({"to": "x", "words": [{"id": a.0, "start": 0, "end": 5}, {"id": a.0, "start": 20, "end": 99}]}), + json!({"to": "x", "words": [{"id": b.0, "start": 1, "end": 4}]}), + json!({"to": "x", "words": [{"id": a.0, "start": 5, "end": 5}]}), + json!({"to": "x", "words": [{"id": a.0, "start": 0, "end": 5, "x": 1}]}), + json!({"to": "x", "words": [{"id": a.0, "start": -1, "end": 5}]}), + json!({"to": "x", "words": [{"id": 999_999, "start": 0, "end": 5}]}), + json!({"to": "x", "words": {"id": a.0}}), + json!({"words": []}), + ]; + for p in bad { + assert!(s.execute("text.spelling.change", &p).is_err(), "{p} is refused"); + } + assert_eq!(plain(&s, a), "qzxvw one qzxvw\nqzxvw", "nothing changed by a refused list"); + assert_eq!(run(&mut s, "text.spelling.change", json!({"to": "x", "words": []}))["changed"], 0); +} + +/// A listed word that already reads as `to` is left alone: with no other word, no edit and no +/// undo step, so the redo history stays. +#[test] +fn change_all_skips_words_that_already_read_as_the_replacement() { + let mut s = session(); + let a = text(&mut s, 50.0, "fixed qzxvw"); + run(&mut s, "text.editRange", json!({"id": a.0, "start": 6, "end": 11, "insert": "other"})); + run(&mut s, "edit.undo", json!({})); + let (undo, redo) = { + let h = &s.doc().unwrap().history; + (h.undo.len(), h.redo.len()) + }; + let r = run(&mut s, "text.spelling.change", json!({"to": "fixed", "words": [{"id": a.0, "start": 0, "end": 5}]})); + assert_eq!(r["changed"], 0); + let h = &s.doc().unwrap().history; + assert_eq!((h.undo.len(), h.redo.len()), (undo, redo), "no undo step, and redo kept"); + let words = json!([{"id": a.0, "start": 0, "end": 5}, {"id": a.0, "start": 6, "end": 11}]); + assert_eq!(run(&mut s, "text.spelling.change", json!({"to": "fixed", "words": words}))["changed"], 1); + assert_eq!(plain(&s, a), "fixed fixed"); +} + /// Each change to the custom dictionary moves its generation on, whether it is saved or not, so /// what Auto Spell Check found before is checked again. #[test] diff --git a/crates/engine/src/tests/swatches.rs b/crates/engine/src/tests/swatches.rs index e59e9a90b1..2d29d98a23 100644 --- a/crates/engine/src/tests/swatches.rs +++ b/crates/engine/src/tests/swatches.rs @@ -262,8 +262,8 @@ fn document_color_mode_converts_effect_colors() { assert_eq!((object(&s), style(&s)), before); } -/// Document Color Mode converts the series paints and label styles a graph keeps, so a graph drawn -/// again after the switch paints its series and labels in the new mode. +/// Document Color Mode converts the series paints, label styles and line rows a graph keeps, so a +/// graph drawn again after the switch paints its series, labels and lines in the new mode. #[test] fn document_color_mode_converts_the_paints_a_graph_keeps() { let mut s = session(); @@ -284,22 +284,26 @@ fn document_color_mode_converts_the_paints_a_graph_keeps() { } // A fill row on the label, which the graph keeps with the label's rows. run(&mut s, "appearance.addFill", json!({"ids": [label.0]})); + // A stroke on an axis line, which the graph keeps for its axis lines and tick marks. + let line = part(&s, "Axes").children().unwrap().iter().find(|c| matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. })).unwrap().id; + run(&mut s, "paint.setStroke", json!({"color": "#ff0000", "ids": [line.0]})); let kept = |s: &Session| -> Vec<Color> { let g = doc(s).node(id).unwrap().extras().graph.as_deref().unwrap().clone(); let rows = [&g.label_styles.values_rows, &g.label_styles.categories_rows, &g.label_styles.legend_rows]; let rows: Vec<Color> = rows.into_iter().flatten().filter_map(|r| r.paint.fill.as_ref()?.color()).collect(); + let lines = g.label_styles.axis_rows.iter().filter_map(|r| r.paint.stroke.as_ref()?.color()); let labels = [g.label_styles.values, g.label_styles.categories, g.label_styles.legend]; let labels = labels.into_iter().flatten().map(|st| st.fill.color().unwrap()); - g.series_paints.iter().filter_map(|p| p.fill.as_ref()?.color()).chain(labels).chain(rows).collect() + g.series_paints.iter().filter_map(|p| p.fill.as_ref()?.color()).chain(labels).chain(rows).chain(lines).collect() }; let before = kept(&s); - assert_eq!(before, [Color::rgb(1.0, 0.0, 0.0); 3]); + assert_eq!(before, [Color::rgb(1.0, 0.0, 0.0); 4]); let undo = s.doc().unwrap().history.undo.len(); run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"})); let cmyk = first_fill(doc(&s).node(red).unwrap()); assert!(matches!(cmyk, Color::Cmyk { .. }), "{cmyk:?}"); - assert_eq!(kept(&s), [cmyk; 3]); + assert_eq!(kept(&s), [cmyk; 4]); assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); // Drawn again from new data, the series keeps the converted color. run(&mut s, "graph.setData", json!({"id": id.0, "rows": [[2, 3], [4, 5]]})); 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/tangent_line.rs b/crates/engine/src/tests/tangent_line.rs new file mode 100644 index 0000000000..78511d766b --- /dev/null +++ b/crates/engine/src/tests/tangent_line.rs @@ -0,0 +1,40 @@ +//! Snap to Tangent with the Line Segment tool: a line dragged from one circle to another lands on +//! their common tangent, drawn by `shape.line` as one undo step. + +use serde_json::json; +use vectorcraft_doc::NodeKind; +use vectorcraft_geom::{Point, Vec2}; +use vectorcraft_tools::{PointerEvent, PointerKind}; + +use crate::*; + +use PointerKind::{Down, Drag, Up}; + +#[test] +fn a_line_segment_drag_draws_the_common_tangent_as_one_undo_step() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 500, "height": 500})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 60, "y": 210, "width": 80, "height": 80})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 240, "y": 190, "width": 120, "height": 120})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let count = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + assert_eq!(count(&s), 2); + // Circles about (100, 250), radius 40, and (300, 250), radius 60: the outer tangent above them + // has the normal (-0.1, -√0.99) and touches them at center + radius × normal. + let n = Vec2::new(-0.1, -(0.99f64).sqrt()); + let (on_a, on_b) = (Point::new(100.0, 250.0) + n * 40.0, Point::new(300.0, 250.0) + n * 60.0); + s.select_tool("lineSegment", ViewInfo::default()).unwrap(); + let to = on_b + Vec2::new(0.5, 0.7); + for (k, x, y) in [(Down, 100.0, 210.0), (Drag, 200.0, 200.0), (Drag, to.x, to.y), (Up, to.x, to.y)] { + s.pointer(&PointerEvent::new(k, x, y), ViewInfo::default()).unwrap(); + } + assert_eq!(count(&s), 3); + let id = *s.doc().unwrap().selection.objects.first().unwrap(); + let NodeKind::Path { path, .. } = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("a path") }; + let ends: Vec<Point> = path.subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends.len(), 2); + // Within what the drawn circles' 0.03% radius error allows. + assert!((ends[0] - on_a).hypot() < 0.15 && (ends[1] - on_b).hypot() < 0.15, "{ends:?}, want {on_a:?} {on_b:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(count(&s), 2, "one undo removes the line"); +} diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index 62587f4824..ed4a82dce6 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -4027,3 +4027,35 @@ fn apply_fill_to_stroke_with_characters_selected_changes_only_them() { let labels = undo_labels(&s); assert_eq!((labels.len(), labels.last().map(String::as_str)), (steps + 1, Some("Apply Fill to Stroke"))); } + +/// Redefines `[Normal Character Style]` with `fill` (`charStyle.setAttrs`). +fn set_normal_fill(s: &mut Session, fill: vectorcraft_color::Paint) { + let attrs = crate::cmd::textstyles::char_attrs(&CharStyle { fill, ..CharStyle::default() }); + s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": {"fill": attrs["fill"]}})).unwrap(); +} + +/// #7975: type the Type tool starts is filled as [Normal Character Style] is, black unless it was +/// redefined, not with the current fill a shape left behind. +#[test] +fn new_type_takes_the_normal_character_style_fill_not_the_current_fill() { + use vectorcraft_color::{Color, Paint}; + let mut s = session(); + let v = ViewInfo::default(); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 60, "height": 60})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + assert_eq!(s.paint.fill, Paint::solid(Color::rgb(1.0, 0.0, 0.0)), "the current fill is red"); + s.select_tool("type", v).unwrap(); + click(&mut s, 200.0, 200.0); + s.tool_text("Black", v).unwrap(); + let id = s.doc().unwrap().selection.objects[0]; + assert_eq!(obj(&s, id).runs[0].style.fill, Paint::solid(Color::BLACK)); + // A redefined [Normal Character Style] gives new type its fill. + let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + set_normal_fill(&mut s, blue.clone()); + let made = s.execute("text.create", &json!({"x": 100, "y": 300, "text": "Blue"})).unwrap(); + assert_eq!(obj(&s, NodeId(made["id"].as_u64().unwrap())).runs[0].style.fill, blue); + // A color given to the command still wins. + let made = s.execute("text.create", &json!({"x": 100, "y": 400, "text": "Green", "color": "#00ff00"})).unwrap(); + assert_eq!(obj(&s, NodeId(made["id"].as_u64().unwrap())).runs[0].style.fill, Paint::solid(Color::rgb(0.0, 1.0, 0.0))); +} diff --git a/crates/engine/src/tests/textimport.rs b/crates/engine/src/tests/textimport.rs index b369346096..cc89a8261b 100644 --- a/crates/engine/src/tests/textimport.rs +++ b/crates/engine/src/tests/textimport.rs @@ -468,6 +468,15 @@ fn malformed_docx_fails_cleanly() { assert!(e.contains("not a WordprocessingML document"), "{e}"); let e = place(&mut s, "a.docx", &store(&[("word/document.xml", b"<w:document><w:body>")])).unwrap_err(); assert!(e.contains("not well-formed XML"), "{e}"); + for xml in [ + format!(r#"<w:document xmlns:w="{W_NS}"><w:body><w:p><w:r><w:t>partial text</w:t></w:r></w:p>"#), + document("<w:p><w:r><w:t>A&missing;B</w:t></w:r></w:p>"), + document("<w:p><w:r><w:t xml:space=\"preserve\" xml:space=\"default\">text</w:t></w:r></w:p>"), + document("<w:p xmlns:a=\"urn:test\" xmlns:b=\"urn:test\" a:id=\"1\" b:id=\"2\"><w:r><w:t>text</w:t></w:r></w:p>"), + ] { + let e = place(&mut s, "a.docx", &store(&[("word/document.xml", xml.as_bytes())])).unwrap_err(); + assert!(e.contains("not well-formed XML"), "{e}"); + } let e = place(&mut s, "a.docx", &store(&[("word/document.xml", document("<w:p/>").as_bytes())])).unwrap_err(); assert!(e.contains("no text to place"), "{e}"); // A file whose headers understate what it unpacks to, and one whose headers say it is too large. diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index 9119c3e151..a50485f3f8 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -2420,6 +2420,69 @@ fn a_variable_library_defines_text_variables_and_data_sets() { assert_eq!(s.doc().unwrap().doc.variables.datasets.len(), 2); } +/// The Variables panel's Import… reads a data source by its extension, in any case: a .csv, .tsv +/// or .txt file as Import Data Sets… reads it, and an .xml file as Load Variable Library… reads it. +/// Any other extension, or none, is refused before the file is read. +#[test] +fn variable_import_reads_a_data_source_by_its_extension() { + let dir = Folder::new("vars-import"); + let mut s = session(); + let t = text(&mut s, "Alice"); + s.execute("variable.define", &json!({"name": "Name", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Name", "ids": [t.0]})).unwrap(); + + for name in ["rows.csv", "rows.TSV", "rows.txt"] { + let path = dir.file(name); + write(&path, b"Name\nAnn\nBob\n"); + let r = s.execute("variable.import", &json!({"path": path})).unwrap(); + assert_eq!((r["format"].clone(), r["names"].clone()), (json!("csv"), json!(["Data Set 1", "Data Set 2"])), "{name}"); + } + s.execute("dataset.select", &json!({"name": "Data Set 2"})).unwrap(); + assert_eq!(plain(&s, t), "Bob"); + + let xml = r#"<variableSets><variableSet><variables><variable varName="Name" trait="textcontent"/></variables><sampleDataSets><sampleDataSet dataSetName="Row 1"><Name><p>Charlie</p></Name></sampleDataSet></sampleDataSets></variableSet></variableSets>"#; + let path = dir.file("library.Xml"); + write(&path, xml.as_bytes()); + let r = s.execute("variable.import", &json!({"path": path})).unwrap(); + assert_eq!((r["format"].clone(), r["names"].clone(), r["deleted"].clone()), (json!("xml"), json!(["Row 1"]), json!([]))); + // The library declares the bound text variable, so its binding stays. + s.execute("dataset.select", &json!({"name": "Row 1"})).unwrap(); + assert_eq!(plain(&s, t), "Charlie"); + + // The extension picks the reader: CSV text in an .xml file goes to the library reader, which + // refuses it, and a library in a .csv file goes to the CSV reader. + let csv_in_xml = dir.file("rows.xml"); + write(&csv_in_xml, b"Name\nAnn\n"); + let e = s.execute("variable.import", &json!({"path": csv_in_xml})).unwrap_err().to_string(); + assert!(e.contains("variable.loadLibrary"), "{e}"); + let xml_in_csv = dir.file("library.csv"); + write(&xml_in_csv, xml.as_bytes()); + let e = s.execute("variable.import", &json!({"path": xml_in_csv})).unwrap_err().to_string(); + assert!(e.contains("dataset.import"), "{e}"); + + // Other extensions, or none, are refused before the file is read, so a missing file gives the + // same error; the data sets stay as they were. + let refused = "Import reads a data source file ending in .csv, .tsv, .txt or .xml"; + for (name, exists) in [("rows.json", true), ("rows", true), ("rows.csv.bak", true), ("missing.ai", false)] { + let path = dir.file(name); + if exists { + write(&path, b"Name\nAnn\n"); + } + let e = s.execute("variable.import", &json!({"path": path})).unwrap_err().to_string(); + assert!(e.contains(refused), "{name}: {e}"); + } + let names: Vec<String> = s.doc().unwrap().doc.variables.datasets.iter().map(|d| d.name.clone()).collect(); + assert_eq!(names, ["Row 1"]); + + // `path` is required, and the command takes no other parameter. + for bad in [json!({}), json!({"path": 3})] { + let e = s.execute("variable.import", &bad).unwrap_err().to_string(); + assert!(e.contains("missing `path`"), "{bad}: {e}"); + } + let e = s.execute("variable.import", &json!({"path": dir.file("rows.csv"), "csv": "Name\nX\n"})).unwrap_err().to_string(); + assert!(e.contains("unknown parameter `csv`"), "{e}"); +} + /// Load Variable Library replaces the document's variables and data sets: every variable goes with /// its bindings and values, a variable of another kind with a library variable's name included, /// and every data set goes, the active one included. A text variable the library also declares @@ -2665,6 +2728,11 @@ fn malformed_variable_libraries_are_refused() { let long_graph = format!("<Shown><data><values>{}</values></data></Shown>", row.repeat(2_000)); let cases = [ ("not well-formed XML", "<variableSets><variableSet>".to_string()), + ("not well-formed XML", ok.replace("<p>x</p>", "<p>A&missing;B</p>")), + ("not well-formed XML", ok.replace("</variableSets>", "")), + ("not well-formed XML", ok.replace("varName=\"Name\"", "varName=\"Name\" varName=\"Other\"")), + ("not well-formed XML", ok.replace("<variable ", "<variable xmlns:a=\"urn:test\" xmlns:b=\"urn:test\" a:id=\"1\" b:id=\"2\" ")), + ("missing `varName`", ok.replace("varName=\"Name\"", "xmlns:m=\"urn:metadata\" m:varName=\"Name\"")), ("no `variableSets` element", "<svg><variables/></svg>".to_string()), ("declares no variables", "<variableSets><variableSet><variables/></variableSet></variableSets>".to_string()), ("is declared twice", library(&[("Name", "textcontent"), ("Name", "textcontent")], &[])), @@ -3545,6 +3613,17 @@ fn variable_sort_orders_the_list_by_each_column() { } } +#[test] +fn variable_library_attributes_keep_their_namespace() { + let mut s = session(); + let xml = library(&[("Name", "textcontent")], &[("A", &[("Name", &["x"])])]) + .replace("varName=\"Name\"", "xmlns:m=\"urn:metadata\" m:varName=\"Other\" varName=\"Name\""); + let loaded = s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap(); + assert_eq!(loaded["variables"], json!(["Name"])); + let sets = s.execute("dataset.list", &json!({})).unwrap(); + assert_eq!(sets["datasets"][0]["values"], json!({"Name": {"text": "x"}})); +} + /// The sort is panel state: it is not an undo step and does not count as a change to save, and /// setting the order the list already has does not redraw anything. A bad `by` or `descending` /// is an error that leaves the order as it was. 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<u8> { } 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/src/tooling.rs b/crates/engine/src/tooling.rs index 59eb78a51b..9250cf8030 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -255,7 +255,7 @@ impl Session { } // The Selection and Group Selection tools act on the instance whole. self.select_whole_instance(id); - // The tool lent to does not see the press: it counts as a press elsewhere for the clicks a + // The lending tool does not see the press: it counts as a press elsewhere for the clicks a // double-click or triple-click compares. self.tool.press_elsewhere(); let lent = self.make_tool(id); @@ -1347,6 +1347,18 @@ impl Session { } // Every value is checked before any is set, so an invalid one changes nothing. vectorcraft_tools::builder::check_builder_options(tool.unwrap_or(self.tool.id()), &values)?; + if tool.unwrap_or(self.tool.id()) == vectorcraft_tools::cropimage::ID { + use vectorcraft_tools::cropimage as crop; + // The most the selected image can be cropped to, when one is selected. + let max = self.doc().ok().and_then(|st| { + let (id, _) = crop::selected_image(&st.doc, &st.selection)?; + match &st.doc.node(id)?.kind { + vectorcraft_doc::NodeKind::Image(im) => Some(crop::image_ppi(im).1), + _ => None, + } + }); + crop::check_options(&values, max)?; + } // The Place queue is read later, by a click outside any automation scope: its files must // be readable now, under the roots of whoever sets it. if let Some(entries) = values.get("queue").and_then(|q| q.get("entries")).and_then(Value::as_array) { 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 fce3742d11..fd1edc9b77 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -963,6 +963,13 @@ fn structured_junk() { ("addon.pathtools.trim", json!({"points": [[0, 0], [1e7, 1e7], [-1e7, 5], [0, 0]]})), ("addon.pathtools.trim", json!({"points": [[0, 0], [1, "y"], null]})), ("addon.pathtools.trim", json!({"at": [50, 50], "tolerance": 100})), + // Path Precision Tools: Tangent Circle. + ("addon.pathtools.tangentCircle", json!({"ids": [2, 3], "radius": 1e6, "circle": u64::MAX})), + ("addon.pathtools.tangentCircle", json!({"ids": [2, 3, 4], "radius": f64::MIN_POSITIVE, "circle": -1})), + ("addon.pathtools.tangentCircle", json!({"ids": [2, 2], "radius": "1 mm"})), + ("addon.pathtools.tangentCircle", json!({"ids": [2, 3], "radius": 0.01, "circle": 64})), + ("addon.pathtools.tangentCircle", json!({"ids": [2, 3, 4]})), + ("addon.pathtools.tangentCircle", json!({"ids": "x", "radius": f64::NAN, "circle": 1.5})), // Arrange Tools add-on. ("addon.arrange.grid", json!({"columns": u64::MAX, "gapX": 1e6, "gapY": -1e6, "centerOnArtboard": true})), ("addon.arrange.grid", json!({"layout": "row", "gapX": f64::MAX, "columns": -1})), @@ -984,6 +991,10 @@ fn structured_junk() { ("addon.pathtools.divideDashes", json!({"dash": 1e-308, "gap": -1e308, "fit": "x"})), ("addon.pathtools.divideDashes", json!({"dash": 0.01, "gap": 1e6, "fit": true, "removeGaps": false})), ("addon.pathtools.divideDashes", json!({"dash": f64::MAX, "gap": [0], "removeGaps": null})), + ("addon.pathtools.commonTangents", json!({"tangents": "all", "centerline": true})), + ("addon.pathtools.commonTangents", json!({"tangents": "x", "centerline": "y", "ids": [u64::MAX, -1]})), + ("addon.pathtools.commonTangents", json!({"tangents": null, "ids": [1, 2, 3, 4], "centerline": null})), + ("addon.pathtools.commonTangents", json!({"tangents": ["external"], "ids": "all"})), ("addon.pathtools.expandDashes", json!({})), ("addon.pathtools.expandDashes", json!({"ids": [0, 1, 2, 3, u64::MAX]})), ("addon.pathtools.expandDashes", json!({"ids": "x", "junk": f64::MAX})), @@ -993,6 +1004,16 @@ fn structured_junk() { ("addon.document.symbolsFromLayers", json!({"layers": "x", "replace": 3})), ("addon.document.symbolsFromLayers", json!({"layers": [1e308, -1, null, u64::MAX], "replace": true})), ("addon.document.symbolsFromLayers", json!({"layers": [], "replace": true})), + // Packaging Tools add-on. + ("addon.packaging.setRole", json!({"role": "cut", "ids": [u64::MAX], "overprint": "no"})), + ("addon.packaging.setRole", json!({"role": ["crease"], "ids": "all"})), + ("addon.packaging.setRole", json!({"role": "none", "overprint": null})), + ("addon.packaging.roles", json!({"ids": [-1, 1e300]})), + ("addon.packaging.setRoleSwatch", json!({"role": "perforation", "swatch": "[Registration]"})), + ("addon.packaging.setRoleSwatch", json!({"role": "cut", "swatch": 5})), + ("addon.packaging.check", json!({"ids": [u64::MAX, -1], "select": "yes", "tolerance": 1e308})), + ("addon.packaging.check", json!({"tolerance": "-5 mm", "select": true})), + ("addon.packaging.check", json!({"ids": [], "tolerance": null})), // Smart Pen add-on. ("addon.pen.append", json!({"id": 2, "x": 1e308, "y": 0, "in": [1e308, -1e308]})), ("addon.pen.append", json!({"id": 2, "subpath": u64::MAX, "x": 0, "y": 0, "segment": "curved"})), @@ -1472,7 +1493,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<Result<image::RgbaImage, Refused>> { + 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::<u16>(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::<u16>(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::<u32>(Tag::Unknown(292)).ok().flatten().unwrap_or(0); + let lsb_first = d.find_tag_unsigned::<u16>(Tag::FillOrder).ok().flatten() == Some(2); + let encoding = if compression == 3 && t4_options & 1 != 0 { + // Each row's tag bit says how it is coded. + EncodingMode::Group3_2D { k: 2 } + } else { + EncodingMode::Group3_1D + }; + // 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::<u32>(Tag::TileWidth).ok().flatten().filter(|&v| v > 0)?; + let th = d.find_tag_unsigned::<u32>(Tag::TileLength).ok().flatten().filter(|&v| v > 0)?; + (tw, th, Tag::TileOffsets, Tag::TileByteCounts) + } else { + let rows = d.find_tag_unsigned::<u32>(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::<u64>(offsets).ok().flatten().unwrap_or_default(); + let counts = d.find_tag_unsigned_vec::<u64>(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<Result<image::RgbaImage, Refused>> { + 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<Vec<u8>> { + let mut files = Vec::new(); + for (width, height) in [(1usize, 1usize), (7, 3), (40, 6), (64, 17), (131, 9)] { + let rows: Vec<Vec<bool>> = (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 8de519fa4e..21c7fa8a15 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -1,5 +1,5 @@ //! Untrusted files never crash the app: garbage, truncated, mutated and hostile SVG, PDF, DXF and HP-GL input, -//! mutated raster images (Photoshop documents and JPEG XL images among them) placed with File → Place, and swatch (`.vcswatches`, `.gpl`, `.ase`), graphic style (`.vcstyles`), flattener preset +//! mutated raster images (Photoshop documents and JPEG XL images among them) placed with File → Place, Photoshop documents' slices (damaged or cut short) opened and placed, and swatch (`.vcswatches`, `.gpl`, `.ase`), graphic style (`.vcstyles`), flattener preset //! (`.vcflattener`) and export preset (`.vcexportpresets`) libraries, shortcut sets and action sets other apps save as text (`.kys`, `.aia`), and native files (compressed, damaged, saved for older versions), //! must load as an error or as a document that then renders and exports, without a panic; nor may //! bitmaps, PDF and text pasted from other apps, nor EMF and WMF pictures (damaged files, records @@ -37,7 +37,41 @@ fn config() -> ProptestConfig { fn affinity_preview_sample() -> Vec<u8> { 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<u8>)> { 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<u8>)> { 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::<Vec<_>>()))); - let gray = jxl(ColorSpace::Luma, BitDepth::Sixteen, &(0..30).map(|i| (i * 41) as u8).collect::<Vec<_>>()); + use craft_jxl::{EncodeOptions, ImageRef, Layout, Samples}; + let opts = EncodeOptions { lossless: true, ..EncodeOptions::default() }; + let rgba: Vec<u8> = (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<u16> = (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 "); @@ -1939,6 +2017,271 @@ proptest! { } } +// ---------- PSD slices ---------- + +/// A Unicode string as a PSD file stores it: a count of UTF-16 units, then the units. +fn psd_unicode(s: &str) -> Vec<u8> { + let units: Vec<u16> = s.encode_utf16().collect(); + let mut b = (units.len() as u32).to_be_bytes().to_vec(); + b.extend(units.iter().flat_map(|u| u.to_be_bytes())); + b +} + +/// A descriptor key or class ID: length 0 and its four characters, or its length and its characters. +fn psd_key(k: &str) -> Vec<u8> { + let mut b = if k.len() == 4 { 0u32 } else { k.len() as u32 }.to_be_bytes().to_vec(); + b.extend(k.as_bytes()); + b +} + +/// A descriptor's class (an empty name and the ID `null`), then the count of its items. +fn psd_class(count: usize) -> Vec<u8> { + let mut b = psd_unicode(""); + b.extend(psd_key("null")); + b.extend((count as u32).to_be_bytes()); + b +} + +/// A descriptor of `items`, each a key and a typed value. +fn psd_descriptor(items: &[(&str, Vec<u8>)]) -> Vec<u8> { + let mut b = psd_class(items.len()); + for (k, v) in items { + b.extend(psd_key(k)); + b.extend(v); + } + b +} + +/// A typed descriptor value: its four-character type, then `body`. +fn psd_value(kind: &[u8; 4], body: &[u8]) -> Vec<u8> { + [kind.as_slice(), body].concat() +} + +fn psd_long(v: i32) -> Vec<u8> { + psd_value(b"long", &v.to_be_bytes()) +} + +fn psd_text(t: &str) -> Vec<u8> { + psd_value(b"TEXT", &psd_unicode(t)) +} + +fn psd_enum(kind: &str, v: &str) -> Vec<u8> { + psd_value(b"enum", &[psd_key(kind), psd_key(v)].concat()) +} + +/// A bounds object: left, top, right and bottom (px), stored top, left, bottom, right. +fn psd_bounds([l, t, r, b]: [i32; 4]) -> Vec<u8> { + psd_value(b"Objc", &psd_descriptor(&[("Top ", psd_long(t)), ("Left", psd_long(l)), ("Btom", psd_long(b)), ("Rght", psd_long(r))])) +} + +/// The slices of the samples: origin (0: generated automatically, 1: follows a layer, 2: made by +/// the user), name, and left, top, right and bottom on the 12 × 10 px canvas. Two come in; the +/// automatic one between them is left out. +const PSD_SLICES: [(u32, &str, [i32; 4]); 3] = [(2, "a", [1, 2, 5, 6]), (0, "auto", [0, 0, 12, 1]), (1, "b", [6, 3, 11, 9])]; + +/// The data of an image resource 1050 holding [`PSD_SLICES`]. +struct SliceSample { + version: u32, + data: Vec<u8>, + /// Where the slice count starts in `data`. + count_at: usize, +} + +/// Version 6: the bounds of all the slices, the group's name, the count and one record per slice. +/// The first record is followed by a Photoshop 7 descriptor (version 16) with a nested object, which +/// the reader reads past to the second record. +fn psd_slices_v6() -> SliceSample { + let mut b = 6u32.to_be_bytes().to_vec(); + b.extend([0i32, 0, 10, 12].iter().flat_map(|v| v.to_be_bytes())); + b.extend(psd_unicode("group")); + let count_at = b.len(); + b.extend((PSD_SLICES.len() as u32).to_be_bytes()); + for (i, (origin, name, rect)) in PSD_SLICES.iter().enumerate() { + // The ID, the group ID and the origin; a slice that follows a layer gives the layer's ID. + b.extend((i as u32 + 1).to_be_bytes()); + b.extend(0u32.to_be_bytes()); + b.extend(origin.to_be_bytes()); + if *origin == 1 { + b.extend(4u32.to_be_bytes()); + } + b.extend(psd_unicode(name)); + // An Image slice: its rectangle, link, target, message, alternative text, plain cell text, + // alignment and background color (alpha, red, green, blue). + b.extend(1u32.to_be_bytes()); + b.extend(rect.iter().flat_map(|v| v.to_be_bytes())); + for t in ["https://example.com/", "_blank", "", "alt"] { + b.extend(psd_unicode(t)); + } + b.push(0); + b.extend(psd_unicode("")); + b.extend([0u8; 8]); + b.extend([255, 10, 20, 30]); + if i == 0 { + b.extend(16u32.to_be_bytes()); + let color = psd_value(b"Objc", &psd_descriptor(&[("Rd ", psd_value(b"doub", &128f64.to_be_bytes()))])); + b.extend(psd_descriptor(&[("topOutset", psd_long(0)), ("bgColor", color)])); + } + } + SliceSample { version: 6, data: b, count_at } +} + +/// Versions 7 and 8: a version 16 descriptor with the slices' bounds, base name and `slices` list, +/// each slice an object with a nested bounds and background color object. +fn psd_slices_descriptor(version: u32) -> SliceSample { + let mut b = version.to_be_bytes().to_vec(); + b.extend(16u32.to_be_bytes()); + b.extend(psd_class(3)); + b.extend(psd_key("bounds")); + b.extend(psd_bounds([0, 0, 12, 10])); + b.extend(psd_key("baseName")); + b.extend(psd_text("sheet")); + b.extend(psd_key("slices")); + b.extend(b"VlLs"); + let count_at = b.len(); + b.extend((PSD_SLICES.len() as u32).to_be_bytes()); + for (i, (origin, name, rect)) in PSD_SLICES.iter().enumerate() { + let origin = match origin { + 0 => "autoGenerated", + 1 => "layerGenerated", + _ => "userGenerated", + }; + let doub = |v: f64| psd_value(b"doub", &v.to_be_bytes()); + let color = psd_value(b"Objc", &psd_descriptor(&[("Rd ", doub(10.0)), ("Grn ", doub(20.0)), ("Bl ", doub(30.0))])); + b.extend(psd_value( + b"Objc", + &psd_descriptor(&[ + ("sliceID", psd_long(i as i32 + 1)), + ("groupID", psd_long(0)), + ("origin", psd_enum("ESliceOrigin", origin)), + ("Type", psd_enum("ESliceType", "Img ")), + ("bounds", psd_bounds(*rect)), + ("Nm ", psd_text(name)), + ("url", psd_text("https://example.com/")), + ("bgColorType", psd_enum("ESliceBGColorType", "Clr ")), + ("bgColor", color), + ]), + )); + } + SliceSample { version, data: b, count_at } +} + +/// Resource 1050 in versions 6, 7 and 8. +fn psd_slice_samples() -> Vec<SliceSample> { + vec![psd_slices_v6(), psd_slices_descriptor(7), psd_slices_descriptor(8)] +} + +/// A flat 12 × 10 px RGB PSD file whose one image resource is 1050 holding `data`, and where +/// `data` lies in it. +fn sliced_psd(data: &[u8]) -> (Vec<u8>, std::ops::Range<usize>) { + // The signature, version 1, reserved bytes, 3 channels, 10 rows, 12 columns, 8 bits, RGB, and + // no color mode data. + let mut f = b"8BPS\0\x01\0\0\0\0\0\0\0\x03".to_vec(); + f.extend(10u32.to_be_bytes()); + f.extend(12u32.to_be_bytes()); + f.extend([0, 8, 0, 3]); + f.extend([0; 4]); + let mut block = b"8BIM".to_vec(); + block.extend(1050u16.to_be_bytes()); + block.extend([0, 0]); + block.extend((data.len() as u32).to_be_bytes()); + let start = f.len() + 4 + block.len(); + block.extend(data); + block.resize(block.len().next_multiple_of(2), 0); + f.extend((block.len() as u32).to_be_bytes()); + f.extend(block); + // No layer and mask information, then the merged image, raw. + f.extend([0; 4]); + f.extend([0, 0]); + f.extend((0..360u32).map(|v| (v * 7) as u8)); + (f, start..start + data.len()) +} + +/// PSD file `f` opened (the names of the document's slices, and the open's warnings), counted by +/// `document.psdInfo`, and placed embedded in a new document (the count of the slices it brings in). +fn sliced_psd_imports(f: &[u8]) -> (Vec<String>, Value, Value, usize) { + let mut s = vectorcraft_engine::Session::new(); + let p = json!({"name": "sheet.psd", "dataBase64": vectorcraft_format::base64_encode(f)}); + let r = s.execute("document.open", &p).unwrap(); + let names = s.doc().unwrap().doc.slices.iter().map(|x| x.options.name.clone()).collect(); + let info = s.execute("document.psdInfo", &p).unwrap(); + s.execute("file.new", &json!({})).unwrap(); + let placed = s.execute("file.place", &json!({"name": "sheet.psd", "dataBase64": vectorcraft_format::base64_encode(f), "link": false})).unwrap(); + (names, r["warnings"].clone(), info["slices"].clone(), placed["slices"].as_array().map_or(0, Vec::len)) +} + +/// Each sample reaches the slice reader: its two user slices open and place, without a warning, +/// and `document.psdInfo` counts them; the automatic one is left out. +#[test] +fn the_sliced_psd_samples_bring_in_their_user_slices() { + for sample in psd_slice_samples() { + let (names, warnings, info, placed) = sliced_psd_imports(&sliced_psd(&sample.data).0); + assert_eq!(names, ["a", "b"], "version {}: {warnings}", sample.version); + assert_eq!(warnings.as_array().map_or(0, Vec::len), 0, "version {}: {warnings}", sample.version); + assert_eq!((info, placed), (json!(2), 2), "version {}", sample.version); + } +} + +/// A slice count past the 10,000 read, or one larger than the slices stored, and resource data cut +/// short, open and place the file without its slices, with a warning, and `document.psdInfo` +/// counts none. +#[test] +fn sliced_psd_samples_with_huge_counts_or_cut_short_come_in_without_their_slices() { + for sample in psd_slice_samples() { + let mut damaged = vec![]; + for count in [10_001u32, 0x7fff_ffff, u32::MAX] { + let mut d = sample.data.clone(); + d[sample.count_at..sample.count_at + 4].copy_from_slice(&count.to_be_bytes()); + damaged.push((format!("count {count}"), d)); + } + damaged.push(("one byte short".into(), sample.data[..sample.data.len() - 1].to_vec())); + damaged.push(("cut in the count".into(), sample.data[..sample.count_at + 2].to_vec())); + for (what, d) in damaged { + let (names, warnings, info, placed) = sliced_psd_imports(&sliced_psd(&d).0); + let warned = warnings.as_array().is_some_and(|w| w.iter().any(|w| w.as_str().is_some_and(|w| w.contains("the slices can't be read")))); + assert!(warned, "version {}, {what}: {warnings}", sample.version); + assert_eq!((names.len(), info, placed), (0, json!(0), 0), "version {}, {what}", sample.version); + } + } +} + +proptest! { + #![proptest_config(config())] + + /// Mutated copies of the slice samples never crash opening the file, `document.psdInfo` or + /// placing it embedded: the resource's data mutated, then kept whole, cut short with the + /// resource's length saying so, or with the file cut short in the resource's block. + #[test] + fn mutated_psd_slices_never_panic(which in 0usize..3, mode in 0u8..3, cut in any::<usize>(), edits in prop::collection::vec((any::<usize>(), any::<u8>()), 0..12)) { + let SliceSample { version, mut data, .. } = psd_slice_samples().swap_remove(which); + let len = data.len(); + for (at, b) in edits { + data[at % len] = b; + } + let bytes = match mode { + 0 => sliced_psd(&data).0, + 1 => { + data.truncate(cut % (len + 1)); + sliced_psd(&data).0 + } + _ => { + let (mut f, at) = sliced_psd(&data); + f.truncate(at.start - 12 + cut % (len + 13)); + f + } + }; + let r = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + let p = json!({"name": "sheet.psd", "dataBase64": vectorcraft_format::base64_encode(&bytes)}); + let _ = no_panic(s.execute("document.open", &p)); + let _ = no_panic(s.execute("document.psdInfo", &p)); + let _ = no_panic(s.execute("file.new", &json!({}))); + let p = json!({"name": "sheet.psd", "dataBase64": vectorcraft_format::base64_encode(&bytes), "link": false}); + let _ = no_panic(s.execute("file.place", &p)); + }); + prop_assert!(r.is_ok(), "version {version}, mode {mode}: panicked: {:?}", r.err()); + } +} + /// 1-bit TIFFs compressed with CCITT Group 3: modified Huffman (Compression 2) in three strips, T.4 /// (Compression 3) with two-dimensional rows, fill bits, six EOLs at the end and each byte's lowest /// bit first, and T.4 two-dimensional rows in 16 × 16 tiles. @@ -1993,7 +2336,41 @@ proptest! { /// and a 32-bit one with an extension area. fn targa_samples() -> Vec<(&'static str, Vec<u8>)> { 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(); @@ -2511,6 +2888,32 @@ proptest! { paste_from_elsewhere("clipboard.importEps", json!({"dataBase64": vectorcraft_format::base64_encode(ps.as_bytes())}))?; } + /// Any bytes read by `readhexstring` or `readline` into strings of any length, from the + /// program's own file, through a filter decoded when first read, or from a file being run: + /// read as data, or as an error. + #[test] + fn eps_readhexstring_and_readline_data_never_panic( + data in prop::collection::vec(prop::sample::select(vec![b'0', b'9', b'a', b'F', b'g', b' ', b'\t', b'\r', b'\n', b'>', b'%', b'(', 0u8, 0xff]), 0..300), + len in 0usize..40, + line in any::<bool>(), + source in 0usize..3, + ) { + let op = if line { "readline" } else { "readhexstring" }; + let file = if source == 1 { "currentfile /ASCIIHexDecode filter" } else { "currentfile" }; + let reads = format!("/s {len} string def /f {file} def 30 {{ f s {op} pop pop }} repeat"); + let mut bytes = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec(); + if source == 2 { + bytes.extend_from_slice(format!("currentfile 0 (endstream) /SubFileDecode filter cvx exec\n{reads}\n").as_bytes()); + bytes.extend_from_slice(&data); + bytes.extend_from_slice(b"\nendstream\nshowpage\n"); + } else { + bytes.extend_from_slice(format!("{reads}\n").as_bytes()); + bytes.extend_from_slice(&data); + bytes.extend_from_slice(b"\nshowpage\n"); + } + survive("readhexstring and readline data", || vectorcraft_eps::import(&bytes).ok().map(|r| r.document))?; + } + /// Damaged or hostile CMYK images (a CMYK JPEG, an image with a key color): read as images, /// or as an error. #[test] @@ -2682,7 +3085,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::<String>()); } }); @@ -2739,7 +3159,7 @@ fn arb_ps_token() -> impl Strategy<Value = String> { "gsave", "grestore", "save", "restore", "concat", "translate", "scale", "rotate", "setlinewidth", "setdash", "setgray", "setrgbcolor", "setcmykcolor", "sethsbcolor", "setcolorspace", "setcolor", "setpattern", "makepattern", "shfill", "arc", "arcn", "arct", "arcto", "rectfill", "rectclip", "rectstroke", "image", "imagemask", "colorimage", "currentfile", "filter", - "readhexstring", "readstring", "show", "stringwidth", "charpath", "findfont", "scalefont", "makefont", "setfont", "selectfont", + "readhexstring", "readstring", "readline", "show", "stringwidth", "charpath", "findfont", "scalefont", "makefont", "setfont", "selectfont", "def", "bind", "load", "dup", "exch", "pop", "roll", "index", "copy", "for", "repeat", "loop", "exit", "if", "ifelse", "exec", "stopped", "begin", "end", "dict", "array", "string", "get", "put", "getinterval", "putinterval", "aload", "astore", "forall", "[", "]", "<<", ">>", "{", "}", "matrix", "currentmatrix", "setmatrix", "transform", "itransform", "invertmatrix", "pathbbox", 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/it/three_d_light_color.rs b/crates/engine/tests/it/three_d_light_color.rs index 381bc92f15..40752a2fce 100644 --- a/crates/engine/tests/it/three_d_light_color.rs +++ b/crates/engine/tests/it/three_d_light_color.rs @@ -579,6 +579,29 @@ fn colored_light_surfaces_match_supersampling_at_internal_facet_edges() { assert!(failures.is_empty(), "{failures:#?}"); } +/// Inflate turned so its facets narrow to slivers at the edges, in an opaque solid fill under two +/// colored lights, against 3x averaged down ([`seams_against_supersampled`]): each facet and its +/// seam cover an edge pixel once together, so at most one RGB channel is more than 3 levels off, by +/// no more than 4, and no alpha is off. +#[test] +fn turned_colored_inflate_facets_and_seams_cover_their_edges_once() { + let lights = json!([ + {"color":"#ff0000","rotation":135,"height":35,"intensity":70}, + {"color":"#0000ff","rotation":-35,"height":25,"intensity":65} + ]); + let (mut s, _) = setup("threeD.inflate"); + let change = json!({"index":0,"item":null,"params":{"ambient":10,"lights":lights,"rotationX":50,"rotationY":35}}); + s.execute("effect.setParams", &change).unwrap(); + s.execute("paint.setFill", &json!({"color":"#ffcc66"})).unwrap(); + let image = render(doc(&s)); + let (measured, color, max, holes, worst) = seams_against_supersampled(doc(&s), &image); + assert!(measured > 2_000, "{measured} pixels inside"); + assert!( + holes == 0 && color <= 1 && max <= 4, + "of {measured} pixels, {color} channels off by more than 3 (at most {max}), {holes} alphas off: {worst:?}" + ); +} + /// The closed facet edges of colored-light surfaces survive SVG and PDF, read back and drawn at /// 1:1, and Expand Appearance: inside the art, every pixel stays opaque and within 6 levels of the /// live art. @@ -648,6 +671,107 @@ fn batched_colored_inflate_preserves_compound_holes_and_surface_opacity() { assert_eq!(image.pixels, render(doc(&s)).pixels); } +/// The alpha of `d` drawn at 1:1 against a 3x render averaged down. Inside the art, on each pixel +/// whose 3x average and its eight neighbors' share one alpha, a pixel is off when it is below 255 +/// where that alpha is 255, otherwise more than 3 levels away from it. Outside the art, a pixel is +/// painted past the outline when it has an alpha above 3 where it and its eight neighbors are empty +/// at 3x. Returns (pixels measured inside, pixels off, the largest alpha off, pixels painted past the +/// outline, the first few of either). +fn alpha_against_supersampled(d: &Document) -> (usize, usize, u8, usize, Vec<String>) { + let image = render(d); + let fine = vectorcraft_render::Renderer::new().render( + d, + 1200, + 1200, + kurbo::Affine::scale(3.0), + &vectorcraft_render::RenderOptions { background: None, artboards: false, ..Default::default() }, + ); + let average = fine.area_resized(400, 400).unwrap(); + let (mut measured, mut off, mut worst, mut past) = (0, 0, 0, 0); + let mut first = vec![]; + for y in 1..399 { + for x in 1..399 { + let q = average.pixel(x, y)[3]; + if !(y - 1..=y + 1).all(|y| (x - 1..=x + 1).all(|x| average.pixel(x, y)[3] == q)) { + continue; + } + let p = image.pixel(x, y)[3]; + let wrong = if q == 0 { + let painted = p > 3; + past += usize::from(painted); + painted + } else { + measured += 1; + let hole = if q == 255 { p < 255 } else { p.abs_diff(q) > 3 }; + off += usize::from(hole); + worst = worst.max(p.abs_diff(q)); + hole + }; + if wrong && first.len() < 4 { + first.push(format!("({x},{y}) {p} vs {q}")); + } + } + } + (measured, off, worst, past, first) +} + +/// Revolve under colored lights draws each face of a gradient-lit surface on its own, over an +/// underlay of its faces clipped to the surface's outline: at 1:1, no pixel inside the art lets the +/// background through where a 3x render averaged down is opaque, none paints past the outline, and +/// a surface's opacity, its gradient's transparent stops and its blending mode apply once. The same +/// holds for the art read back from SVG and PDF and for Expand Appearance. +#[test] +fn colored_revolve_faces_leave_no_alpha_holes_at_one_to_one() { + let gradient = |opacity: f64| { + json!({"gradient":{"kind":"linear","start":[100,150],"end":[200,150],"stops":[ + {"offset":0,"color":"#ffffff","opacity":opacity},{"offset":1,"color":"#808080","opacity":opacity} + ]}}) + }; + let lights = json!([ + {"color":"#ff0000","rotation":135,"height":35,"intensity":70}, + {"color":"#0000ff","rotation":-35,"height":25,"intensity":65} + ]); + let cases = [ + ("red light, gradient", gradient(1.0), json!({}), None), + ("red light, solid", json!({"color":"#ffcc66"}), json!({}), None), + ("two lights, gradient", gradient(1.0), json!({"ambient":10,"lights":lights}), None), + ("two lights, solid", json!({"color":"#ffcc66"}), json!({"ambient":10,"lights":lights}), None), + ("red light, edge-on faces", gradient(1.0), json!({"rotationX":-80}), None), + ("red light, gradient at 60%", gradient(0.6), json!({}), None), + ("red light, fill at 60%", gradient(1.0), json!({}), Some(json!({"item":0,"opacity":60}))), + ("red light, multiply", gradient(1.0), json!({}), Some(json!({"item":0,"blend":"Multiply"}))), + ]; + let mut failures = vec![]; + for (name, fill, params, transparency) in cases { + let (mut s, _) = capped_profile(); + s.execute("effect.setParams", &json!({"index":0,"item":null,"params":params})).unwrap(); + s.execute("paint.setFill", &fill).unwrap(); + if let Some(t) = transparency { + s.execute("transparency.set", &t).unwrap(); + } + let svg = s.execute("document.serialize", &json!({"format":"svg"})).unwrap()["text"].as_str().unwrap().to_owned(); + assert!(!svg.contains("<image"), "{name}"); + let pdf = s.execute("document.serialize", &json!({"format":"pdf"})).unwrap(); + let pdf = vectorcraft_format::base64_decode(pdf["dataBase64"].as_str().unwrap()).unwrap(); + assert!(!pdf.windows(b"/Subtype /Image".len()).any(|w| w == b"/Subtype /Image"), "{name}"); + let live = doc(&s).clone(); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + for (of, d) in [ + ("live", live), + ("SVG", vectorcraft_svg::import(&svg).unwrap()), + ("PDF", vectorcraft_pdf::import(&pdf).unwrap()), + ("expanded", doc(&s).clone()), + ] { + let (measured, off, worst, past, first) = alpha_against_supersampled(&d); + assert!(measured > 10_000, "{name} {of}: {measured} pixels inside"); + if off > 0 || past > 0 { + failures.push(format!("{name} {of}: of {measured} pixels, {off} off (at most {worst}), {past} past the outline: {first:?}")); + } + } + } + assert!(failures.is_empty(), "{failures:#?}"); +} + /// Under colored lights, an Inflate fill and stroke in solid colors draw each face on its own, in /// one depth order: zoomed in, the fill's faces show the colors the one composite of the surface /// shows (drawn when the stroke is translucent), with no seam between faces; at 1x, where a pixel 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#"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40"><image x="0" y="0" width="40" height="40" href="ext.png"/></svg>"#; 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/engine/tests/plugin_safe_mode.rs b/crates/engine/tests/plugin_safe_mode.rs index 2c5fc1c307..9ff0d0668a 100644 --- a/crates/engine/tests/plugin_safe_mode.rs +++ b/crates/engine/tests/plugin_safe_mode.rs @@ -463,6 +463,69 @@ fn expand_appearance_keeps_a_plug_in_effect_safe_mode_skips() { s.execute("effect.expandAppearance", &json!({})).unwrap(); } +/// In Safe Mode, a plug-in effect in the art of a graph design in a series stops Expand Appearance of the graph only +/// when an effect of the series group draws that art with the group. +#[test] +fn expand_appearance_in_safe_mode_checks_design_art_its_series_group_draws() { + let _f = fresh(); + let mut s = Session::new(); + let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.graph", "effect", "{}"), r#"{"objects":[]}"#)).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4"; + let graph = s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"] + .as_u64() + .unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].clone(); + s.execute("effect.apply", &json!({"effect": "plugin.test.sm.graph", "ids": [r]})).unwrap(); + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + s.execute("graph.design", &json!({"new": "Plug"})).unwrap(); + s.execute("graph.column", &json!({"id": graph, "seriesIndexes": [0], "design": "Plug"})).unwrap(); + let series = |s: &Session, index: u32| { + let d = &s.doc().unwrap().doc; + let n = d.node(vectorcraft_engine::doc::NodeId(graph)).unwrap(); + n.children().unwrap().iter().find(|c| c.extras().series_index == Some(index)).unwrap().id + }; + let (art_series, other_series) = (series(&s, 0), series(&s, 1)); + // A mark in the other series has an effect to expand. + let mark = s.doc().unwrap().doc.node(other_series).unwrap().children().unwrap()[0].id; + s.execute("effect.apply", &json!({"effect": "distort.puckerBloat", "ids": [mark.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [graph]})).unwrap(); + safe_mode::set_active(Some(safe_mode::Source::Flag)); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + safe_mode::set_active(None); + s.execute("edit.undo", &json!({})).unwrap(); + // With a Transform effect on the art's series group, expanding the group draws the art's plug-in effect. + let shift = { + let t = s.execute("shape.rectangle", &json!({"x": 700, "y": 20, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.transform", "ids": [t], "params": {"moveH": 5}})).unwrap(); + s.doc().unwrap().doc.node(vectorcraft_engine::doc::NodeId(t)).unwrap().appearance.effects[0].clone() + }; + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(art_series).unwrap().appearance.effects.push(shift); + s.execute("select.set", &json!({"ids": [graph]})).unwrap(); + safe_mode::set_active(Some(safe_mode::Source::Flag)); + let err = s.execute("effect.expandAppearance", &json!({})).unwrap_err().to_string(); + safe_mode::set_active(None); + assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}"); + // With a Gaussian Blur on a fill of the art's series group instead, expanding the group makes an image of it, art included. + let blurred_fill = { + let t = s.execute("shape.rectangle", &json!({"x": 700, "y": 40, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [t], "item": 0, "params": {"radius": 2}})).unwrap(); + s.doc().unwrap().doc.node(vectorcraft_engine::doc::NodeId(t)).unwrap().appearance.items[0].clone() + }; + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let g = d.node_mut(art_series).unwrap(); + g.appearance.effects.clear(); + g.appearance.items.push(blurred_fill); + } + s.execute("select.set", &json!({"ids": [graph]})).unwrap(); + safe_mode::set_active(Some(safe_mode::Source::Flag)); + let err = s.execute("effect.expandAppearance", &json!({})).unwrap_err().to_string(); + safe_mode::set_active(None); + assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}"); +} + /// In Safe Mode, a plug-in effect on a dimension selected with the art it measures does not stop /// Expand Appearance: the dimension is left as it is, its effect included, and the art expands. #[test] 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.rs b/crates/eps/src/ai_editing.rs index f27e646791..b6ddb245c2 100644 --- a/crates/eps/src/ai_editing.rs +++ b/crates/eps/src/ai_editing.rs @@ -265,6 +265,15 @@ pub fn export_ai_editing(doc: &Document, o: &AiEditingOptions) -> Result<AiEditi /// [`export_ai_editing`] writing at most `max_objects` objects, counted as the reader counts them. fn export_within(doc: &Document, o: &AiEditingOptions, max_objects: usize) -> Result<AiEditingOutput, String> { + export_held(doc, o, max_objects, true) +} + +/// [`export_within`]; with `keep_wraps`, wrapped area type the reader wraps the same is written as +/// type ([`writer::wraps_held`]). When such type is written and art is left out at the object +/// limit, the wrap objects above it may be among what is left out, and the document is written +/// again with that type as its outlines. +fn export_held(source: &Document, o: &AiEditingOptions, max_objects: usize, keep_wraps: bool) -> Result<AiEditingOutput, String> { + let doc = source; let board = doc.artboards.first().ok_or("the document has no artboard")?.rect; if !(board.is_finite() && board.width() > 0.0 && board.height() > 0.0) { return Err("the document has no artboard".into()); @@ -277,6 +286,8 @@ fn export_within(doc: &Document, o: &AiEditingOptions, max_objects: usize) -> Re let (symbol_styled, pattern_styled) = writer::styled_definitions(doc); let own_styles = doc.graphic_styles != Document::new(1.0, 1.0).graphic_styles; let links = writer::style_links(doc); + // Before baking, which leaves the wrap objects that may be written as they are unchanged. + let wraps_held = if keep_wraps { writer::wraps_held(doc, &styled) } else { HashSet::new() }; // Live geometry effects as their result, as the PDF part draws them. let baked = baked(doc); let doc = baked.as_ref().unwrap_or(doc); @@ -309,6 +320,7 @@ fn export_within(doc: &Document, o: &AiEditingOptions, max_objects: usize) -> Re w.brushes_live = scale == 1.0; w.symbol_doc = symbol_doc; w.max_objects = max_objects; + w.wraps_held = wraps_held; w.reserve_swatch_gradients(); if scale == 1.0 { w.styled = styled; @@ -320,6 +332,9 @@ fn export_within(doc: &Document, o: &AiEditingOptions, max_objects: usize) -> Re for layer in &doc.layers { w.layer(layer); } + if w.wrapped_type_cut() { + return export_held(source, o, max_objects, false); + } // The symbols no instance uses too; their art adds definitions. w.symbols(); // The brushes, once the layers have said whether an object is written with one. diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index c1e1d664df..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<u8> { 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<Node>], path: &str, out: &mut Vec<Strin let blob = doc.image_blob(im).unwrap(); let pixels = match blob.cmyk() { Some(inks) if blob.is_cmyk() => 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<String> = 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::<Vec<_>>()); 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); @@ -10810,6 +11020,129 @@ fn unreachable_envelope() -> ! { panic!("not an envelope") } +/// `doc` with its first artboard 20,000.5 points wide: it is written on a large canvas, at 1/10. +fn on_large_canvas(mut doc: Document) -> Document { + doc.artboards[0].rect = Rect::new(0.0, 0.0, 20_000.5, 100.0); + doc +} + +/// A route an envelope was read back by: its name, the envelope and the reader's notes. +type EnvelopeRoute = (&'static str, Node, Vec<String>); + +/// The envelope `doc` holds alone on its first layer, read back from the editing data alone and +/// beside a page that draws as `doc` does ([`read_with_page`]); and the writer's warnings. +fn envelope_both_routes(doc: &Document) -> (Vec<EnvelopeRoute>, Vec<String>) { + let (alone, warnings, notes) = envelope_back(doc); + let (paged, _, page_notes) = read_with_page(doc); + assert_eq!(paged.len(), 1, "{paged:#?} {page_notes:?}"); + (vec![("alone", alone, notes), ("beside its page", (*paged[0]).clone(), page_notes)], warnings) +} + +/// On a large canvas, a warp, a mesh and a top object envelope, with Edit Contents off and on, are +/// written live at 1/10 and open as the same envelope at their size, from the editing data alone +/// and beside the page: contents, Fidelity, Edit Contents, Envelope Options, shape and name as +/// saved. Saved again as they opened, they open as the same envelope again. +#[test] +fn large_canvas_envelope_kinds_round_trip_on_both_ai_routes() { + // GUARDS: an envelope on a large canvas was written as its drawn art, with a warning. + use vectorcraft_doc::live::EnvelopeOptions; + for (name, kind) in live_envelope_kinds() { + for editing in [false, true] { + let what = format!("{name}, editing {editing}"); + let doc = on_large_canvas(envelope_doc(kind.clone(), 50.0, editing, EnvelopeOptions::NEW)); + let text = program(&doc); + assert!(text.contains("%AI24_LargeCanvasScale: 10\n") && text.contains("AIDeformOptionsKey"), "{what}"); + let (routes, warnings) = envelope_both_routes(&doc); + assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{what}: {warnings:?}"); + for (route, back, notes) in routes { + let what = format!("{what}, {route}"); + assert!(!notes.iter().any(|w| w == crate::import::ENVELOPE_DRAWN), "{what}: {notes:?}"); + let NodeKind::Envelope { content, kind: got, fidelity, editing: e, options, frame } = &back.kind else { + panic!("{what}: {back:#?} {notes:?}") + }; + assert_eq!((*fidelity, *e, *options, **frame), (50.0, editing, EnvelopeOptions::NEW, Affine::IDENTITY), "{what}"); + assert!(same_envelope_kind(&kind, got), "{what}: {got:?}"); + assert_eq!(back.name.as_deref(), Some("Bent"), "{what}"); + let colors: Vec<Option<Color>> = content.iter().map(|c| c.appearance.fill_paint().color()).collect(); + assert_eq!(colors, [Some(Color::rgb(1.0, 0.0, 0.0)), Some(Color::rgb(0.0, 0.0, 1.0))], "{what}"); + let b = content.iter().filter_map(|c| c.visual_bounds()).reduce(|a, b| a.union(b)).unwrap(); + let want = Rect::new(40.0, 20.0, 160.0, 80.0); + assert!([b.x0 - want.x0, b.y0 - want.y0, b.x1 - want.x1, b.y1 - want.y1].iter().all(|d| d.abs() < 1e-2), "{what}: {b:?}"); + } + let (back, _, _) = envelope_back(&doc); + let mut again = on_large_canvas(Document::new(200.0, 100.0)); + let layer = again.layers[0].id; + again.insert(Some(layer), usize::MAX, back).unwrap(); + let (twice, warnings, notes) = envelope_back(&again); + assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{what}, saved again: {warnings:?}"); + let NodeKind::Envelope { kind: twice, .. } = &twice.kind else { panic!("{what}, saved again: {twice:#?} {notes:?}") }; + assert!(same_envelope_kind(&kind, twice), "{what}, saved again: {twice:?}"); + } + } +} + +/// On a large canvas, envelopes with Distort Appearance whose stroked contents (at fractional places) +/// map from their bounds with their strokes keep that margin, the contents' 8-point strokes and the +/// Distort Linear Gradients and Distort Pattern Fills switches, from the editing data alone and +/// beside the page. +#[test] +fn large_canvas_envelope_stroke_margin_round_trips_on_both_ai_routes() { + // GUARDS: read from the editing data alone, the saved size was compared at 1/10 with contents at + // their size, and the contents' strokes came back at 1/10: the margin was lost. + use vectorcraft_doc::live::{EnvelopeOptions, envelope_content_boxes, envelope_stroke_margin}; + for (name, kind) in live_envelope_kinds() { + for editing in [false, true] { + let what = format!("{name}, editing {editing}"); + let mut doc = Document::new(200.0, 100.0); + let switches = EnvelopeOptions { distort_linear_gradients: editing, distort_pattern_fills: !editing, ..EnvelopeOptions::NEW }; + let mut envelope = envelope_node(&mut doc, kind.clone(), 50.0, editing, switches); + let NodeKind::Envelope { content, options, .. } = &mut envelope.kind else { unreachable_envelope() }; + for c in content.iter_mut() { + let c = Arc::make_mut(c); + c.transform(Affine::translate((0.25, 0.375)), true); + let fill = c.appearance.fill_paint(); + c.appearance = Appearance::basic(fill, solid(Color::BLACK), 8.0).into(); + } + let (stroked, plain) = envelope_content_boxes(content, Affine::IDENTITY).unwrap(); + options.bounds_margin = envelope_stroke_margin(stroked, plain).unwrap(); + let want = *options; + assert!(want.bounds_margin.iter().all(|m| *m > 0.0), "{what}: {want:?}"); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, envelope).unwrap(); + let (routes, warnings) = envelope_both_routes(&on_large_canvas(doc)); + assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{what}: {warnings:?}"); + for (route, back, notes) in routes { + let what = format!("{what}, {route}"); + let NodeKind::Envelope { content, options, .. } = &back.kind else { panic!("{what}: {back:#?} {notes:?}") }; + let margin = options.bounds_margin; + assert!(margin.iter().zip(want.bounds_margin).all(|(a, b)| (a - b).abs() < 1e-4), "{what}: {margin:?} {want:?}"); + assert_eq!(EnvelopeOptions { bounds_margin: want.bounds_margin, ..*options }, want, "{what}"); + let widths: Vec<f64> = content.iter().filter_map(|c| c.appearance.stroke().map(|s| s.width)).collect(); + assert!(widths.len() == 2 && widths.iter().all(|w| (w - 8.0).abs() < 1e-4), "{what}: {widths:?}"); + } + } + } +} + +/// On a large canvas a path's stroke weight and dashes, written at 1/10, come back at their size +/// from the editing data alone. +#[test] +fn a_large_canvas_path_keeps_its_stroke_weight_and_dashes_read_alone() { + // GUARDS: read from the editing data alone, the stroke's weight, dashes and dash offset came + // back at 1/10 while the path came back at its size. + let mut doc = on_large_canvas(Document::new(200.0, 100.0)); + let mut n = + Node::path(doc.alloc_id(), shapes::line((20.0, 50.0).into(), (180.0, 50.0).into()), Appearance::basic(Paint::None, solid(Color::BLACK), 6.0)); + n.appearance.stroke_mut().unwrap().dash = Some(Dash { pattern: vec![12.0, 4.5], offset: 3.0, align_corners: false }); + put(&mut doc, n); + let back = read_back(&doc); + let st = back.layers[0].children().unwrap()[0].appearance.stroke().cloned().unwrap(); + assert!((st.width - 6.0).abs() < 1e-6, "{st:?}"); + let dash = st.dash.unwrap(); + assert!(dash.pattern.len() == 2 && (dash.pattern[0] - 12.0).abs() < 1e-6 && (dash.pattern[1] - 4.5).abs() < 1e-6, "{dash:?}"); + assert!((dash.offset - 3.0).abs() < 1e-6, "{dash:?}"); +} + /// The record is written in the order the reader reads it: on `%_` lines the group holding the /// grid, its dictionary with the options, the contents' block and the kind, then the distorted art /// on plain lines and the plugin's `XP`. While the contents are edited, the group holds them and @@ -10923,7 +11256,10 @@ fn envelopes_the_reader_cannot_open_live_are_written_as_their_art() { ("fractional fidelity", fractional), ("margin kept", margin_kept), ]; - for (what, doc) in cases { + // On a large canvas too. + let large: Vec<(String, Document)> = + cases.iter().map(|(what, doc)| (format!("{what}, on a large canvas"), on_large_canvas(doc.clone()))).collect(); + for (what, doc) in cases.into_iter().map(|(what, doc)| (what.to_string(), doc)).chain(large) { let text = program(&doc); assert!(!text.contains("AIDeformOptionsKey"), "{what}: {text}"); let (back, warnings, _) = envelope_back(&doc); @@ -11508,6 +11844,349 @@ fn same_region(before: &[(Vec<[f64; 4]>, f64, bool)], after: &[(Vec<[f64; 4]>, f before.len() == after.len() && before.iter().zip(after).all(|(b, a)| close(&b.0, &a.0) && (b.1 - a.1).abs() < 1e-6 && b.2 == a.2) } +/// A `w` × `h` document of area type "Body" in the frame `frame`, with `over` above it (bottom +/// first), its wrap shapes resolved as the canvas resolves them. +fn wrapped_body(w: f64, h: f64, frame: Rect, over: impl FnOnce(&mut Document) -> Vec<Node>) -> Document { + use vectorcraft_doc::{TextKind, TextObject, TextRun}; + let mut doc = Document::new(w, h); + let layer = doc.layers[0].id; + let size = frame.height() / 20.0; + let mut body = TextObject::point(vectorcraft_geom::Point::ZERO, "", style(size, Color::BLACK)); + body.runs = vec![TextRun::new("one two three four five six seven eight nine ten eleven twelve", style(size, Color::BLACK))]; + body.kind = TextKind::Area { frame: shapes::rectangle(frame) }; + body.xf = Affine::IDENTITY; + let body = named(text_node(&mut doc, body), "Body"); + let over = over(&mut doc); + for n in std::iter::once(body).chain(over) { + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + vectorcraft_doc::text::resolve_wrap(None, &mut doc); + doc +} + +/// The characters, frame and wrap shapes of the area type on `doc`'s first layer, as it is (its +/// shapes not resolved again). +fn area_type(doc: &Document) -> Option<(String, Option<Rect>, usize)> { + use vectorcraft_doc::TextKind; + doc.layers[0].children().unwrap().iter().find_map(|n| match &n.kind { + NodeKind::Text(t) if matches!(&t.kind, TextKind::Area { .. }) => { + let TextKind::Area { frame } = &t.kind else { return None }; + Some((t.runs.iter().map(|r| r.text.as_str()).collect(), frame.transformed(t.xf).bounds(), t.wrap.len())) + } + _ => None, + }) +} + +/// Area type wrapped only by plain paths, compound paths and groups that don't clip is written as +/// type and reopens as area type with its characters, its frame and the same wrap shapes, which +/// the reader works out again from the objects above it ([`crate::import`]'s +/// `resolve_text_wrap`): a filled path with a negative offset and Invert Wrap, a locked path with +/// only a stroke, a compound path, a group of two squares with a hidden member, an offset of +/// -1000 pt, and an empty group and an open line with options, which wrap nothing. +#[test] +fn area_type_wrapped_by_plain_objects_stays_type() { + type Make = fn(&mut Document) -> Vec<Node>; + fn ring(doc: &mut Document, r: Rect) -> Node { + let outer = Node::path(doc.alloc_id(), shapes::rectangle(r), Appearance::default()); + let inner = Node::path(doc.alloc_id(), shapes::rectangle(r.inset(-10.0)), Appearance::default()); + let mut ring = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd }); + ring.appearance = Appearance::basic(solid(Color::gray(0.5)), Paint::None, 0.0).into(); + ring + } + let cases: [(&str, Make); 6] = [ + ("a path, a negative offset, Invert Wrap", |doc| { + vec![wrapped(square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)), -4.25, true)] + }), + ("a locked stroked path", |doc| { + let mut n = Node::path( + doc.alloc_id(), + shapes::ellipse(Rect::new(80.0, 30.0, 180.0, 130.0)), + Appearance::basic(Paint::None, solid(Color::BLACK), 2.0), + ); + n.locked = true; + vec![wrapped(n, 6.0, false)] + }), + ("a compound path", |doc| vec![wrapped(ring(doc, Rect::new(80.0, 30.0, 200.0, 150.0)), 7.0, true)]), + ("a group", |doc| { + let a = square(doc, Rect::new(40.0, 40.0, 80.0, 80.0), Color::gray(0.5)); + let mut hidden = square(doc, Rect::new(120.0, 40.0, 160.0, 80.0), Color::gray(0.5)); + hidden.visible = false; + let b = square(doc, Rect::new(200.0, 100.0, 240.0, 140.0), Color::gray(0.5)); + vec![wrapped(group(doc, vec![a, hidden, b], false), -2.0, false)] + }), + ("an offset of -1000 pt", |doc| vec![wrapped(square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)), -1000.0, false)]), + ("an empty group and an open line", |doc| { + let line = Node::path( + doc.alloc_id(), + shapes::line((20.0, 20.0).into(), (280.0, 180.0).into()), + Appearance::basic(Paint::None, solid(Color::BLACK), 1.0), + ); + let empty = group(doc, vec![], false); + let n = square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)); + vec![wrapped(n, 3.0, false), wrapped(empty, 5.0, false), wrapped(line, 5.0, false)] + }), + ]; + for (name, make) in cases { + let doc = wrapped_body(300.0, 200.0, Rect::new(10.0, 10.0, 290.0, 190.0), make); + let before = area_type(&doc).unwrap(); + assert_ne!(before.2, 0, "{name}: the type is wrapped"); + let out = export_ai_editing(&doc, &opts()).unwrap(); + let text_out = String::from_utf8_lossy(&out.program).replace("\r\n", "\n"); + assert!(!out.warnings.iter().any(|w| w == writer::TYPE), "{name}: {:?}", out.warnings); + assert!(text_out.contains("/AI11Text"), "{name}"); + let back = read_back(&doc); + let after = area_type(&back).unwrap_or_else(|| panic!("{name}: no area type\n{text_out}")); + assert_eq!(after.0, before.0, "{name}"); + let (b, a) = (before.1.unwrap(), after.1.unwrap()); + assert!([b.x0 - a.x0, b.y0 - a.y0, b.x1 - a.x1, b.y1 - a.y1].iter().all(|d| d.abs() < 1e-3), "{name}: {b:?} {a:?}"); + assert_eq!(after.2, before.2, "{name}: the reader wrapped it"); + assert!(same_region(&area_wrap_region(&doc), &area_wrap_region(&back)), "{name}\n{text_out}"); + // The object that wraps it comes back as the same kind, lock and options. + let source = |d: &Document| { + let n = d.layers[0].children().unwrap()[1].clone(); + (std::mem::discriminant(&n.kind), n.locked, n.visible, n.extras().wrap) + }; + assert_eq!(source(&back), source(&doc), "{name}\n{text_out}"); + } +} + +/// Area type stays outlines when a wrap object above it is not written as itself, or its shapes +/// are not the ones the objects above it give it: an object with an effect, a blend, a symbol +/// instance, a path with a gradient, a compound path with a hidden member, a group holding type, +/// a compound path of one subpath (read back as a path), an offset past 1000 pt, a clipping group, and shapes of an object that has moved since. +#[test] +fn area_type_wrapped_by_other_objects_stays_outlines() { + type Make = fn(&mut Document) -> Vec<Node>; + let cases: [(&str, Make); 10] = [ + ("an effect", |doc| { + let n = styled_rect(doc, "Shadowed", Rect::new(100.0, 40.0, 160.0, 120.0), solid(Color::gray(0.5)), Paint::None, vec![drop_shadow()]); + vec![wrapped(n, 4.0, false)] + }), + ("a blend", |doc| { + let keys = vec![ + Arc::new(square(doc, Rect::new(60.0, 80.0, 70.0, 90.0), Color::gray(0.5))), + Arc::new(square(doc, Rect::new(220.0, 110.0, 230.0, 120.0), Color::gray(0.5))), + ]; + let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(60.0), ..Default::default() }; + vec![wrapped(Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }), 4.5, false)] + }), + ("a symbol instance", |doc| { + two_leaves(doc); + vec![wrapped(instance(doc, "Leaf", Affine::new([3.0, 0.0, 0.0, 3.0, 150.0, 100.0])), 4.5, false)] + }), + ("a gradient", |doc| { + let g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]); + let ap = Appearance::basic(Paint::Gradient(Box::new(GradientPaint::new(g))), Paint::None, 0.0); + vec![wrapped(Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(100.0, 40.0, 160.0, 120.0)), ap), 4.0, false)] + }), + ("a compound path with a hidden member", |doc| { + let outer = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(80.0, 30.0, 200.0, 150.0)), Appearance::default()); + let mut inner = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(100.0, 50.0, 180.0, 130.0)), Appearance::default()); + inner.visible = false; + let mut ring = + Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd }); + ring.appearance = Appearance::basic(solid(Color::gray(0.5)), Paint::None, 0.0).into(); + vec![wrapped(ring, 4.0, false)] + }), + ("a group holding type", |doc| { + let label = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(100.0, 100.0), "Label", style(20.0, Color::BLACK)); + let label = text_node(doc, label); + let n = square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)); + vec![wrapped(group(doc, vec![n, label], false), 4.0, false)] + }), + ("a compound path of one subpath", |doc| { + let only = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(80.0, 30.0, 200.0, 150.0)), Appearance::default()); + let mut one = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(only)], rule: FillRule::NonZero }); + one.appearance = Appearance::basic(solid(Color::gray(0.5)), Paint::None, 0.0).into(); + vec![wrapped(one, 4.0, false)] + }), + ("an offset past 1000 pt", |doc| vec![wrapped(square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)), 1000.5, false)]), + ("a clipping group", |doc| { + let clip = clipping(doc, shapes::rectangle(Rect::new(80.0, 30.0, 200.0, 150.0))); + let n = square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)); + vec![wrapped(group(doc, vec![clip, n], true), 4.0, false)] + }), + ("a path moved since", |doc| vec![wrapped(square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)), 4.0, false)]), + ]; + let mut typed = vec![]; + for (name, make) in cases { + let mut doc = wrapped_body(300.0, 200.0, Rect::new(10.0, 10.0, 290.0, 190.0), make); + assert_ne!(area_type(&doc).unwrap().2, 0, "{name}: the type is wrapped"); + if name == "a path moved since" { + let id = doc.layers[0].children().unwrap()[1].id; + doc.node_mut(id).unwrap().transform(Affine::translate((30.0, 0.0)), false); + } + let out = export_ai_editing(&doc, &opts()).unwrap(); + if !out.warnings.iter().any(|w| w == writer::TYPE) || area_type(&read_back(&doc)).is_some() { + typed.push(name); + } + } + assert!(typed.is_empty(), "written as type: {typed:?}"); +} + +/// Each frame of threaded area type is checked on its own: a thread whose first frame is wrapped +/// by a path and a group and whose second by the group alone is written as type and reopens as the +/// same thread with the same shapes in each frame; with a blend over the second frame, the whole +/// thread is written as outlines. +#[test] +fn threaded_area_type_wrapped_by_plain_objects_stays_type() { + use vectorcraft_doc::{TextKind, TextObject, TextRun}; + for blend in [false, true] { + let mut doc = Document::new(400.0, 200.0); + let layer = doc.layers[0].id; + let st = style(10.0, Color::BLACK); + let mut first = TextObject::point(vectorcraft_geom::Point::ZERO, "", st.clone()); + first.runs = vec![TextRun::new("one two three four five six seven eight nine ten eleven twelve thirteen fourteen ", st.clone())]; + first.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(10.0, 10.0, 190.0, 90.0)) }; + first.xf = Affine::IDENTITY; + let mut second = first.clone(); + second.runs = vec![TextRun::new("fifteen sixteen seventeen eighteen nineteen twenty", st.clone())]; + second.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(210.0, 10.0, 390.0, 90.0)) }; + let (first, second) = (named(text_node(&mut doc, first), "First"), named(text_node(&mut doc, second), "Second")); + doc.text_threads.push(vec![first.id, second.id]); + let path = wrapped(square(&mut doc, Rect::new(60.0, 20.0, 100.0, 60.0), Color::gray(0.5)), -3.0, true); + let over_second = if blend { + let keys = vec![ + Arc::new(square(&mut doc, Rect::new(250.0, 20.0, 260.0, 30.0), Color::gray(0.5))), + Arc::new(square(&mut doc, Rect::new(340.0, 60.0, 350.0, 70.0), Color::gray(0.5))), + ]; + let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(30.0), ..Default::default() }; + wrapped(Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }), 2.0, false) + } else { + let a = square(&mut doc, Rect::new(250.0, 20.0, 290.0, 60.0), Color::gray(0.5)); + let b = square(&mut doc, Rect::new(120.0, 50.0, 300.0, 80.0), Color::gray(0.5)); + wrapped(group(&mut doc, vec![a, b], false), 2.0, false) + }; + // Bottom first: the first frame, the path, the second frame, the group or blend. + for n in [first, path, second, over_second] { + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + vectorcraft_doc::text::resolve_wrap(None, &mut doc); + type Region = Vec<(Vec<[f64; 4]>, f64, bool)>; + let shapes = |d: &Document| -> Vec<Region> { + d.layers[0] + .children() + .unwrap() + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some( + t.wrap + .iter() + .map(|s| { + let parts = s + .path + .subpaths + .iter() + .map(|sp| { + let b = PathData::new(vec![sp.clone()]).bounds().unwrap_or_default(); + [b.x0, b.y0, b.x1, b.y1] + }) + .collect(); + (parts, s.wrap.offset, s.wrap.invert) + }) + .collect(), + ), + _ => None, + }) + .collect() + }; + let before = shapes(&doc); + assert_eq!(before.iter().map(Vec::len).collect::<Vec<_>>(), [2, 1], "blend: {blend}"); + let out = export_ai_editing(&doc, &opts()).unwrap(); + let back = read_back(&doc); + if blend { + assert!(out.warnings.iter().any(|w| w == writer::TYPE), "{:?}", out.warnings); + assert!(back.text_threads.is_empty()); + continue; + } + assert!(!out.warnings.iter().any(|w| w == writer::TYPE), "{:?}", out.warnings); + assert_eq!(back.text_threads.len(), 1); + let names: Vec<_> = back.text_threads[0].iter().map(|id| back.node(*id).and_then(|n| n.name.clone())).collect(); + assert_eq!(names, [Some("First".to_string()), Some("Second".to_string())]); + let after = shapes(&back); + assert_eq!(after.len(), 2); + for (b, a) in before.iter().zip(&after) { + assert!(same_region(b, a), "{before:?}\n{after:?}"); + } + } +} + +/// Wrapped area type is written as type only while the wrap shapes of all the area type the reader +/// reads stay within what it copies: 150 frames under a wrap object of 10,000 anchors are, and +/// with 100 more frames under it, none are. +#[test] +fn area_type_wrapped_past_the_reader_limit_stays_outlines() { + use vectorcraft_doc::{TextKind, TextObject}; + let area = |doc: &mut Document| { + let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "Wrapped", style(10.0, Color::BLACK)); + t.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)) }; + t.xf = Affine::IDENTITY; + let n = text_node(doc, t); + doc.insert(Some(doc.layers[0].id), 0, n).unwrap() + }; + let mut doc = Document::new(100.0, 100.0); + let ids: Vec<_> = (0..150).map(|_| area(&mut doc)).collect(); + let mut zigzag = vec![(40.0, 0.0).into()]; + zigzag.extend((1..10_000).map(|i| vectorcraft_geom::Point::new(40.0 + 20.0 * f64::from(i) / 10_000.0, if i % 2 == 0 { 0.0 } else { 100.0 }))); + let n = wrapped( + Node::path(doc.alloc_id(), PathData::new(vec![vectorcraft_geom::SubPath::polyline(&zigzag, true)]), Appearance::default()), + 6.0, + false, + ); + doc.insert(Some(doc.layers[0].id), usize::MAX, n).unwrap(); + vectorcraft_doc::text::resolve_wrap(None, &mut doc); + let held = writer::wraps_held(&doc, &std::collections::HashMap::new()); + assert!(ids.iter().all(|id| held.contains(id)), "{} of {}", held.len(), ids.len()); + for _ in 0..100 { + area(&mut doc); + } + assert!(vectorcraft_doc::text::wrap_work(&doc) > crate::import::MAX_WRAP_WORK); + assert!(writer::wraps_held(&doc, &std::collections::HashMap::new()).is_empty()); +} + +/// Wrapped area type stays type with room for every object, and is written as outlines when art is +/// left out at the object limit: one object short, the wrap object above it would be left out and +/// the reader would not wrap the type. +#[test] +fn area_type_wrapped_past_the_object_limit_is_written_as_outlines() { + let doc = wrapped_body(300.0, 200.0, Rect::new(10.0, 10.0, 290.0, 190.0), |doc| { + vec![wrapped(square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)), 4.0, false)] + }); + let read = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap(); + let all = export_within(&doc, &opts(), read).unwrap(); + assert!(!all.warnings.iter().any(|w| w == writer::OBJECT_LIMIT || w == writer::TYPE), "{:?}", all.warnings); + let short = export_within(&doc, &opts(), read - 1).unwrap(); + assert!(short.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "{:?}", short.warnings); + assert!(short.warnings.iter().any(|w| w == writer::TYPE), "{:?}", short.warnings); + let (back, _) = crate::ai_alone(&short.program).unwrap(); + assert!(area_type(&back).is_none(), "{}", String::from_utf8_lossy(&short.program)); +} + +/// On a large canvas, area type wrapped by a plain path is written as type and reopens with the +/// same wrap shapes, the offset at its size. +#[test] +fn area_type_wrapped_on_a_large_canvas_stays_type() { + let doc = wrapped_body(20_000.0, 20_000.0, Rect::new(1000.0, 1000.0, 9000.0, 9000.0), |doc| { + vec![wrapped(square(doc, Rect::new(3000.0, 3000.0, 5000.0, 6000.0), Color::gray(0.5)), -12.5, true)] + }); + let before = area_type(&doc).unwrap(); + assert_ne!(before.2, 0); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::TYPE), "{:?}", out.warnings); + let back = read_back(&doc); + let after = area_type(&back).expect("area type"); + assert_eq!((after.0.as_str(), after.2), (before.0.as_str(), before.2)); + let (b, a) = (area_wrap_region(&doc), area_wrap_region(&back)); + let close = b.len() == a.len() + && b.iter().zip(&a).all(|(b, a)| { + b.0.len() == a.0.len() + && b.0.iter().zip(&a.0).all(|(x, y)| x.iter().zip(y).all(|(x, y)| (x - y).abs() < 1e-2)) + && (b.1 - a.1).abs() < 1e-3 + && b.2 == a.2 + }); + assert!(close, "{b:?}\n{a:?}"); +} + /// Type written as its outlines wraps area type below it by its bounds, as it did before saving, /// not by its glyphs: its text wrap options go on an unpainted rectangle of its bounds, the last /// member of the outlines' group, which keeps the type's name and has no options of its own. @@ -11869,8 +12548,8 @@ fn an_envelope_of_area_type_in_written_art_leaves_the_wrap_on_the_bounds() { } /// A clipping path inside art cut to a clipping object is written as its fills and its strokes, -/// two objects: its text wrap options are written once, whether it has both or only strokes, and -/// with its strokes when the region outside leaves nothing of its fills. +/// two objects: its text wrap options are written once, whether it has both, only strokes, or +/// fills the region outside leaves nothing of. #[test] fn a_clipping_path_written_as_its_paint_keeps_one_text_wrap() { for (fill, left, width) in [(solid(Color::gray(0.5)), 20.0, 2.0), (Paint::None, 20.0, 2.0), (solid(Color::gray(0.5)), 101.0, 4.0)] { @@ -11981,3 +12660,347 @@ fn a_graph_with_art_left_out_is_written_without_records() { assert!(!text.contains("%_Gs") && !text.contains(" Go\n") && !text.contains("%_GS"), "{max}: {text}"); } } + +/// The wrap shapes [`vectorcraft_doc::text::resolve_wrap`] gives the area type in `doc`. +fn area_wrap(doc: &Document) -> Vec<vectorcraft_doc::WrapShape> { + let mut d = doc.clone(); + vectorcraft_doc::text::resolve_wrap(None, &mut d); + let mut out = vec![]; + d.layers[0].walk(&mut |n| { + if let NodeKind::Text(t) = &n.kind + && matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }) + { + out.clone_from(&t.wrap); + } + }); + out +} + +/// `got` and `want` are the same wrap shapes: the same options, offsets within `1e-6`, and the +/// same subpaths with anchors within `1e-3`. +fn same_shapes(got: &[vectorcraft_doc::WrapShape], want: &[vectorcraft_doc::WrapShape], case: &str) { + let same = got.len() == want.len() + && got.iter().zip(want).all(|(g, w)| { + g.wrap.invert == w.wrap.invert + && (g.wrap.offset - w.wrap.offset).abs() < 1e-6 + && g.path.subpaths.len() == w.path.subpaths.len() + && g.path.subpaths.iter().zip(&w.path.subpaths).all(|(a, b)| { + a.closed == b.closed + && a.anchors.len() == b.anchors.len() + && a.anchors.iter().zip(&b.anchors).all(|(p, q)| (p.p - q.p).hypot() < 1e-3) + }) + }); + assert!(same, "{case}\n{got:?}\n{want:?}"); +} + +/// A clipping object that isn't written as an object of its own (a group, an image, a symbol +/// instance, a path or compound path without paint in art cut to a clipping object) or is written +/// as its outlines or cut (type, a path the outer clipping object cuts) keeps its text wrap options on one unpainted object +/// of its wrap outline: area type below it wraps alike after a round trip, and the object stays +/// locked or hidden as it was. A clipping object without options gets no such object. +#[test] +fn a_clipping_object_not_written_whole_keeps_its_text_wrap() { + use vectorcraft_doc::{TextKind, TextObject, TextRun}; + let cases = ["group", "hidden", "locked", "image", "instance", "type", "unpainted path", "unpainted compound", "cut path", "no options"]; + for case in cases { + let mut doc = Document::new(400.0, 200.0); + let layer = doc.layers[0].id; + let st = style(10.0, Color::BLACK); + let mut area = TextObject::point(vectorcraft_geom::Point::ZERO, "", st.clone()); + area.runs = vec![TextRun::new("One two three four five six", st)]; + area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 400.0, 200.0)) }; + area.xf = Affine::IDENTITY; + let area = text_node(&mut doc, area); + doc.insert(Some(layer), usize::MAX, area).unwrap(); + let art = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(art) }); + let mut cutter = match case { + "group" | "hidden" | "locked" | "no options" => { + let mut off = square(&mut doc, Rect::new(200.0, 20.0, 230.0, 60.0), Color::gray(0.5)); + off.visible = false; + let members = vec![ + square(&mut doc, Rect::new(20.0, 20.0, 50.0, 60.0), Color::gray(0.5)), + square(&mut doc, Rect::new(60.0, 30.0, 90.0, 70.0), Color::gray(0.5)), + off, + ]; + group(&mut doc, members, false) + } + "image" => image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::new([20.0, 0.0, 0.0, 20.0, 30.0, 40.0]), None), + "instance" => instance(&mut doc, "Leaf", Affine::translate((40.0, 30.0))), + "type" => { + let label = TextObject::point(vectorcraft_geom::Point::new(30.0, 50.0), "Clip", style(24.0, Color::BLACK)); + text_node(&mut doc, label) + } + "unpainted path" => clipping(&mut doc, shapes::rectangle(Rect::new(20.0, 20.0, 80.0, 80.0))), + "unpainted compound" => { + let outer = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 80.0, 80.0)), Appearance::default()); + let inner = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(30.0, 30.0, 70.0, 70.0)), Appearance::default()); + Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd }) + } + _ => { + let mut c = clipping(&mut doc, shapes::rectangle(Rect::new(50.0, 20.0, 150.0, 80.0))); + c.appearance = Appearance::basic(solid(Color::gray(0.5)), Paint::None, 0.0).into(); + c + } + }; + cutter.visible = case != "hidden"; + cutter.locked = case == "locked"; + let cutter = if case == "no options" { cutter } else { wrapped(cutter, -4.5, true) }; + let member = square(&mut doc, Rect::new(30.0, 30.0, 70.0, 50.0), Color::rgb(1.0, 0.0, 0.0)); + let mut top = group(&mut doc, vec![cutter, member], true); + if matches!(case, "unpainted path" | "unpainted compound" | "cut path") { + let frame = square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0), Color::gray(0.9)); + let frame = group(&mut doc, vec![frame], false); + top = group(&mut doc, vec![frame, top], true); + } + doc.insert(Some(layer), usize::MAX, top).unwrap(); + let text = program(&doc); + let back = read_back(&doc); + if case == "no options" { + assert!(!text.contains("(AI11TextWrapOffset)"), "{text}"); + assert!(wraps(back.layers[0].children().unwrap()).is_empty()); + continue; + } + assert_eq!(text.matches("(AI11TextWrapOffset)").count(), 1, "{case}\n{text}"); + same_wraps(&wraps(back.layers[0].children().unwrap()), &[(None, -4.5, true)]); + let mut carrier = None; + back.layers[0].walk(&mut |n| { + if n.extras().wrap.is_some() { + carrier = Some((n.locked, n.visible)); + } + }); + assert_eq!(carrier, Some((case == "locked", case != "hidden")), "{case}"); + let want = area_wrap(&doc); + assert_eq!(want.is_empty(), case == "hidden", "{case}"); + same_shapes(&area_wrap(&back), &want, case); + } +} + +/// With too little room for the unpainted object that carries a clipping object's text wrap +/// options, the options are left out, never written on another object, and the data stays readable. +#[test] +fn a_clipping_objects_text_wrap_is_left_out_without_room() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let members = vec![ + square(&mut doc, Rect::new(20.0, 20.0, 50.0, 60.0), Color::gray(0.5)), + square(&mut doc, Rect::new(60.0, 30.0, 90.0, 70.0), Color::gray(0.5)), + ]; + let cutter = wrapped(group(&mut doc, members, false), 2.0, false); + let member = square(&mut doc, Rect::new(30.0, 30.0, 70.0, 50.0), Color::rgb(1.0, 0.0, 0.0)); + let top = group(&mut doc, vec![cutter, member], true); + doc.insert(Some(layer), usize::MAX, top).unwrap(); + let all = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap(); + for room in 0..=all { + let out = export_within(&doc, &opts(), room).unwrap(); + assert!(crate::import::objects_read(&out.program).unwrap() <= room); + let text = String::from_utf8_lossy(&out.program).replace("\r\n", "\n"); + // The group, then the compound path of the two squares (three objects): with room for all four + // the options are written, on that compound path. + assert_eq!(text.matches("(AI11TextWrapOffset)").count(), usize::from(room >= 4), "{room}\n{text}"); + let (back, _) = crate::ai_alone(&out.program).unwrap(); + let mut carriers = vec![]; + back.layers[0].walk(&mut |n| { + if n.extras().wrap.is_some() { + carriers.push(matches!(n.kind, NodeKind::Compound { .. }) && n.appearance.items.is_empty()); + } + }); + assert_eq!(carriers, if room >= 4 { vec![true] } else { vec![] }, "{room}\n{text}"); + } +} + +/// A clipping object written as art cut to it (one that isn't a path or compound path with points, +/// or any clipping object in art already cut to one) keeps its name, its opacity mask and its +/// visibility variable on one unpainted object, locked and hidden as it was: the reader reads the +/// name once, on that object, with the mask, and binds the variable to it. The fills and strokes the +/// clipping object paints keep its opacity mask, without its name. +#[test] +fn a_cut_clipping_object_keeps_its_name_mask_and_variables() { + use vectorcraft_doc::{TextObject, Variable, VariableKind}; + // Each case, with the number of objects written for the clipping object's paint. + let cases = [ + ("group", 0), + ("hidden", 0), + ("locked", 0), + ("image", 0), + ("instance", 0), + ("blend", 0), + ("type", 1), + ("unpainted path", 0), + ("unpainted compound", 0), + ("fill", 1), + ("stroke", 1), + ("fill and stroke", 2), + ]; + for (case, parts) in cases { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let art = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(art) }); + let rect = Rect::new(20.0, 20.0, 80.0, 80.0); + let mut cutter = match case { + "image" => image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::new([20.0, 0.0, 0.0, 20.0, 30.0, 40.0]), None), + "instance" => instance(&mut doc, "Leaf", Affine::translate((40.0, 30.0))), + "blend" => { + let keys = vec![ + Arc::new(square(&mut doc, Rect::new(20.0, 20.0, 30.0, 30.0), Color::gray(0.5))), + Arc::new(square(&mut doc, Rect::new(60.0, 20.0, 70.0, 30.0), Color::gray(0.5))), + ]; + let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(10.0), ..Default::default() }; + Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }) + } + "type" => text_node(&mut doc, TextObject::point(vectorcraft_geom::Point::new(30.0, 50.0), "Clip", style(24.0, Color::BLACK))), + "unpainted path" => clipping(&mut doc, shapes::rectangle(rect)), + "unpainted compound" => { + let outer = Node::path(doc.alloc_id(), shapes::rectangle(rect), Appearance::default()); + let inner = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(30.0, 30.0, 70.0, 70.0)), Appearance::default()); + Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd }) + } + "fill" | "stroke" | "fill and stroke" => { + let mut c = clipping(&mut doc, shapes::rectangle(rect)); + let fill = if case == "stroke" { Paint::None } else { solid(Color::gray(0.5)) }; + let stroke = if case == "fill" { Paint::None } else { solid(Color::rgb(0.0, 0.0, 1.0)) }; + c.appearance = Appearance::basic(fill, stroke, if case == "fill" { 0.0 } else { 2.0 }).into(); + c + } + _ => { + let members = vec![square(&mut doc, Rect::new(20.0, 20.0, 50.0, 60.0), Color::gray(0.5)), square(&mut doc, rect, Color::gray(0.5))]; + group(&mut doc, members, false) + } + }; + cutter.name = Some("Cutter".into()); + cutter.visible = case != "hidden"; + cutter.locked = case == "locked"; + let veil = square(&mut doc, Rect::new(20.0, 20.0, 60.0, 60.0), Color::rgb(1.0, 1.0, 1.0)); + cutter.extras_mut().mask = Some(Box::new(OpacityMask::new(veil, false))); + let id = cutter.id; + let member = square(&mut doc, Rect::new(30.0, 30.0, 70.0, 50.0), Color::rgb(1.0, 0.0, 0.0)); + let mut top = group(&mut doc, vec![cutter, member], true); + if matches!(case, "unpainted path" | "unpainted compound" | "fill" | "stroke" | "fill and stroke") { + let frame = square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0), Color::gray(0.9)); + let frame = group(&mut doc, vec![frame], false); + top = group(&mut doc, vec![frame, top], true); + } + doc.insert(Some(layer), usize::MAX, top).unwrap(); + doc.variables.variables.push(Variable { name: "show".into(), kind: VariableKind::Visibility }); + doc.variables.bind(id, "show"); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().all(|w| w != writer::BINDINGS), "{case}: {:?}", out.warnings); + let text = String::from_utf8(out.program).unwrap().replace("\r\n", "\n"); + assert_eq!(text.matches("%_/XMLUID : (Cutter) ; (AI10_ArtUID) ,").count(), 1, "{case}\n{text}"); + assert_eq!(text.matches("(AI9_Mask)").count(), 1 + parts, "{case}\n{text}"); + let back = read_back(&doc); + let (mut cutters, mut masked) = (vec![], 0); + back.layers[0].walk(&mut |n| { + masked += usize::from(n.extras().mask.is_some()); + if n.name.as_deref() == Some("Cutter") { + let unpainted = matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && n.appearance.items.is_empty(); + cutters.push((n.id, unpainted, n.extras().mask.is_some(), n.locked, n.visible)); + } + }); + let [(carrier, unpainted, mask, locked, visible)] = cutters[..] else { panic!("{case}: {cutters:?}\n{text}") }; + assert!(unpainted && mask, "{case}"); + assert_eq!((locked, visible), (case == "locked", case != "hidden"), "{case}"); + assert_eq!(masked, 1 + parts, "{case}"); + assert_eq!(back.variables.objects_of("show"), vec![carrier], "{case}"); + } +} + +/// With too little room for the unpainted object that carries a cut clipping object's dictionary, +/// the dictionary is left out, never written on another object; with room for the object but not +/// for its opacity mask's art, only the mask is left out. The data stays readable. +#[test] +fn a_cut_clipping_objects_dictionary_is_left_out_without_room() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let before = named(square(&mut doc, Rect::new(150.0, 10.0, 160.0, 20.0), Color::gray(0.2)), "Before"); + doc.insert(Some(layer), usize::MAX, before).unwrap(); + let members = vec![ + square(&mut doc, Rect::new(20.0, 20.0, 50.0, 60.0), Color::gray(0.5)), + square(&mut doc, Rect::new(60.0, 30.0, 90.0, 70.0), Color::gray(0.5)), + ]; + let mut cutter = wrapped(named(group(&mut doc, members, false), "Cutter"), 2.0, false); + cutter.locked = true; + let veil = vec![ + square(&mut doc, Rect::new(20.0, 20.0, 40.0, 40.0), Color::rgb(1.0, 1.0, 1.0)), + square(&mut doc, Rect::new(40.0, 40.0, 60.0, 60.0), Color::rgb(1.0, 1.0, 1.0)), + ]; + let veil = group(&mut doc, veil, false); + cutter.extras_mut().mask = Some(Box::new(OpacityMask::new(veil, false))); + let member = square(&mut doc, Rect::new(30.0, 30.0, 70.0, 50.0), Color::rgb(1.0, 0.0, 0.0)); + let top = group(&mut doc, vec![cutter, member], true); + doc.insert(Some(layer), usize::MAX, top).unwrap(); + let all = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap(); + let mut kept = vec![]; + for room in 0..=all { + let out = export_within(&doc, &opts(), room).unwrap(); + assert!(crate::import::objects_read(&out.program).unwrap() <= room); + let text = String::from_utf8_lossy(&out.program).replace("\r\n", "\n"); + let (back, _) = crate::ai_alone(&out.program).unwrap(); + let mut found = vec![]; + back.layers[0].walk(&mut |n| { + let x = n.extras(); + if !matches!(n.kind, NodeKind::Layer { .. }) && (n.name.is_some() || x.wrap.is_some() || x.mask.is_some()) { + let carrier = matches!(n.kind, NodeKind::Compound { .. }) && n.appearance.items.is_empty(); + found.push((n.name.clone(), carrier, x.wrap.is_some(), x.mask.is_some(), n.locked)); + } + }); + let before = (Some("Before".to_string()), false, false, false, false); + let rest = match found.split_first() { + Some((b, rest)) if room > 0 => { + assert_eq!(b, &before, "{room}\n{text}"); + rest + } + _ => &found[..], + }; + match rest { + [] => kept.push((false, false)), + [(name, true, true, mask, true)] if name.as_deref() == Some("Cutter") => kept.push((true, *mask)), + _ => panic!("{room}: {found:?}\n{text}"), + } + } + assert_eq!(kept.last(), Some(&(true, true))); + // Once the carrier fits it stays, and once its mask fits it stays too. + let carrier = kept.iter().position(|k| k.0).unwrap(); + let mask = kept.iter().position(|k| k.1).unwrap(); + assert!(carrier < mask, "{kept:?}"); + assert!(kept[carrier..].iter().all(|k| k.0) && kept[mask..].iter().all(|k| k.1), "{kept:?}"); +} + +/// A cut clipping object with an opacity mask alone gets no unpainted object when its mask's art +/// doesn't fit: an object without the dictionary it was written for would be extra art. +#[test] +fn a_cut_clipping_object_without_room_for_its_mask_gets_no_carrier() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let members = vec![ + square(&mut doc, Rect::new(20.0, 20.0, 50.0, 60.0), Color::gray(0.5)), + square(&mut doc, Rect::new(60.0, 30.0, 90.0, 70.0), Color::gray(0.5)), + ]; + let mut cutter = group(&mut doc, members, false); + let veil = vec![ + square(&mut doc, Rect::new(20.0, 20.0, 40.0, 40.0), Color::rgb(1.0, 1.0, 1.0)), + square(&mut doc, Rect::new(40.0, 40.0, 60.0, 60.0), Color::rgb(1.0, 1.0, 1.0)), + ]; + let veil = group(&mut doc, veil, false); + cutter.extras_mut().mask = Some(Box::new(OpacityMask::new(veil, false))); + let top = group(&mut doc, vec![cutter], true); + doc.insert(Some(layer), usize::MAX, top).unwrap(); + let all = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap(); + for room in 0..=all { + let out = export_within(&doc, &opts(), room).unwrap(); + let text = String::from_utf8_lossy(&out.program).replace("\r\n", "\n"); + let (back, _) = crate::ai_alone(&out.program).unwrap(); + let mut carriers = vec![]; + back.layers[0].walk(&mut |n| { + if matches!(n.kind, NodeKind::Compound { .. }) && n.appearance.items.is_empty() { + carriers.push(n.extras().mask.is_some()); + } + }); + assert!(carriers.is_empty() || carriers == [true], "{room}: {carriers:?}\n{text}"); + assert_eq!(carriers.is_empty(), !text.contains("(AI9_Mask)"), "{room}\n{text}"); + if room == all { + assert_eq!(carriers, [true], "{text}"); + } + } +} diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 1b48697e32..bea247262b 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -31,6 +31,7 @@ pub(super) use envelopes::ENVELOPES; pub(super) use styles::{LARGE_CANVAS_STYLES, style_links, styled_definitions, styled_objects}; #[cfg(test)] pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, STYLE_LINKS, WARPED_IMAGES, same_appearance}; +pub(super) use texts::wraps_held; pub(super) use images::PAYLOAD; #[cfg(test)] @@ -49,7 +50,7 @@ pub(super) use variables::{ACTIVE, BINDINGS, LIMITS, VALUES}; /// [`vectorcraft_doc::MAX_DEPTH`]. pub(super) const MAX_NEST: u32 = 8; -pub(super) const TYPE: &str = "type in opacity masks, pattern tiles, symbols and art cut to a clipping object, mirrored type, area type and type on a path that is turned or unevenly scaled or whose frame or path has several parts, area type in an open frame, type on an open path whose ends meet, area type that flows around a text wrap, type of only white space, threads of type on a path, threads whose frames differ in orientation or hold a frame written as outlines, type of sizes past what the reader reads, stories past what the reader reads (1,048,576 bytes a story, 16,777,216 bytes in all, and the size of text document it reads), and type with inline graphics, ruby, gradient or pattern paint, or fills, strokes, effects or an opacity mask of the object's own, is written as its outlines in the editing data for other apps"; +pub(super) const TYPE: &str = "type in opacity masks, pattern tiles, symbols and art cut to a clipping object, mirrored type, area type and type on a path that is turned or unevenly scaled or whose frame or path has several parts, area type in an open frame, type on an open path whose ends meet, area type whose text wrap cannot be preserved from the saved objects, type of only white space, threads of type on a path, threads whose frames differ in orientation or hold a frame written as outlines, type of sizes past what the reader reads, stories past what the reader reads (1,048,576 bytes a story, 16,777,216 bytes in all, and the size of text document it reads), and type with inline graphics, ruby, gradient or pattern paint, or fills, strokes, effects or an opacity mask of the object's own, is written as its outlines in the editing data for other apps"; pub(super) const PATTERNS: &str = "pattern fills whose tiles aren't a grid or whose art reaches past the tile, pattern fills in another pattern's tile or in a symbol, and pattern fills nested more than 8 deep are written as their tiles cut to the shape in the editing data for other apps"; pub(super) const PATTERN_TILES: &str = "pattern fills with more tiles than a fill places are written filled gray in the editing data for other apps"; pub(super) const CLIPPING: &str = "clipping groups and clipping layers whose clipping object isn't a path, and the clipping groups inside them, are written as their art cut to that object in the editing data for other apps"; @@ -228,6 +229,10 @@ pub(super) struct Writer<'a> { bound: Vec<(vectorcraft_doc::NodeId, String, Vec<String>)>, /// The text document: the stories of the type written as text. pub(super) texts: texts::TextDoc, + /// The area type with wrap shapes that may be written as type ([`texts::wraps_held`]). + pub(super) wraps_held: HashSet<NodeId>, + /// Area type with wrap shapes was written as type. + wrapped_typed: bool, /// Symbol instances on the layers may be written as instances ([`Self::live_instance`]); false /// on a large canvas, where they are written as their art. pub(super) symbols_live: bool, @@ -348,6 +353,8 @@ impl<'a> Writer<'a> { typed: false, bound: vec![], texts: texts::TextDoc::default(), + wraps_held: HashSet::new(), + wrapped_typed: false, cms: vectorcraft_color::cms::active(), body: String::new(), warnings: vec![], @@ -404,6 +411,12 @@ impl<'a> Writer<'a> { } } + /// Was area type with wrap shapes written as type, and art left out at the object limit + /// ([`Self::take_objects`])? The reader may then wrap that type by fewer objects than it had. + pub(super) fn wrapped_type_cut(&self) -> bool { + self.wrapped_typed && self.left_out > 0 + } + /// Whether `count` more objects may be written: the objects written so far, counted as the /// reader counts them ([`object_count`]), stay within [`Self::max_objects`]. Past it the art is /// left out, with a warning. @@ -1218,26 +1231,25 @@ impl<'a> Writer<'a> { } /// A container's members, the first one's outline cutting the others: its fills painted - /// behind them (cut to the region outside too), its strokes over them, not cut by it. Its text - /// wrap options are written once: with its fills, or with its strokes when no fill object is - /// written (it has no fills, or the region outside leaves nothing of them). + /// behind them (cut to the region outside too), its strokes over them, not cut by it. Its name, + /// variables and text wrap options are written once, under them all, with its opacity mask + /// ([`Self::object_carrier`]), and not with its fills or strokes, which may be cut or left out + /// and keep only the opacity mask they are drawn through. fn clip_contents(&mut self, children: &[Arc<Node>]) { let Some((first, rest)) = children.split_first() else { return }; + self.object_carrier(first); // Nothing to clip by hides the clipped art. let Some((outline, rule)) = vectorcraft_effects::clip_outline(first) else { return }; let mut paint = first.clip_paint(); + for part in [&mut paint.fill, &mut paint.stroke].into_iter().flatten() { + part.extras_mut().wrap = None; + part.name = None; + } let outer = self.clip.clone(); let region = self.cut(&PathData::from_bezpath(&outline), rule); self.clip = Some(region); if let Some(fill) = &paint.fill { - let objects = self.objects; self.node(fill); - if self.objects > objects - && let Some(stroke) = &mut paint.stroke - && stroke.extras().wrap.is_some() - { - stroke.extras_mut().wrap = None; - } } for c in rest { self.node(c); @@ -1248,6 +1260,48 @@ impl<'a> Writer<'a> { } } + /// The dictionary of clipping object `first` ([`Self::dictionary`]: its name, visibility + /// variables, text wrap options and opacity mask), when it has one, on an unpainted path (a + /// compound path for several subpaths), uncut, locked and hidden as `first` is. The path is the + /// outline area type wraps around when `first` has text wrap options + /// ([`vectorcraft_doc::text::wrap_outline`]); else, and without the options when that outline is + /// empty, `first`'s clipping outline, or the rectangle of its bounds when it has none. Nothing + /// is written without such a path, or without room for the path ([`Self::take_objects`]), or + /// when the dictionary would be empty (an opacity mask left out with nothing else in it). + fn object_carrier(&mut self, first: &Node) { + let points = |p: &PathData| p.subpaths.iter().any(|sp| !sp.anchors.is_empty()); + let wrap = first.extras().wrap.filter(|_| self.drawn == 0 && !self.in_look); + let wrap_outline = wrap.map(|_| vectorcraft_doc::text::wrap_outline(first)).filter(points); + let named = first.name.as_deref().is_some_and(|s| !s.is_empty()); + let bound = !self.bound_variables(first, false, false).is_empty(); + if wrap_outline.is_none() && !named && !bound && first.extras().mask.is_none() { + return; + } + let wrapped = wrap_outline.is_some(); + let outline = wrap_outline + .or_else(|| vectorcraft_effects::clip_outline(first).map(|(o, _)| PathData::from_bezpath(&o)).filter(points)) + .or_else(|| finite_bounds(first).map(shapes::rectangle)); + let Some(outline) = outline else { return }; + let (start, state, gs, objects) = (self.body.len(), self.state, self.gs, self.objects); + self.state(first.locked, !first.visible); + self.plain_object(&outline, FillRule::NonZero, None, None, Xy::of(first).object()); + if self.objects == objects { + // Without the path, its lock and hidden lines are taken out too, and no dictionary follows. + self.body.truncate(start); + self.state = state; + return; + } + self.block_end = usize::MAX; + let path_end = self.body.len(); + // Text wrap options go only on the outline area type wraps around. + self.wrap_moved = !wrapped; + self.dictionary(first); + if self.body.len() == path_end { + self.body.truncate(start); + (self.state, self.gs, self.objects) = (state, gs, objects); + } + } + /// `path` (filled by `rule`) cut to the region the art is cut to, as a non-zero path. fn cut(&self, path: &PathData, rule: FillRule) -> PathData { match &self.clip { @@ -1482,7 +1536,11 @@ impl<'a> Writer<'a> { let thread = doc.text_threads.iter().find(|th| th.contains(&n.id)); let contents = self.contents_level.filter(|(hidden, nest, _)| (*hidden, *nest) == (self.hidden, self.nest)); // Type that can't be a stub is written as its outlines, which count their own objects. - if (self.hidden > 0 && contents.is_none()) || self.clip.is_some() || self.in_symbol || (thread.is_none() && !texts::holds(n, t)) { + if (self.hidden > 0 && contents.is_none()) + || self.clip.is_some() + || self.in_symbol + || (thread.is_none() && !texts::holds(n, t, self.wraps_held.contains(&n.id))) + { self.outlined += 1; return self.outlined_text(n, xy); } @@ -1495,7 +1553,7 @@ impl<'a> Writer<'a> { } let placed = if let Some(thread) = thread { // A thread is checked for what it loses, in every frame, when its story is written. - let placed = self.texts.thread(doc, thread, n.id, self.canvas, &|id| !cut_to_clipping_object(doc, id)); + let placed = self.texts.thread(doc, thread, n.id, self.canvas, &|id| !cut_to_clipping_object(doc, id), &self.wraps_held); placed.map(|p| (p, self.texts.take_lost())) } else { self.texts.add(t, self.canvas).map(|story| ((story, 0), texts::loses(t))) @@ -1507,6 +1565,7 @@ impl<'a> Writer<'a> { return self.outlined_text(n, xy); }; self.typed = true; + self.wrapped_typed |= !t.wrap.is_empty(); if lost { self.warn(texts::TYPE_ATTRIBUTES); } diff --git a/crates/eps/src/ai_editing/writer/envelopes.rs b/crates/eps/src/ai_editing/writer/envelopes.rs index 09c6a33550..8b4ebc880d 100644 --- a/crates/eps/src/ai_editing/writer/envelopes.rs +++ b/crates/eps/src/ai_editing/writer/envelopes.rs @@ -27,7 +27,7 @@ use super::{MAX_NEST, Writer, Xy, hide}; use crate::import::{DEFORM_PLUGIN, EnvelopeGridPoint as GridPoint, envelope_outline, envelope_upright, warp_number}; use crate::ps; -pub(in crate::ai_editing) const ENVELOPES: &str = "envelopes whose type is threaded, has text wrap options or is written as its outlines, envelopes without contents, envelopes in opacity masks, pattern tiles, art cut to a clipping object or other envelopes' contents, envelopes on the layers of a large canvas or in a turned or mirrored frame, warps drawn without their style's net, meshes and top objects that the data would open in another shape, envelopes with a Fidelity that isn't a whole number, envelopes that map from a box other than their contents' bounds with or without strokes or keep bounds margins with Distort Appearance off, envelopes after the first 256 envelopes and images with a Warp, and envelopes nested more than 8 deep are written as their art in the editing data for other apps"; +pub(in crate::ai_editing) const ENVELOPES: &str = "envelopes whose type is threaded, has text wrap options or is written as its outlines, envelopes without contents, envelopes in opacity masks, pattern tiles, art cut to a clipping object or other envelopes' contents, envelopes in a turned or mirrored frame, warps drawn without their style's net, meshes and top objects that the data would open in another shape, envelopes with a Fidelity that isn't a whole number, envelopes that map from a box other than their contents' bounds with or without strokes or keep bounds margins with Distort Appearance off, envelopes after the first 256 envelopes and images with a Warp, and envelopes nested more than 8 deep are written as their art in the editing data for other apps"; /// The most rows or columns of an envelope's grid written (Make with Mesh's own limit, and the /// reader's). @@ -356,15 +356,17 @@ fn top_object_grid(path: &PathData, corners: Option<[u32; 4]>) -> Option<(usize, impl Writer<'_> { /// Envelope `n`, of transparency `xy`, as a live envelope (see the module's form), outside opacity - /// masks' art, pattern tiles, art cut to a clipping object and the layers of a large canvas. Type - /// in its contents is written as type, which the reader makes the envelope's contents again. + /// masks' art, pattern tiles and art cut to a clipping object. On a large canvas it is written at + /// the document's reduced size, its saved box size included, which the reader reads at the + /// declared scale. Type in its contents is written as type, which the reader makes the + /// envelope's contents again. /// False, writing nothing, where it is written as its art instead: where the reader would open it /// in another shape, or with its type as drawn art (threaded type, type with text wrap options, /// type written as its outlines), or some of it is left out for the object limit /// ([`Self::take_objects`]). pub(super) fn envelope(&mut self, n: &Node, xy: Xy) -> bool { let NodeKind::Envelope { content, kind, fidelity, editing, options, frame } = &n.kind else { return false }; - if self.hidden > 0 || self.clip.is_some() || self.nest >= MAX_NEST || !self.symbols_live || self.checks_left == 0 { + if self.hidden > 0 || self.clip.is_some() || self.nest >= MAX_NEST || self.checks_left == 0 { return false; } if content.iter().any(|c| holds_type(c)) && !content.iter().all(|c| type_reads_back(c, self.doc)) { diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index 9bc831e537..506d13d9fc 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -17,6 +17,7 @@ use std::collections::{HashMap, HashSet}; use std::fmt::Write; +use std::sync::Arc; use kurbo::{ParamCurveArclen, PathSeg}; use vectorcraft_color::{Color, Paint}; @@ -197,8 +198,8 @@ fn solid(p: &Paint) -> Option<Option<Color>> { /// Can the text document hold type `t` of object `n` as it is: point type that isn't mirrored, or /// area type or type on a path that is only moved ([`shape`]); characters other than inline graphics /// and ruby; solid fills and strokes; no fills, strokes, effects or opacity mask of the object's -/// own; some text. -pub(in crate::ai_editing) fn holds(n: &Node, t: &TextObject) -> bool { +/// own; some text. Area type with wrap shapes only when `wrap_held` ([`wraps_held`]). +pub(in crate::ai_editing) fn holds(n: &Node, t: &TextObject, wrap_held: bool) -> bool { let xf = t.xf.as_coeffs(); let shape_ok = match &t.kind { TextKind::Point => xf.iter().all(|v| v.is_finite()) && t.xf.determinant() > 1e-12, @@ -210,10 +211,9 @@ pub(in crate::ai_editing) fn holds(n: &Node, t: &TextObject) -> bool { } }; // Area type with wrap shapes: the text document doesn't hold them. The reader works them out - // again from the art above the type, which can wrap it differently (a live object written as - // its drawn pieces) or not at all. + // again from the art above the type, which wraps it the same only where `wraps_held` says so. shape_ok - && t.wrap.is_empty() + && (t.wrap.is_empty() || wrap_held) && t.ruby.is_empty() && !t.stacks_warichu() && t.runs.iter().any(|r| r.text.chars().any(|c| !c.is_whitespace())) @@ -324,6 +324,112 @@ fn plain(n: &Node) -> bool { && n.extras().mask.is_none() } +/// The area type of `doc` whose wrap shapes the reader of the editing data works out again as they +/// are ([`vectorcraft_doc::text::resolve_wrap`], which the reader runs on what it reads): the +/// shapes are the ones the wrap objects above it give it now, and each of those objects is written +/// as itself and read back with the same outline and options ([`wrap_source_held`]), in layers +/// and groups written as they are ([`plain_containers`]). `styled`: the objects written with an +/// art style. Empty when the shapes of the document's area type would hold more anchors than the +/// reader copies into them ([`crate::import::MAX_WRAP_WORK`]). +pub(in crate::ai_editing) fn wraps_held(doc: &Document, styled: &HashMap<NodeId, Arc<Node>>) -> HashSet<NodeId> { + let mut held = HashSet::new(); + if vectorcraft_doc::text::wrap_work(doc) > crate::import::MAX_WRAP_WORK { + return held; + } + let mut plain_in = HashSet::new(); + for layer in &doc.layers { + plain_containers(layer, true, styled, &mut plain_in); + } + let mut checked: HashMap<NodeId, bool> = HashMap::new(); + vectorcraft_doc::text::wrap_sources(doc, |n, sources, shapes| { + let NodeKind::Text(t) = &n.kind else { return }; + if t.wrap.is_empty() || shapes != t.wrap || !plain_in.contains(&n.id) { + return; + } + let ok = sources.iter().all(|s| *checked.entry(s.id).or_insert_with(|| plain_in.contains(&s.id) && wrap_source_held(s, styled))); + if ok { + held.insert(n.id); + } + }); + held +} + +/// Adds to `out` the objects with text wrap options and the text objects in `n` (a top-level layer +/// when `top`) that sit only in layers and groups written as they are: layers and sublayers that +/// don't clip and have no effects, and groups that don't clip, have no fills, strokes, effects, +/// art style, opacity mask or graph and aren't written with an art style (`styled`). +fn plain_containers(n: &Node, top: bool, styled: &HashMap<NodeId, Arc<Node>>, out: &mut HashSet<NodeId>) { + let plain = match &n.kind { + NodeKind::Layer { clip, .. } => !clip && n.appearance.effects.is_empty(), + NodeKind::Group { clip, .. } => !top && !clip && n.appearance.items.is_empty() && own_plain(n, styled), + _ => false, + }; + if !plain { + return; + } + for c in n.children().map(Vec::as_slice).unwrap_or_default() { + if c.extras().wrap.is_some() || matches!(c.kind, NodeKind::Text(_)) { + out.insert(c.id); + } + plain_containers(c, false, styled, out); + } +} + +/// Has object `n` no effects, art style, opacity mask or graph, and isn't it a ruler guide or +/// written with an art style (`styled`)? +fn own_plain(n: &Node, styled: &HashMap<NodeId, Arc<Node>>) -> bool { + !styled.contains_key(&n.id) + && n.appearance.effects.is_empty() + && n.appearance.items.iter().all(|i| i.effects().is_empty()) + && n.extras().graphic_style.is_none() + && n.extras().mask.is_none() + && n.extras().graph.is_none() + && !n.is_ruler_guide() +} + +/// Is wrap object `n` written as itself and read back with the same outline and text wrap options: +/// an offset the writer and the reader keep as it is (-1000 to 1000 pt) and a plain object +/// ([`plain_wrap_art`])? +fn wrap_source_held(n: &Node, styled: &HashMap<NodeId, Arc<Node>>) -> bool { + n.extras().wrap.is_some_and(|w| w.offset.is_finite() && w.offset.abs() <= 1000.0) && plain_wrap_art(n, styled) +} + +/// Is `n` written as one object of its own kind that the reader reads back with the same outline +/// ([`vectorcraft_doc::text::resolve_wrap`]): a path of one subpath, a compound path of visible +/// paths with two subpaths or more in all, each painted with no paint, a solid fill, a plain line of a solid color or both, or a +/// group that doesn't clip of such paths, compound paths and groups (hidden ones too) without text +/// wrap options of their own; each without effects, art style, opacity mask or graph +/// ([`own_plain`]). Each subpath has two anchors or more. +fn plain_wrap_art(n: &Node, styled: &HashMap<NodeId, Arc<Node>>) -> bool { + use vectorcraft_doc::AppearanceItem; + let solid = |p: &Paint| matches!(p, Paint::Solid { .. }); + let painted = || match super::visible_items(n).as_slice() { + [] => true, + [AppearanceItem::Fill(f)] => solid(&f.paint), + [AppearanceItem::Stroke(s)] => solid(&s.paint) && vectorcraft_effects::stroke::is_plain(s), + [AppearanceItem::Fill(f), AppearanceItem::Stroke(s)] => solid(&f.paint) && solid(&s.paint) && vectorcraft_effects::stroke::is_plain(s), + _ => false, + }; + let whole = |p: &PathData| p.subpaths.iter().all(|sp| sp.anchors.len() >= 2); + own_plain(n, styled) + && match &n.kind { + NodeKind::Path { path, clipping: false, guide: false, .. } => path.subpaths.len() == 1 && whole(path) && painted(), + // One subpath in all would be written, and read back, as a path. + NodeKind::Compound { children, .. } => { + let subpaths: usize = children.iter().filter_map(|c| c.path_data()).map(|p| p.subpaths.len()).sum(); + let members = children.iter().all(|c| { + c.visible + && matches!(&c.kind, NodeKind::Path { path, clipping: false, guide: false, .. } if !path.subpaths.is_empty() && whole(path)) + }); + painted() && subpaths > 1 && members + } + NodeKind::Group { children, clip: false } => { + n.appearance.items.is_empty() && children.iter().all(|c| c.extras().wrap.is_none() && plain_wrap_art(c, styled)) + } + _ => false, + } +} + /// Is the end bracket of type on an open path so near the path's end that the reader reads it as /// no bracket (`Story::node`: within 0.02 of a segment)? fn end_read_as_none(t: &TextObject) -> bool { @@ -1000,7 +1106,8 @@ impl TextDoc { /// `thread` (its frames in order, all area type the document holds, the first holding the /// story) the first time one of its frames is written. `None` when the thread can't be written /// as one story: `writable` says which frames are written where type can be text (every frame - /// of the thread must be). + /// of the thread must be), and `wraps_held` which frames with wrap shapes the reader wraps the + /// same ([`wraps_held`]; every frame with wrap shapes must be one). pub(in crate::ai_editing) fn thread( &mut self, doc: &Document, @@ -1008,6 +1115,7 @@ impl TextDoc { id: NodeId, canvas: Affine, writable: &dyn Fn(NodeId) -> bool, + wraps_held: &HashSet<NodeId>, ) -> Option<(usize, usize)> { let first = *thread.first()?; if self.planned.insert(first) { @@ -1026,7 +1134,7 @@ impl TextDoc { && t.vertical == vertical && writable(n.id) // The text document doesn't hold wrap shapes (see `holds`). - && t.wrap.is_empty() + && (t.wrap.is_empty() || wraps_held.contains(&n.id)) && plain(n) && t.ruby.is_empty() && !t.stacks_warichu() diff --git a/crates/eps/src/ai_graph.rs b/crates/eps/src/ai_graph.rs index 3e1cebd9f9..cb20f0cb99 100644 --- a/crates/eps/src/ai_graph.rs +++ b/crates/eps/src/ai_graph.rs @@ -17,8 +17,8 @@ use std::fmt::Write; use kurbo::{PathSeg, Point}; use vectorcraft_color::{BlendMode, Paint}; use vectorcraft_doc::{ - Appearance, AppearanceItem, GraphKind, GraphSpec, LabelStyles, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, Node, NodeId, NodeKind, PiePosition, - PieSort, TickLength, ValueAxisSide, + Appearance, AppearanceItem, DEFAULT_FILLED_LINE_WIDTH, FILLED_LINE_OUTLINE_WIDTH, GraphKind, GraphSpec, LabelStyles, MAX_GRAPH_CATEGORIES, + MAX_GRAPH_SERIES, MIN_FILLED_LINE_WIDTH, Node, NodeId, NodeKind, PiePosition, PieSort, TickLength, ValueAxisSide, }; use vectorcraft_effects::stroke; use vectorcraft_geom::{Affine, Rect}; @@ -46,6 +46,9 @@ const EDGE: f64 = 0.01; /// Most values one `Gc` takes. const CELLS_PER_RECORD: usize = 15; +/// Widest `lineShapeWidth` the records give, in points (appendix A, `Gy`). +const MAX_LINE_WIDTH: f64 = 100.0; + /// A graph's records: what goes before its group (`%_Gs` to `%_GC`), and the `Go` line that follows /// each series' group, by the group's id. `%_GS` follows the group. pub(crate) struct Records { @@ -89,7 +92,8 @@ pub(crate) fn records(n: &Node, to_art: Affine) -> Option<Records> { (r.is_finite() && r.width() > 0.0 && r.height() > 0.0).then_some(())?; let plot = to_art.transform_rect_bbox(r); (plot.is_finite() && plot.width() > 0.0 && plot.height() > 0.0).then_some(())?; - let tags = series_groups(children, width, first_col, g.kind == GraphKind::Line)?; + let line = g.kind == GraphKind::Line; + let tags = series_groups(children, width, first_col, line, line && g.filled_lines)?; draws_axes(n, r).then_some(())?; let placed = n.geometric_bounds()?; (r.x0 >= placed.x0 - EDGE && r.y0 >= placed.y0 - EDGE && r.x1 <= placed.x1 + EDGE && r.y1 <= placed.y1 + EDGE).then_some(())?; @@ -97,14 +101,17 @@ pub(crate) fn records(n: &Node, to_art: Affine) -> Option<Records> { let mut head = String::from("%_Gs\n"); let _ = writeln!(head, "%_{} {} {} {} Gb", real(plot.x0), real(plot.y1), real(plot.x1), real(plot.y0)); let flag = |b: bool| u8::from(b); + // `lineShapeWidth`: the width filled lines are drawn at, the graph's default included. let _ = writeln!( head, - "%_{ty} {} {} 14 {} {} 0 {} 6 44 Gy", + "%_{ty} {} {} 14 {} {} {} {} {} 44 Gy", flag(g.drop_shadow), flag(g.first_row_in_front), flag(g.mark_points), flag(g.connect_points), - flag(g.legend_across_top) + flag(g.filled_lines), + flag(g.legend_across_top), + real(g.line_width.unwrap_or(DEFAULT_FILLED_LINE_WIDTH)) ); let _ = writeln!(head, "%_10 2 {} 0 {} {} {} Gd", flag(g.first_column_in_front), real(g.column_width), real(g.cluster_width), flag(g.edge_to_edge)); @@ -233,9 +240,11 @@ fn tick(t: TickLength) -> u8 { } /// Whether `g`'s settings are ones the records give and the reader keeps: a legend beside or across -/// the top, every series of the graph's type, one value axis on the left, lines not filled, no graph -/// designs, label formatting or pie settings, column and cluster widths of 1% to 1000%, and at most -/// [`MAX_TICK_MARKS`] tick marks a division. +/// the top, every series of the graph's type, one value axis on the left, lines filled only where +/// they connect the points (the records ignore the setting otherwise), a Line Width of 0.01 to +/// [`MAX_LINE_WIDTH`] points, with filled lines no series stroked as the bands' outline +/// ([`band_outline`]), which the reader reads as bands, no graph designs, label formatting or pie settings, column and +/// cluster widths of 1% to 1000%, and at most [`MAX_TICK_MARKS`] tick marks a division. fn settings_kept(g: &GraphSpec) -> bool { let percent = |p: f64| (1.0..=1000.0).contains(&p); g.legend @@ -243,7 +252,9 @@ fn settings_kept(g: &GraphSpec) -> bool { && g.value_axis == ValueAxisSide::Left && !g.separate_scales && g.right_series.is_empty() - && !g.filled_lines + && (g.connect_points || !g.filled_lines) + && g.line_width.is_none_or(|w| (MIN_FILLED_LINE_WIDTH..=MAX_LINE_WIDTH).contains(&w)) + && !(g.kind == GraphKind::Line && g.filled_lines && g.series_paints.iter().any(|p| band_outline(&p.stroke.clone().zip(p.stroke_width)))) && g.series_markers.iter().all(Option::is_none) && g.series_columns.iter().all(Option::is_none) && g.label_styles == LabelStyles::default() @@ -318,10 +329,13 @@ fn plain_paint(p: &Node) -> Option<(Option<Paint>, Option<(Paint, f64)>)> { /// The `Go` line of each series' group among `children`: a group whose series index is one of the /// `series` the table has, each once, of paths [`as_drawn`] with one fill and one line alike -/// ([`plain_paint`]), every path filled unless the graph draws lines (`line`). Its column is the +/// ([`plain_paint`]), every path filled unless the graph draws lines (`line`). With filled lines +/// (`bands`), a filled path outlined as [`band_outline`] says is a band, any other filled path is a +/// [`square`] marker or swatch, and the line of the paths that are not bands is the series' line, +/// as the reader reads it. Its column is the /// table's: after the label column when there is one (`first_col`). `None` when a series has no /// such group. -fn series_groups(children: &[std::sync::Arc<Node>], series: usize, first_col: usize, line: bool) -> Option<HashMap<NodeId, String>> { +fn series_groups(children: &[std::sync::Arc<Node>], series: usize, first_col: usize, line: bool, bands: bool) -> Option<HashMap<NodeId, String>> { let mut tags = HashMap::new(); let mut seen = vec![false; series]; for c in children { @@ -332,21 +346,63 @@ fn series_groups(children: &[std::sync::Arc<Node>], series: usize, first_col: us *slot = true; let NodeKind::Group { children: paths, clip: false } = &c.kind else { return None }; (as_drawn(c) && *c.appearance == Appearance::default() && !paths.is_empty()).then_some(())?; - let mut paints = vec![]; + let (mut paints, mut strokes) = (vec![], vec![]); for p in paths { as_drawn(p).then_some(())?; - paints.push(plain_paint(p)?); + let (fill, outline) = plain_paint(p)?; + if bands && fill.is_some() && band_outline(&outline) { + // A band, or a mark outlined as one, which the reader reads as a band. + } else if bands && fill.is_some() && !square(p) { + return None; + } else { + strokes.push(outline); + } + paints.push(fill); } - let fill = paints.iter().find_map(|(f, _)| f.clone()); - paints.iter().all(|(f, _)| f.is_none() || *f == fill).then_some(())?; - (line || paints.iter().all(|(f, _)| f.is_some())).then_some(())?; - let stroke = paints.first().and_then(|(_, s)| s.clone()); - paints.iter().all(|(_, s)| *s == stroke).then_some(())?; + let fill = paints.iter().find_map(Clone::clone); + paints.iter().all(|f| f.is_none() || *f == fill).then_some(())?; + (line || paints.iter().all(Option::is_some)).then_some(())?; + let stroke = strokes.first().cloned().flatten(); + strokes.iter().all(|s| *s == stroke).then_some(())?; tags.insert(c.id, format!("%_2 {} 0 0 Go", s + first_col)); } seen.iter().all(|s| *s).then_some(tags) } +/// Whether `stroke`, a path's line and its weight, is the thin black outline Draw Filled Lines +/// draws around a band, whatever the series' own line. +pub(crate) fn band_outline(stroke: &Option<(Paint, f64)>) -> bool { + stroke + .as_ref() + .is_some_and(|(paint, width)| *width == FILLED_LINE_OUTLINE_WIDTH && paint.color().is_some_and(|c| c.to_rgb_uncalibrated() == [0.0; 3])) +} + +/// Whether path `p` is a square with sides along the page's axes, as a data point's default +/// marker and a legend swatch are: four straight sides, closed, as wide as it is tall. In a series +/// with filled lines, every other filled path is a band. +pub(crate) fn square(p: &Node) -> bool { + let NodeKind::Path { path, .. } = &p.kind else { return false }; + if path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).count() != 1 { + return false; + } + let near = |a: f64, b: f64| (a - b).abs() <= EDGE; + let mut sides = vec![]; + for s in path.to_bezpath().segments() { + let PathSeg::Line(l) = s else { return false }; + if !(near(l.p0.x, l.p1.x) && near(l.p0.y, l.p1.y)) { + sides.push(l); + } + } + let [first, _, _, last] = sides.as_slice() else { return false }; + let (x0, x1) = sides.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), l| (lo.min(l.p0.x), hi.max(l.p0.x))); + let (y0, y1) = sides.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), l| (lo.min(l.p0.y), hi.max(l.p0.y))); + near(last.p1.x, first.p0.x) + && near(last.p1.y, first.p0.y) + && sides.iter().all(|l| near(l.p0.x, l.p1.x) || near(l.p0.y, l.p1.y)) + && x1 - x0 > EDGE + && near(x1 - x0, y1 - y0) +} + /// Whether `art` draws plot `plot`'s left edge and its bottom edge (the document's y runs down) as /// straight lines, each a shown path of one subpath with a plain line ([`plain_paint`]) in a shown /// group, as the reader finds the axes. @@ -407,7 +463,8 @@ pub(crate) mod sample { } /// Graph `g` drawn as a group: a group of each series' marks (a line graph's series as an unfilled - /// line, the others' as filled columns), its axes on the plot's left and bottom edges, and a + /// line, or with filled lines as an outlined band and its markers, the others' as filled + /// columns), its axes on the plot's left and bottom edges, and a /// legend of a swatch for each series; its series groups named after the series. pub(crate) fn graph(doc: &mut Document, g: GraphSpec) -> Node { let r = g.rect; @@ -428,7 +485,27 @@ pub(crate) mod sample { row.get(s).copied().flatten().map(|v| Point::new(r.x0 + 20.0 + 60.0 * c as f64 + 15.0 * s as f64, r.y1 - v * 10.0)) }) .collect(); - let marks: Vec<Arc<Node>> = if g.kind == GraphKind::Line { + let marks: Vec<Arc<Node>> = if g.kind == GraphKind::Line && g.filled_lines { + // A band around the line, as wide as the Line Width, with the thin black outline, and a + // marker on each point. + let half = g.filled_line_width() / 2.0; + let mut bp = kurbo::BezPath::new(); + for (i, p) in points.iter().enumerate() { + if i == 0 { bp.move_to((p.x, p.y - half)) } else { bp.line_to((p.x, p.y - half)) } + } + for p in points.iter().rev() { + bp.line_to((p.x, p.y + half)); + } + bp.close_path(); + let band = Node::path( + doc.alloc_id(), + PathData::from_bezpath(&bp), + Appearance::basic(gray.clone(), Paint::solid(Color::BLACK), super::FILLED_LINE_OUTLINE_WIDTH), + ); + let mut marks = vec![Arc::new(band)]; + marks.extend(points.iter().map(|p| path(doc, shapes::rectangle(Rect::from_center_size(*p, (5.0, 5.0))), gray.clone(), Paint::None))); + marks + } else if g.kind == GraphKind::Line { let mut bp = kurbo::BezPath::new(); for (i, p) in points.iter().enumerate() { if i == 0 { bp.move_to(*p) } else { bp.line_to(*p) } @@ -470,7 +547,7 @@ pub(crate) mod sample { /// Graphs whose records read back whole: each type the records give, every setting they keep /// changed, labels with parentheses, backslashes and non-ASCII characters, a label of 255 bytes, - /// and a table without labels. + /// a table without labels, and line graphs with filled lines and Line Widths the records give. pub(crate) fn kept() -> Vec<(&'static str, Document)> { let mut cases = vec![ ("column", document(spec(GraphKind::Column))), @@ -495,6 +572,18 @@ pub(crate) mod sample { let mut g = spec(GraphKind::Column); (g.series, g.categories) = (vec![], vec![]); cases.push(("no labels", document(g))); + let line = |f: &dyn Fn(&mut GraphSpec)| { + let mut g = spec(GraphKind::Line); + f(&mut g); + document(g) + }; + cases.extend([ + ("filled lines", line(&|g| g.filled_lines = true)), + ("filled lines 8 pt wide", line(&|g| (g.filled_lines, g.line_width) = (true, Some(8.0)))), + ("filled lines 100 pt wide", line(&|g| (g.filled_lines, g.line_width) = (true, Some(100.0)))), + ("filled lines 0.01 pt wide", line(&|g| (g.filled_lines, g.line_width) = (true, Some(0.01)))), + ("a Line Width without filled lines", line(&|g| g.line_width = Some(8.0))), + ]); cases } @@ -513,7 +602,20 @@ pub(crate) mod sample { .collect(); cases.extend([ ("no legend", with(&|g| g.legend = false)), - ("filled lines", with(&|g| (g.kind, g.filled_lines) = (GraphKind::Line, true))), + ("a Line Width past 100 pt", with(&|g| (g.kind, g.filled_lines, g.line_width) = (GraphKind::Line, true, Some(150.0)))), + ("a Line Width under 0.01 pt", with(&|g| (g.kind, g.filled_lines, g.line_width) = (GraphKind::Line, true, Some(0.001)))), + ("filled lines without connected points", with(&|g| (g.kind, g.filled_lines, g.connect_points) = (GraphKind::Line, true, false))), + ( + "filled lines with series stroked as their outline", + with(&|g| { + (g.kind, g.filled_lines) = (GraphKind::Line, true); + g.series_paints = vec![vectorcraft_doc::SeriesPaint { + stroke: Some(Paint::solid(Color::BLACK)), + stroke_width: Some(super::FILLED_LINE_OUTLINE_WIDTH), + ..Default::default() + }]; + }), + ), ("a series of another type", with(&|g| g.series_kinds = vec![None, Some(GraphKind::Line)])), ("a marker design", with(&|g| g.series_markers = vec![Some("Star".into())])), ("a column design", with(&|g| g.series_columns = vec![Some(Default::default())])), @@ -642,6 +744,29 @@ mod tests { assert_eq!(marks, ["1", "1", "1"], "{head}"); } + /// A marker or swatch is a square along the page's axes; a band, a rotated square, a rectangle + /// of other proportions and an open path are not. + #[test] + fn markers_are_squares_and_bands_are_not() { + use vectorcraft_geom::shapes; + let node = |p: vectorcraft_geom::PathData| Node::path(NodeId(1), p, Appearance::default()); + assert!(square(&node(shapes::rectangle(Rect::new(10.0, 10.0, 15.0, 15.0)))), "a 5 pt marker"); + assert!(!square(&node(shapes::rectangle(Rect::new(10.0, 10.0, 60.0, 13.0)))), "a band along a level line"); + let mut diamond = kurbo::BezPath::new(); + diamond.move_to((0.0, 5.0)); + diamond.line_to((5.0, 0.0)); + diamond.line_to((10.0, 5.0)); + diamond.line_to((5.0, 10.0)); + diamond.close_path(); + assert!(!square(&node(vectorcraft_geom::PathData::from_bezpath(&diamond))), "a rotated square"); + let mut open = kurbo::BezPath::new(); + open.move_to((0.0, 0.0)); + for p in [(5.0, 0.0), (5.0, 5.0), (0.0, 5.0), (0.0, 1.0)] { + open.line_to(p); + } + assert!(!square(&node(vectorcraft_geom::PathData::from_bezpath(&open))), "an open path"); + } + /// A table's cells go fifteen to a record, with one string at most in each. #[test] fn cells_go_fifteen_to_a_record_with_one_string_each() { diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 6f77c141ac..259be45eac 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -68,6 +68,8 @@ mod tests_images; #[cfg(test)] mod tests_native; #[cfg(test)] +mod tests_reads; +#[cfg(test)] mod tests_type1; #[cfg(test)] mod tests_type42; @@ -96,7 +98,7 @@ pub(crate) use ai::{ pub(crate) use ai::{ENVELOPE_DRAWN, ENVELOPE_TYPE_DRAWN}; pub(crate) use ate::{MAX_BYTES as MAX_TEXT_DOCUMENT, MAX_FRAMES, MAX_SEGMENTS, MAX_STORY, MAX_VALUES as MAX_TEXT_VALUES, record_version}; pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_alone_with, ai_layers_alone, ai_opened_artboard, is_loss, layered_ai, layered_ai_from}; -pub(crate) use native::{MAX_TEXT, scale_document, scale_symbols}; +pub(crate) use native::{MAX_TEXT, MAX_WRAP_WORK, scale_document, scale_symbols}; pub use text::family_style; pub(crate) use text::{document_font, postscript_face}; diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs index 3ae753b7d5..501b9f4b00 100644 --- a/crates/eps/src/import/ai/envelope.rs +++ b/crates/eps/src/import/ai/envelope.rs @@ -121,11 +121,12 @@ pub(super) fn options(o: &Obj) -> Option<(EnvelopeOptions, f64)> { /// The margins of `content` when the size the file saves for it (`AIDeformArtWidthKey`, /// `AIDeformArtHeightKey`) matches its bounds with its strokes within [`SAVED_SIZE_SLACK`] and lies -/// nearer them than its geometric bounds. None without that size, or for contents with no width or -/// no height. -fn saved_margin(o: &Obj, content: &[Arc<Node>]) -> Option<[f32; 4]> { +/// nearer them than its geometric bounds. The saved size is in art space, and `scale` takes it to the +/// contents' space (a Large Canvas copy read at its declared scale). None without that size, or for +/// contents with no width or no height. +fn saved_margin(o: &Obj, content: &[Arc<Node>], scale: f64) -> Option<[f32; 4]> { let saved = |key: &str| match o.nums(key).as_slice() { - [v] if v.is_finite() => Some(*v), + [v] if v.is_finite() => Some(*v * scale).filter(|v| v.is_finite()), _ => None, }; let (w, h) = (saved("AIDeformArtWidthKey")?, saved("AIDeformArtHeightKey")?); @@ -508,9 +509,10 @@ fn unwrapped(mut nodes: Vec<Node>) -> Vec<Arc<Node>> { } /// The live envelope of dictionary `o`, the group on `%_` lines before it (`before`) and the art -/// in its `AIDeformArtKey` block (`inner`); `None` where they don't make one. -pub(super) fn live(o: &Obj, before: Option<Node>, inner: Vec<Node>) -> Option<NodeKind> { - envelope_as(o, before, inner, false) +/// in its `AIDeformArtKey` block (`inner`); `None` where they don't make one. `scale` takes sizes in +/// art space to the space the art was read into ([`saved_margin`]). +pub(super) fn live(o: &Obj, before: Option<Node>, inner: Vec<Node>, scale: f64) -> Option<NodeKind> { + envelope_as(o, before, inner, false, scale) } /// Is the envelope of dictionary `o` a warp? @@ -521,12 +523,12 @@ fn is_warp(o: &Obj) -> bool { /// [`live`] for a warp, as a mesh envelope on the grid its editing data saves (the mesh that shapes /// it), its points and handles as saved: it draws as that grid does, without the warp's style, bend /// and distortions. `None` for an envelope that isn't a warp, or whose grid doesn't read. -fn live_on_saved_grid(o: &Obj, before: Option<Node>, inner: Vec<Node>) -> Option<NodeKind> { - envelope_as(o, before, inner, true) +fn live_on_saved_grid(o: &Obj, before: Option<Node>, inner: Vec<Node>, scale: f64) -> Option<NodeKind> { + envelope_as(o, before, inner, true, scale) } /// [`live`], or with `on_grid` [`live_on_saved_grid`]. -fn envelope_as(o: &Obj, before: Option<Node>, inner: Vec<Node>, on_grid: bool) -> Option<NodeKind> { +fn envelope_as(o: &Obj, before: Option<Node>, inner: Vec<Node>, on_grid: bool, scale: f64) -> Option<NodeKind> { let editing = switch(o, "AIDeformEditModeKey")?; let (mut options, fidelity) = options(o)?; let before = before?; @@ -546,7 +548,7 @@ fn envelope_as(o: &Obj, before: Option<Node>, inner: Vec<Node>, on_grid: bool) - return None; } if options.distort_appearance { - options.bounds_margin = saved_margin(o, &content).unwrap_or_default(); + options.bounds_margin = saved_margin(o, &content, scale).unwrap_or_default(); } let kind = match (whole(o, "AIDeformStyle")??, on_grid) { (1, false) => warp(o)?, @@ -637,14 +639,15 @@ pub(super) struct WarpedLook { /// An envelope of type read with its drawn art: its dictionary, the group on `%_` lines before it /// and the art in its `AIDeformArtKey` block, as [`live`] takes them (their text slots still -/// empty), and the id of its drawn art in the document. Type is laid out after the layers are read, -/// so it waits for that ([`WarpedType::settle_envelopes`]). +/// empty), the id of its drawn art in the document, and the scale [`live`] takes. Type is laid out +/// after the layers are read, so it waits for that ([`WarpedType::settle_envelopes`]). #[derive(Debug)] pub(crate) struct TypedEnvelope { pub(super) obj: Obj, pub(super) before: Option<Node>, pub(super) inner: Vec<Node>, pub(super) drawn: NodeId, + pub(super) scale: f64, } /// Why an envelope of type kept its drawn art. @@ -788,7 +791,7 @@ impl WarpedType { shown: &BTreeSet<NodeId>, waiting: usize, ) -> Result<(NodeId, Vec<Node>), TypeKept> { - let TypedEnvelope { obj, mut before, mut inner, drawn } = envelope; + let TypedEnvelope { obj, mut before, mut inner, drawn, scale } = envelope; let art = doc.node(drawn).cloned().ok_or(TypeKept::Read)?; // The text slots in the contents, in the order the reader put their hidden copies in. let mut slots = vec![]; @@ -813,13 +816,13 @@ impl WarpedType { } // A warp that VectorCraft's own warp doesn't draw as its drawn art may still draw as the // grid the file saves for it: then it opens as a mesh envelope on that grid. - let on_grid = if is_warp(&obj) { live_on_saved_grid(&obj, before.clone(), inner.clone()) } else { None }; + let on_grid = if is_warp(&obj) { live_on_saved_grid(&obj, before.clone(), inner.clone(), scale) } else { None }; // With Distort Appearance, a file's envelope may map its type from its glyphs grown by half // their strokes' weight or from the glyphs alone, and for type the size the file saves for // that box is often out of date (not the size of the type there now): each is checked. // After all of those, each is checked mapping from what its type paints, where that box is // another: it is measured only when such a check comes and one is left. - let kinds: Vec<NodeKind> = live(&obj, before, inner).into_iter().chain(on_grid).collect(); + let kinds: Vec<NodeKind> = live(&obj, before, inner, scale).into_iter().chain(on_grid).collect(); if kinds.is_empty() { return Err(TypeKept::Read); } diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index 3338968895..a5e222b12f 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -2,8 +2,8 @@ use super::containers::close; use super::document::TEXT_SLOT; use super::raster::{self, Limits, Shape}; use super::types::{ - FLIP, Frame, IMAGE_TOO_LARGE, Kind, LARGE_IMAGES, LINKED_PLACEHOLDERS, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, MAX_POINTS, MAX_SIDE, - NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, PLACED_CROP, PLACED_PAGE, Place, PlacedPage, PlacedTail, + FLIP, Frame, GState, IMAGE_TOO_LARGE, Kind, LARGE_IMAGES, LINKED_PLACEHOLDERS, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, MAX_POINTS, + MAX_SIDE, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, PLACED_CROP, PLACED_PAGE, Place, PlacedPage, PlacedTail, }; use super::{ Affine, AnchorKind, Appearance, AppearanceItem, Arc, BezPath, CANVAS_CENTRE, FillLayer, ImageBlob, ImageObject, Inks, Instance, LinkInfo, Node, @@ -224,12 +224,7 @@ impl<'a> Reader<'a> { items.push(AppearanceItem::Fill(FillLayer { overprint: gs.overprint_fill, ..FillLayer::new(fill_paint.unwrap_or(gs.fill.clone())) })); } if stroke { - let mut st = StrokeLayer::new(stroke_paint.unwrap_or(gs.stroke.clone()), gs.line_width()); - st.cap = gs.cap; - st.join = gs.join; - st.miter_limit = gs.miter; - st.dash = gs.dash.clone(); - st.overprint = gs.overprint_stroke; + let st = self.stroke_layer(stroke_paint.unwrap_or(gs.stroke.clone()), &gs); items.push(AppearanceItem::Stroke(st)); } let kind = NodeKind::Path { path, rule: gs.rule, live: None, clipping: clip, guide }; @@ -330,17 +325,29 @@ impl<'a> Reader<'a> { if !matches!(n.kind, NodeKind::Path { .. }) || n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(_))) { return; } - let mut st = StrokeLayer::new(gs.stroke.clone(), gs.line_width()); - st.cap = gs.cap; - st.join = gs.join; - st.miter_limit = gs.miter; - st.dash = gs.dash.clone(); - st.overprint = gs.overprint_stroke; + let st = self.stroke_layer(gs.stroke.clone(), &gs); + let Some(n) = self.frames.last_mut().and_then(|f| f.children.last_mut()) else { return }; let mut a = (*n.appearance).clone(); a.items.push(AppearanceItem::Stroke(st)); n.appearance = a.into(); } + /// A stroke of `paint` with graphics state `gs`'s weight, caps, joins, miter limit, dashes and + /// overprint, its weight and dashes at the scale the art is read at ([`Self::space_scale`]). + fn stroke_layer(&mut self, paint: Paint, gs: &GState) -> StrokeLayer { + let k = self.space_scale(); + let mut st = StrokeLayer::new(paint, gs.line_width() * k); + st.cap = gs.cap; + st.join = gs.join; + st.miter_limit = gs.miter; + st.dash = gs.dash.clone().map(|mut d| { + d.scale(k); + d + }); + st.overprint = gs.overprint_stroke; + st + } + pub(super) fn set_instance(&mut self, i: &Instance) { let mut to_doc = self.space(); // In a pattern's definition a gradient's `Xm` and `Bm` are written y down about the canvas point of art space's @@ -544,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) } @@ -577,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)) } @@ -670,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 { @@ -766,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); @@ -1024,8 +1040,9 @@ pub(super) fn preview_png(data: &[u8]) -> Option<(Vec<u8>, 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/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index 830e3a48d0..9db1470093 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -885,6 +885,7 @@ impl<'a> Reader<'a> { return; } let Some(p) = self.envelopes.pop() else { return }; + let scale = self.space_scale(); let drawn = self.frames.last().filter(|f| f.children.len() == p.siblings + 1).and_then(|f| f.children.last()); let Some(drawn) = drawn else { self.warn(crate::import::ai::envelope::drawn_note(p.typed)); @@ -894,7 +895,7 @@ impl<'a> Reader<'a> { self.wait_for_type(p); return; } - let live = (self.envelope_checks > 0).then(|| crate::import::ai::envelope::live(&p.obj, p.before, p.inner)).flatten(); + let live = (self.envelope_checks > 0).then(|| crate::import::ai::envelope::live(&p.obj, p.before, p.inner, scale)).flatten(); let Some(kind) = live else { self.warn(crate::import::ai::envelope::DRAWN); return; @@ -982,8 +983,8 @@ impl Reader<'_> { self.warn(crate::import::ai::envelope::TYPE_DRAWN); return; } - let drawn = drawn.id; - self.typed_envelopes.push(crate::import::ai::envelope::TypedEnvelope { obj: p.obj, before: p.before, inner: p.inner, drawn }); + let (drawn, scale) = (drawn.id, self.space_scale()); + self.typed_envelopes.push(crate::import::ai::envelope::TypedEnvelope { obj: p.obj, before: p.before, inner: p.inner, drawn, scale }); } } diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 312b7cc275..258d7d584b 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -934,6 +934,13 @@ impl<'a> Reader<'a> { } } + /// How many times as long [`Self::space`] makes a length in art space: a Large Canvas copy's + /// declared scale in the document, and 1 in a pattern's or a symbol's definition. + pub(super) fn space_scale(&mut self) -> f64 { + let k = self.space().determinant().abs().sqrt(); + if k.is_finite() && k > 0.0 { k } else { 1.0 } + } + /// The space an image's matrix is in → where the art being read goes: [`Self::space`], and in a /// symbol's art (outside a pattern's definition) the canvas's space turned y up about art space's /// origin there, as an instance's matrix in it is; `None` there without a template box. diff --git a/crates/eps/src/import/ai/read/graph.rs b/crates/eps/src/import/ai/read/graph.rs index 609713fe16..ea7fd2e673 100644 --- a/crates/eps/src/import/ai/read/graph.rs +++ b/crates/eps/src/import/ai/read/graph.rs @@ -14,10 +14,14 @@ use std::collections::{HashMap, HashSet}; use std::sync::Arc; use kurbo::{PathSeg, Point}; -use vectorcraft_doc::{Appearance, GraphKind, GraphSpec, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, SeriesPaint, TickLength}; +use vectorcraft_doc::{ + Appearance, DEFAULT_FILLED_LINE_WIDTH, GraphKind, GraphSpec, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, MIN_FILLED_LINE_WIDTH, SeriesPaint, + TickLength, +}; use super::types::{GRAPH_OPS, GRAPH_PLAIN, GRAPH_UNENDED, Kind}; use super::{Affine, AppearanceItem, BlendMode, Node, NodeId, NodeKind, Paint, Reader, Rect, V, obj}; +use crate::ai_graph::{band_outline, square}; /// Most cells of a graph's table, its label row and column included. const MAX_CELLS: usize = 2_600_000; @@ -293,11 +297,20 @@ impl Records { self.spec.legend = true; self.spec.mark_points = flag(marks)?; self.spec.connect_points = flag(lines)?; - // Lines drawn as shapes have a width the model doesn't keep. - (!flag(shapes)?).then_some(())?; - self.spec.filled_lines = false; + // Lines drawn as shapes (Draw Filled Lines); without connected points the flag is ignored. + self.spec.filled_lines = flag(shapes)? && self.spec.connect_points; self.spec.legend_across_top = flag(across)?; - finite(width).filter(|w| (0.0..=100.0).contains(w))?; + // `lineShapeWidth`, in points from 0 to 100. The model holds widths from 0.01 points, 3 points + // being its default; a smaller width is left out while the lines aren't filled, and keeps + // filled lines plain. + let width = finite(width).filter(|w| (0.0..=100.0).contains(w))?; + self.spec.line_width = if width == DEFAULT_FILLED_LINE_WIDTH { + None + } else if width >= MIN_FILLED_LINE_WIDTH { + Some(width) + } else { + (!self.spec.filled_lines).then_some(None)? + }; // 44: the series are measured against the left axis; 45 (right) isn't kept per series. (int(axis)? == 44).then_some(())?; if let Some([percentage, digits]) = pie { @@ -471,20 +484,36 @@ fn as_drawn(n: &Node) -> bool { /// Each series' fill and stroke, read from its group (`tags`), which holds paths only, one at /// least: the paths with a fill share it, and every path has the same stroke or none. Only a line -/// graph (`line`) has paths without a fill: its lines. `None` when they differ, or the group, its -/// own appearance or a path is drawn otherwise than [`as_drawn`]. -fn series_paints(art: &Node, tags: &HashMap<NodeId, u32>, line: bool) -> Option<Vec<SeriesPaint>> { +/// graph (`line`) has paths without a fill: its lines. With filled lines (`bands`), a filled path +/// outlined as [`band_outline`] says is a band or a mark drawn like one and gives no stroke; any +/// other filled path but a [`square`] marker or legend swatch is a band outlined otherwise. The +/// other paths give the series' stroke, and without them the series has none. A series with a band +/// and no stroke on its other paths keeps no stroke at all, so with filled lines turned off its thin +/// line is drawn in the series color at 1 pt, as for a graph drawn here. `None` when they +/// differ, a band has another outline, or the group, its own appearance or a path is drawn +/// otherwise than [`as_drawn`]. +fn series_paints(art: &Node, tags: &HashMap<NodeId, u32>, line: bool, bands: bool) -> Option<Vec<SeriesPaint>> { let mut paints = vec![SeriesPaint::default(); tags.len()]; for group in art.children().into_iter().flatten() { let Some(slot) = tags.get(&group.id).and_then(|i| paints.get_mut(usize::try_from(*i).ok()?)) else { continue }; (as_drawn(group) && *group.appearance == Appearance::default()).then_some(())?; let paths: Vec<&Arc<Node>> = group.children().into_iter().flatten().collect(); (!paths.is_empty() && paths.iter().all(|p| matches!(p.kind, NodeKind::Path { .. }))).then_some(())?; - let (mut fills, mut strokes) = (vec![], vec![]); + let (mut fills, mut strokes, mut banded) = (vec![], vec![], false); for p in &paths { as_drawn(p).then_some(())?; - fills.extend(shown(p, true).ok()?); - strokes.push(shown(p, false).ok()?); + let filled = shown(p, true).ok()?; + let outline = shown(p, false).ok()?; + if bands && filled.is_some() && band_outline(&outline) { + // A band, or a mark outlined as one: the graph keeps no stroke for a series that draws bands. + banded = true; + } else if bands && filled.is_some() && !square(p) { + // A band outlined otherwise: the graph draws it again with the thin black outline only. + return None; + } else { + strokes.push(outline); + } + fills.extend(filled); } let fill = fills.first().map(|(paint, _)| paint.clone()); fills.iter().all(|(paint, _)| Some(paint) == fill.as_ref()).then_some(())?; @@ -494,6 +523,7 @@ fn series_paints(art: &Node, tags: &HashMap<NodeId, u32>, line: bool) -> Option< slot.fill = fill; (slot.stroke, slot.stroke_width) = match stroke { Some((paint, width)) => (Some(paint), Some(width)), + None if banded => (None, None), None => (Some(Paint::None), None), }; } @@ -628,7 +658,8 @@ impl<'a> Reader<'a> { if r.x0 < placed.x0 - EDGE || r.y0 < placed.y0 - EDGE || r.x1 > placed.x1 + EDGE || r.y1 > placed.y1 + EDGE { return false; } - let Some(paints) = series_paints(art, &tags, spec.kind == GraphKind::Line) else { return false }; + let line = spec.kind == GraphKind::Line; + let Some(paints) = series_paints(art, &tags, line, line && spec.filled_lines) else { return false }; spec.series_paints = paints; spec.placed = Some(placed); spec.placed_art = art.children().and_then(|c| vectorcraft_doc::graph::graph_art_without_type(c)); @@ -646,6 +677,7 @@ impl<'a> Reader<'a> { mod tests { use super::*; use vectorcraft_color::Color; + use vectorcraft_doc::FILLED_LINE_OUTLINE_WIDTH; use vectorcraft_geom::shapes; /// A graph's art: one series group (id 2) holding one mark painted `ap`, the group changed by @@ -665,9 +697,58 @@ mod tests { let mut two = one.clone(); two.items.extend(one.items.iter().find(|i| i.is_fill()).cloned()); let tags = HashMap::from([(NodeId(2), 0)]); - let kept = series_paints(&art(one, |_| {}), &tags, false).expect("one fill"); + let kept = series_paints(&art(one, |_| {}), &tags, false, false).expect("one fill"); assert_eq!((kept[0].fill.as_ref(), kept[0].stroke.as_ref()), (Some(&red), Some(&Paint::None))); - assert!(series_paints(&art(two, |_| {}), &tags, false).is_none()); + assert!(series_paints(&art(two, |_| {}), &tags, false, false).is_none()); + } + + /// With filled lines, a band's thin black outline is not the series' stroke: its markers' stroke + /// is, and with unstroked markers or none the series keeps no stroke. A band outlined otherwise + /// than its markers has no one stroke. + #[test] + fn a_filled_line_bands_outline_is_not_its_series_stroke() { + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let series = |band: Appearance, marker: Appearance| { + let band = Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 3.0)), band)); + let marker = Arc::new(Node::path(NodeId(4), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), marker)); + Node::group(NodeId(1), vec![Arc::new(Node::group(NodeId(2), vec![band, marker]))]) + }; + let tags = HashMap::from([(NodeId(2), 0)]); + let outlined = Appearance::basic(red.clone(), Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)), FILLED_LINE_OUTLINE_WIDTH); + let marker = Appearance::basic(red.clone(), Paint::None, 0.0); + let kept = series_paints(&series(outlined.clone(), marker.clone()), &tags, true, true).expect("a band and a marker"); + assert_eq!((kept[0].fill.as_ref(), kept[0].stroke.as_ref(), kept[0].stroke_width), (Some(&red), None, None)); + let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + let stroked = Appearance::basic(red.clone(), blue.clone(), 2.0); + let kept = series_paints(&series(outlined.clone(), stroked), &tags, true, true).expect("a band and a stroked marker"); + assert_eq!((kept[0].stroke.as_ref(), kept[0].stroke_width), (Some(&blue), Some(2.0))); + let bands_only = Node::group( + NodeId(1), + vec![Arc::new(Node::group( + NodeId(2), + vec![Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 3.0)), outlined.clone()))], + ))], + ); + let kept = series_paints(&bands_only, &tags, true, true).expect("a band alone"); + assert_eq!((kept[0].stroke.as_ref(), kept[0].stroke_width), (None, None), "a band alone"); + // A band as long as it is wide is a square, and still a band: its outline is not the series' stroke. + let square_band = |marker: Appearance| { + let band = Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 3.0, 3.0)), outlined.clone())); + let marker = Arc::new(Node::path(NodeId(4), shapes::rectangle(Rect::new(10.0, 0.0, 15.0, 5.0)), marker)); + Node::group(NodeId(1), vec![Arc::new(Node::group(NodeId(2), vec![band, marker]))]) + }; + let kept = series_paints(&square_band(marker.clone()), &tags, true, true).expect("a square band and a marker"); + assert_eq!((kept[0].stroke.as_ref(), kept[0].stroke_width), (None, None), "a square band"); + assert!(series_paints(&series(outlined, marker.clone()), &tags, true, false).is_none(), "lines not filled"); + let thick = Appearance::basic(red.clone(), Paint::solid(Color::BLACK), 1.0); + assert!(series_paints(&series(thick, marker), &tags, true, true).is_none(), "a 1 pt outline"); + // A band outlined as its markers are stroked is drawn again with the thin black outline. + assert!(series_paints(&series(stroked_like(&blue), stroked_like(&blue)), &tags, true, true).is_none(), "a band outlined in blue"); + } + + /// A red mark stroked 2 pt in `paint`. + fn stroked_like(paint: &Paint) -> Appearance { + Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), paint.clone(), 2.0) } /// A series group that is hidden, see-through or in another blending mode is not drawn again so. @@ -675,8 +756,8 @@ mod tests { fn a_series_group_drawn_otherwise_has_no_series_paint() { let ap = || Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); let tags = HashMap::from([(NodeId(2), 0)]); - assert!(series_paints(&art(ap(), |g| g.visible = false), &tags, false).is_none(), "hidden"); - assert!(series_paints(&art(ap(), |g| g.opacity = 0.5), &tags, false).is_none(), "50% opaque"); - assert!(series_paints(&art(ap(), |g| g.blend = BlendMode::Multiply), &tags, false).is_none(), "Multiply"); + assert!(series_paints(&art(ap(), |g| g.visible = false), &tags, false, false).is_none(), "hidden"); + assert!(series_paints(&art(ap(), |g| g.opacity = 0.5), &tags, false, false).is_none(), "50% opaque"); + assert!(series_paints(&art(ap(), |g| g.blend = BlendMode::Multiply), &tags, false, false).is_none(), "Multiply"); } } diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index f133a9ee03..ca625a13c2 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(); @@ -11381,6 +11418,68 @@ fn a_graphs_type_and_settings_come_from_its_records() { assert!(art(&r.doc)[0].extras().graph.is_some()); } +/// A series of a line graph drawn with filled lines at `x`: a band filled with the series' color and +/// outlined in a thin black line, and a marker filled alike with no outline. +fn band_series(x: f64) -> String { + format!("0.5 0 0 0 k\n0 0 0 1 K\n0.25 w\n{}B\n1 w\n{}f\n", rect_path(x, 120.0, x + 40.0, 128.0), rect_path(x + 18.0, 122.0, x + 23.0, 127.0)) +} + +/// [`live_graph`] as a line graph with style record `style`, each series drawn by [`band_series`]. +fn band_graph(style: &str) -> String { + live_graph().replace(LIVE_STYLE, style).replace(&series_bar(110.0), &band_series(110.0)).replace(&series_bar(140.0), &band_series(140.0)) +} + +/// A line graph whose lines are drawn as shapes (`drawLinesAsShapes` 1 with `drawLines` 1) keeps +/// Draw Filled Lines and its Line Width (`lineShapeWidth`, in points): 3 points is the graph's +/// default. Its series keep their bands' fill, and the bands' thin black outline is not taken as the +/// series' stroke. With `drawLines` 0 the flag is ignored, and the width is kept for later. +#[test] +fn a_line_graph_drawn_with_filled_lines_keeps_them_and_their_width() { + let live = |text: String| { + let r = read(stream7(&layer7("Graph", &text)).as_bytes()).unwrap(); + assert!(r.warnings.is_empty(), "{text}: {:?}", r.warnings); + let a = art(&r.doc); + let g = a[0].extras().graph.clone().unwrap_or_else(|| panic!("{text}: a live graph")); + (g, live_graphs(&r.doc).1) + }; + let (g, tagged) = live(band_graph("%_7 0 0 14 1 1 1 0 8 44 Gy\n")); + assert_eq!((g.kind, g.filled_lines, g.line_width, tagged), (GraphKind::Line, true, Some(8.0), 2)); + let fill = Some(Paint::solid(Color::cmyk(0.5, 0.0, 0.0, 0.0))); + assert!(g.series_paints.iter().all(|p| p.fill == fill && p.stroke.is_none() && p.stroke_width.is_none()), "{:?}", g.series_paints); + assert_eq!(live(band_graph("%_7 0 0 14 1 1 1 0 3 44 Gy\n")).0.line_width, None, "3 pt"); + assert_eq!(live(band_graph("%_7 0 0 14 1 1 1 0 6 44 Gy\n")).0.line_width, Some(6.0), "6 pt"); + assert_eq!(live(band_graph("%_7 0 0 14 1 1 1 0 100 44 Gy\n")).0.line_width, Some(100.0), "100 pt"); + assert_eq!(live(band_graph("%_7 0 0 14 1 1 1 0 0.01 44 Gy\n")).0.line_width, Some(0.01), "0.01 pt"); + // Without filled lines, the series are drawn as the graph's columns are. + let (g, _) = live(live_graph().replace(LIVE_STYLE, "%_7 0 0 14 1 0 1 0 8 44 Gy\n")); + assert_eq!((g.connect_points, g.filled_lines, g.line_width), (false, false, Some(8.0)), "points not connected"); + let (g, _) = live(live_graph().replace(LIVE_STYLE, "%_7 0 0 14 1 1 0 0 0 44 Gy\n")); + assert_eq!((g.filled_lines, g.line_width), (false, None), "lines not filled, 0 pt"); +} + +/// A graph with filled lines whose Line Width the model doesn't hold (0, under 0.01 points, or out of +/// the records' 0 to 100), or with a lines-as-shapes value other than 0 and 1, keeps its drawn art +/// as plain objects, with one note. +#[test] +fn filled_lines_of_a_width_the_model_cant_hold_stay_plain_art() { + for style in [ + "%_7 0 0 14 1 1 1 0 0 44 Gy\n", + "%_7 0 0 14 1 1 1 0 0.001 44 Gy\n", + "%_7 0 0 14 1 1 1 0 101 44 Gy\n", + "%_7 0 0 14 1 1 1 0 -2 44 Gy\n", + "%_7 0 0 14 1 1 1 0 1e999 44 Gy\n", + "%_7 0 0 14 1 1 0 0 101 44 Gy\n", + "%_7 0 0 14 1 1 2 0 8 44 Gy\n", + ] { + let r = read(stream7(&layer7("Graph", &band_graph(style))).as_bytes()).unwrap_or_else(|e| panic!("{style}: {e}")); + assert_eq!(r.warnings, [GRAPH_PLAIN], "{style}"); + assert_eq!(live_graphs(&r.doc), (vec![], 0), "{style}"); + let mut kept = false; + r.doc.walk(|n| kept |= n.children().is_some_and(|c| c.len() == 3)); + assert!(kept, "{style}: the drawn art is kept"); + } +} + /// A graph keeps its drawn art and stays plain, with one note, when a record has a shape or value /// appendix A doesn't give, sets what the model doesn't keep, or the table, the series tags or the /// art don't fit the graph. @@ -11396,7 +11495,7 @@ fn graphs_the_model_cant_keep_stay_plain_art() { ("type 11", live_graph().replace("%_5 0 0 14", "%_11 0 0 14")), ("legends in wedges", live_graph().replace("%_5 0 0 14", "%_5 0 0 15")), ("the right axis", live_graph().replace("6 44 Gy", "6 45 Gy")), - ("lines as shapes", live_graph().replace("%_5 0 0 14 0 1 0", "%_5 0 0 14 0 1 1")), + ("lines as shapes 0 pt wide", live_graph().replace("%_5 0 0 14 0 1 0 0 6", "%_5 0 0 14 0 1 1 0 0")), ("both axes alike", live_graph().replace(LIVE_DIALOG, "%_10 2 0 1 90 80 0 Gd\n")), ("a subscription", live_graph().replace(LIVE_DIALOG, &format!("{LIVE_DIALOG}%_0 0 1 1 1 Gj\n"))), ("a customization", live_graph().replace("GC\n", "GC\n%_2 Gt\n%_(Bars) GD\n%_GT\n")), 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<u8>, 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<u8>, usize)> { +fn fax(raw: &[u8], settings: CcittParams) -> Res<(Vec<u8>, 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<u8>, - /// 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<Predictor>, /// `CCITTFaxDecode`'s parameters. - pub(super) fax: Option<DecodeSettings>, + pub(super) fax: Option<CcittParams>, } /// 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<DecodeSettings> { +pub(super) fn fax_settings(d: Option<&DictRef>) -> Res<CcittParams> { 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<DecodeSettings> { 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..c4fc09e0b0 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -31,6 +31,7 @@ pub(super) enum Source { } impl Interp<'_> { + #[allow(clippy::cognitive_complexity)] // One arm for each file operator, most of them a few lines. pub fn data_op(&mut self, op: Op) -> Res { use Op::*; match op { @@ -50,23 +51,7 @@ impl Interp<'_> { ReadLine => { let s = self.pop_str()?; let Obj::File { stream: f, .. } = self.pop()? else { return ps_err("typecheck", "") }; - let n = s.len(); - let mut line = vec![]; - let mut ended = false; - while line.len() < n { - match self.read(&f, 1)?.first() { - Some(b'\n') | None => { - ended = true; - break; - } - Some(b'\r') => { - self.skip_lf(&f); - ended = true; - break; - } - Some(b) => line.push(*b), - } - } + let (line, ended) = self.read_line(&f, s.len())?; self.fill(s, &line)?; self.push(Obj::Bool(ended))?; } @@ -219,38 +204,71 @@ impl Interp<'_> { }) } - /// After `readline` consumes CR, consume only an immediately following LF. PostScript - /// treats CR/LF as one line ending (PLRM §3.8); raw reads must keep every other byte. - /// The preceding `read` has already materialized any pending filter. - fn skip_lf(&mut self, f: &Rc<RefCell<Stream>>) { - match &mut *f.borrow_mut() { + /// Run `scan` over the bytes left in file `f`, in one slice, and consume as many of them as + /// it says it used. A file still pending after `materialize` has no bytes left. + fn scan<T>(&mut self, f: &Rc<RefCell<Stream>>, scan: impl FnOnce(&[u8]) -> (T, usize)) -> Res<T> { + self.materialize(f)?; + Ok(match &mut *f.borrow_mut() { Stream::Current => { - if self.lex.rest().first() == Some(&b'\n') { - self.lex.advance(1); - } + let (found, used) = scan(self.lex.data()); + self.lex.advance(used); + found } Stream::Buf { data, pos, .. } => { - if data.get(*pos) == Some(&b'\n') { - *pos += 1; - } + let start = (*pos).min(data.len()); + let (found, used) = scan(data.get(start..).unwrap_or_default()); + *pos = start.saturating_add(used).min(data.len()); + found } - Stream::Pending { .. } => {} - } + Stream::Pending { .. } => scan(&[]).0, + }) } - /// Up to `n` bytes read as hexadecimal digits from `f` (other characters skipped). - pub(in super::super) fn read_hex(&mut self, f: &Rc<RefCell<Stream>>, n: usize) -> Res<Vec<u8>> { - let mut out = Vec::with_capacity(n); - let mut high: Option<u8> = None; - while out.len() < n { - let Some(&b) = self.read(f, 1)?.first() else { break }; - let Some(v) = char::from(b).to_digit(16) else { continue }; - match high.take() { - Some(h) => out.push(h << 4 | v as u8), - None => high = Some(v as u8), - } + /// `readline` from `f` into a string of `n` bytes: the line, and whether it ended at a line + /// ending or at the end of the data. The line ending is consumed and left out of the line. + /// CR LF is one line ending (PLRM §3.8), and a lone CR leaves the byte after it unread. A + /// line that fills the string leaves the bytes after it unread, a line ending included. + pub(in super::super) fn read_line(&mut self, f: &Rc<RefCell<Stream>>, n: usize) -> Res<(Vec<u8>, bool)> { + if n == 0 { + return Ok((vec![], false)); } - Ok(out) + self.scan(f, |data| { + let room = data.get(..n).unwrap_or(data); + match room.iter().position(|b| matches!(b, b'\n' | b'\r')) { + Some(i) => { + let crlf = room.get(i) == Some(&b'\r') && data.get(i + 1) == Some(&b'\n'); + ((room.get(..i).unwrap_or_default().to_vec(), true), i + 1 + usize::from(crlf)) + } + None if room.len() == n => ((room.to_vec(), false), n), + None => ((room.to_vec(), true), room.len()), + } + }) + } + + /// Up to `n` bytes read as hexadecimal digits from `f` (other characters skipped). The read + /// stops at the digit that completes the `n`th byte and leaves what follows unread. A lone + /// digit at the end of the data gives no byte. + pub(in super::super) fn read_hex(&mut self, f: &Rc<RefCell<Stream>>, n: usize) -> Res<Vec<u8>> { + if n == 0 { + return Ok(vec![]); + } + self.scan(f, |data| { + let mut out = Vec::with_capacity(n.min(data.len() / 2)); + let mut high: Option<u8> = None; + let mut used = 0; + for &b in data { + if out.len() == n { + break; + } + used += 1; + let Some(v) = char::from(b).to_digit(16) else { continue }; + match high.take() { + Some(h) => out.push(h << 4 | v as u8), + None => high = Some(v as u8), + } + } + (out, used) + }) } /// Skip the whitespace and the `>` that end hexadecimal data in `f`, if a `>` is next: the @@ -893,12 +911,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 +940,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 5acaba34a4..ac57122bd4 100644 --- a/crates/eps/src/import/native.rs +++ b/crates/eps/src/import/native.rs @@ -49,7 +49,7 @@ mod slots; #[cfg(test)] use build::{Frame, MADE, prune_unseen}; -pub(crate) use build::{scale_document, scale_symbols}; +pub(crate) use build::{MAX_WRAP_WORK, scale_document, scale_symbols}; #[cfg(test)] use compare::{ MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, PageView, Shares, compare, compared, comparison_render, comparison_samples, differ, differ_in_colour, @@ -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/native/build.rs b/crates/eps/src/import/native/build.rs index 09368870e8..bb970debe3 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -773,7 +773,7 @@ fn settle_warped_type( } /// Most anchors copied into the wrap shapes of a file's area type ([`vectorcraft_doc::text::wrap_work`]). -const MAX_WRAP_WORK: usize = 2_000_000; +pub(crate) const MAX_WRAP_WORK: usize = 2_000_000; /// [`relayout_wrapped`], or an error when the wrap shapes would hold more than [`MAX_WRAP_WORK`] /// anchors. 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<Preview> { const MAX_PREVIEW_PIXELS: u64 = 1 << 26; fn tiff_rgba(tiff: &[u8]) -> Option<image::RgbaImage> { - 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<Document> { 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] <f0> 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<T>(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..ac3b5a369a 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -106,6 +106,23 @@ fn image_data_comes_from_the_file_being_run() { ); } +/// An image whose procedure reads its rows with `readhexstring` comes out with the same pixels as +/// the same samples given as one hexadecimal string, with the digits broken by CR LF, LF, tabs, +/// spaces and characters that are not digits, read from the program's own file and from a file +/// being run. +#[test] +fn hex_rows_read_by_a_procedure_match_a_hexadecimal_string() { + let rgb: Vec<u8> = (0..36u32).map(|i| (i * 37 % 256) as u8).collect(); + let digits = hex(&rgb); + let breaks = ["\r\n", "\n", "\t", " z", "%"]; + let broken: String = digits.as_bytes().chunks(5).zip(breaks.iter().cycle()).map(|(d, b)| format!("{}{b}", String::from_utf8_lossy(d))).collect(); + let want = pixels(&read(&format!("10 10 scale 4 3 8 [4 0 0 -3 0 3] <{digits}> false 3 colorimage")), 4, 3); + assert_eq!(want, rgb.chunks(3).map(|p| [p[0], p[1], p[2], 255]).collect::<Vec<_>>()); + let image = "10 10 scale 4 3 8 [4 0 0 -3 0 3] {currentfile 12 string readhexstring pop} false 3 colorimage"; + assert_eq!(pixels(&read(&format!("{image}\r\n{broken}\n")), 4, 3), want); + assert_eq!(pixels(&read(&format!("currentfile 0 (endstream) /SubFileDecode filter cvx exec\n{image}\n{broken}\nendstream\n")), 4, 3), want); +} + /// A filter waits until it is first read, then reads the file it was made over, wherever the /// program runs by then: one over the program's own file, read in a file being run, and one over /// a file being run, read in a file that one runs. @@ -181,7 +198,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 +376,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 +588,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<Vec<u8>> = (0..4).map(|y| (0..5).map(|x| gray.get_pixel(x, y)[0]).collect()).collect(); diff --git a/crates/eps/src/import/tests_reads.rs b/crates/eps/src/import/tests_reads.rs new file mode 100644 index 0000000000..3220edd028 --- /dev/null +++ b/crates/eps/src/import/tests_reads.rs @@ -0,0 +1,359 @@ +//! `readhexstring` and `readline` (PLRM 3rd ed., §8.2) read the data left in a file in one pass. +//! The tests run the one-pass readers next to reference readers that take one byte per call, on the +//! same data in the same interpreter state: the program's own file after the whitespace that ends +//! the last token, a decoded buffer read from its start or part way in, and a filter decoded when it +//! is first read. The bytes, the result or error, and every byte left unread must agree. + +use std::cell::RefCell; +use std::fmt::Debug; +use std::rc::Rc; +use std::time::{Duration, Instant}; + +use vectorcraft_doc::Document; +use vectorcraft_geom::{Affine, Rect}; + +use super::data::Stream; +use super::graphics::{GState, Out}; +use super::interp::Interp; +use super::obj::{Obj, Res}; + +type File = Rc<RefCell<Stream>>; + +/// Bytes as hexadecimal digits. +fn hex(data: &[u8]) -> String { + data.iter().map(|b| format!("{b:02x}")).collect() +} + +/// An interpreter that has run `src` up to its `quit`, and the file object the program left on the +/// operand stack. What follows `quit` in `src` is still unread. +fn file_after(src: &[u8]) -> (Interp<'_>, File) { + let mut doc = Document::new(100.0, 100.0); + doc.layers.clear(); + let page = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 100.0]); + let mut it = Interp::new(src, GState::default(), Out::new(doc, page, Rect::new(0.0, 0.0, 100.0, 100.0))); + assert_eq!(it.run(), Ok(()), "{}", String::from_utf8_lossy(src)); + let Ok(Obj::File { stream, .. }) = it.pop() else { panic!("no file on the stack: {}", String::from_utf8_lossy(src)) }; + (it, stream) +} + +/// The reference `readline`: one byte per call, a CR followed by an LF ending the line once. +fn line_by_bytes(it: &mut Interp, f: &File, n: usize) -> Res<(Vec<u8>, bool)> { + let mut line = vec![]; + let mut ended = false; + while line.len() < n { + match it.read(f, 1)?.first() { + Some(b'\n') | None => { + ended = true; + break; + } + Some(b'\r') => { + match &mut *f.borrow_mut() { + Stream::Current => { + if it.lex.rest().first() == Some(&b'\n') { + it.lex.advance(1); + } + } + Stream::Buf { data, pos, .. } => { + if data.get(*pos) == Some(&b'\n') { + *pos += 1; + } + } + Stream::Pending { .. } => {} + } + ended = true; + break; + } + Some(b) => line.push(*b), + } + } + Ok((line, ended)) +} + +/// The reference `readhexstring`: one byte per call, characters that are not hexadecimal digits +/// skipped. +fn hex_by_bytes(it: &mut Interp, f: &File, n: usize) -> Res<Vec<u8>> { + let mut out = Vec::with_capacity(n); + let mut high: Option<u8> = None; + while out.len() < n { + let Some(&b) = it.read(f, 1)?.first() else { break }; + let Some(v) = char::from(b).to_digit(16) else { continue }; + match high.take() { + Some(h) => out.push(h << 4 | v as u8), + None => high = Some(v as u8), + } + } + Ok(out) +} + +fn line_one_pass(it: &mut Interp, f: &File, n: usize) -> Res<(Vec<u8>, bool)> { + it.read_line(f, n) +} + +fn hex_one_pass(it: &mut Interp, f: &File, n: usize) -> Res<Vec<u8>> { + it.read_hex(f, n) +} + +/// Hexadecimal data as CID `StartData` reads it: the digits, then a closing `>` if one is next. +fn hex_and_end_one_pass(it: &mut Interp, f: &File, n: usize) -> Res<Vec<u8>> { + let d = it.read_hex(f, n)?; + it.skip_hex_end(f)?; + Ok(d) +} + +fn hex_and_end_by_bytes(it: &mut Interp, f: &File, n: usize) -> Res<Vec<u8>> { + let d = hex_by_bytes(it, f, n)?; + it.skip_hex_end(f)?; + Ok(d) +} + +/// How the program reaches the data. +#[derive(Clone, Copy, Debug)] +enum Form { + /// `currentfile`, with this whitespace after the token before the data. + Current(&'static [u8]), + /// A buffer decoded at once, with this many bytes of it read before the data. + Buf(usize), + /// An `ASCIIHexDecode` filter over `currentfile`, decoded when it is first read, with this + /// whitespace after the token before the digits. + Pending(&'static [u8]), +} + +const FORMS: [Form; 13] = [ + Form::Current(b" "), + Form::Current(b"\n"), + Form::Current(b"\r"), + Form::Current(b"\r\n"), + Form::Current(b"\r\r\n"), + Form::Current(b"\n\r"), + Form::Current(b"\t\t"), + Form::Buf(0), + Form::Buf(2), + Form::Buf(3), + Form::Pending(b"\n"), + Form::Pending(b"\r\n"), + Form::Pending(b" "), +]; + +/// A program that leaves a file over `data` on the operand stack, in form `form`. +fn program(form: Form, data: &[u8]) -> Vec<u8> { + match form { + Form::Current(lead) => [b"currentfile quit".as_slice(), lead, data].concat(), + Form::Buf(0) => format!("<{}> /ReusableStreamDecode filter quit", hex(data)).into_bytes(), + Form::Buf(skip) => { + let before = b"\r\n\r".get(..skip).unwrap_or(b"\r\n\r".as_slice()); + format!("<{}{}> /ReusableStreamDecode filter dup {skip} string readstring pop pop quit", hex(before), hex(data)).into_bytes() + } + Form::Pending(lead) => [b"currentfile /ASCIIHexDecode filter quit".as_slice(), lead, hex(data).as_bytes(), b"> tail"].concat(), + } +} + +type Reader<T> = fn(&mut Interp, &File, usize) -> Res<T>; + +/// Read `data` in `form` with `one_pass` and with `by_bytes` in two interpreters in the same state, +/// and check that they agree on the result and on everything left to read. +fn agree<T: PartialEq + Debug>(form: Form, data: &[u8], n: usize, one_pass: Reader<T>, by_bytes: Reader<T>) { + let src = program(form, data); + let (mut a, fa) = file_after(&src); + let (mut b, fb) = file_after(&src); + let at = || format!("{form:?}, {:?}, n = {n}", String::from_utf8_lossy(data)); + assert_eq!(one_pass(&mut a, &fa, n), by_bytes(&mut b, &fb, n), "result: {}", at()); + assert_eq!(a.lex.rest(), b.lex.rest(), "program left unread: {}", at()); + assert_eq!(a.read(&fa, usize::MAX), b.read(&fb, usize::MAX), "file left unread: {}", at()); + assert_eq!(a.lex.rest(), b.lex.rest(), "program left after the file: {}", at()); + a.release(); + b.release(); +} + +/// A fixed sequence of pseudo-random numbers (xorshift), so a failure repeats. +struct Rng(u64); + +impl Rng { + fn below(&mut self, n: usize) -> usize { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + (self.0 % n.max(1) as u64) as usize + } +} + +/// `chosen`, then `count` strings of up to 24 bytes from `alphabet`. +fn samples(chosen: &[&[u8]], alphabet: &[u8], count: usize, rng: &mut Rng) -> Vec<Vec<u8>> { + let random = (0..count).map(|_| { + let len = rng.below(25); + (0..len).filter_map(|_| alphabet.get(rng.below(alphabet.len())).copied()).collect() + }); + chosen.iter().map(|s| s.to_vec()).chain(random).collect() +} + +/// String lengths to read `data` with: none, one, past its end, exactly its length and one more, +/// and one at random. +fn lengths(data: &[u8], rng: &mut Rng) -> [usize; 6] { + [0, 1, 3, data.len(), data.len() + 1, rng.below(data.len() + 3)] +} + +#[test] +fn readline_reads_in_one_pass_as_byte_by_byte() { + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + let chosen: [&[u8]; 16] = [ + b"", + b"\n", + b"\r", + b"\r\n", + b"\n\r", + b"\r\r\n", + b"abc", + b"abc\n", + b"abc\r", + b"abc\rX", + b"abc\r\nX", + b"abc\n\nX", + b"abcdefgh\r\nX", + b"abcdefgh\nX", + b"a\0b\xff\rX", + b"abc\r\n", + ]; + for data in samples(&chosen, b"ab\r\n\r\n x\0\xff", 40, &mut rng) { + for form in FORMS { + for n in lengths(&data, &mut rng) { + agree(form, &data, n, line_one_pass, line_by_bytes); + } + } + } +} + +#[test] +fn readhexstring_reads_in_one_pass_as_byte_by_byte() { + let mut rng = Rng(0x2545_f491_4f6c_dd1d); + let chosen: [&[u8]; 14] = [ + b"", + b"0", + b"a", + b"0a", + b"0a1", + b"0 a\r\n1b>X", + b"zz0g1", + b"ff\r\n00\nAA", + b"0a1b2c3d", + b"0a1b\r\n2c>", + b"\r\n0a", + b"a b c d e", + b"0a>", + b"0a \r\n >X", + ]; + for data in samples(&chosen, b"0123456789abcdefABCDEFg \r\n\t>z%", 40, &mut rng) { + for form in FORMS { + for n in lengths(&data, &mut rng) { + agree(form, &data, n, hex_one_pass, hex_by_bytes); + agree(form, &data, n, hex_and_end_one_pass, hex_and_end_by_bytes); + } + } + } +} + +/// `readline` of `data` into `n` bytes, after `currentfile` and a CR LF, gives `line` and `ended` +/// and leaves `left` unread. +fn line_case(data: &[u8], n: usize, line: &[u8], ended: bool, left: &[u8]) { + let src = program(Form::Current(b"\r\n"), data); + let (mut it, f) = file_after(&src); + assert_eq!(it.read_line(&f, n), Ok((line.to_vec(), ended)), "{:?}", String::from_utf8_lossy(data)); + assert_eq!(it.read(&f, usize::MAX), Ok(left.to_vec()), "{:?}", String::from_utf8_lossy(data)); + it.release(); +} + +/// `readhexstring` of `data` into `n` bytes, after `currentfile` and a CR LF, gives `bytes` and +/// leaves `left` unread in the program. +fn hex_case(data: &[u8], n: usize, bytes: &[u8], left: &[u8]) { + let src = program(Form::Current(b"\r\n"), data); + let (mut it, f) = file_after(&src); + assert_eq!(it.read_hex(&f, n), Ok(bytes.to_vec()), "{:?}", String::from_utf8_lossy(data)); + assert_eq!(it.lex.rest(), left, "{:?}", String::from_utf8_lossy(data)); + it.release(); +} + +/// The results the one-pass readers give at the edges of the data, stated directly. +#[test] +fn one_pass_reads_stop_where_their_data_ends() { + // A CR LF ends one line; a lone CR leaves the next byte unread. + line_case(b"ab\r\nX", 8, b"ab", true, b"X"); + line_case(b"ab\rX", 8, b"ab", true, b"X"); + line_case(b"ab\nX", 8, b"ab", true, b"X"); + // A line that fills the string leaves its line ending unread. + line_case(b"abcd\nX", 4, b"abcd", false, b"\nX"); + line_case(b"abc\r\nX", 3, b"abc", false, b"\r\nX"); + // The end of the data ends the line. + line_case(b"ab", 8, b"ab", true, b""); + line_case(b"", 8, b"", true, b""); + // The read stops on the digit that completes the last byte. + hex_case(b"0a\r\n1b>X", 2, &[0x0a, 0x1b], b">X"); + // Characters that are not digits are skipped. + hex_case(b"z0 g\ta%", 1, &[0x0a], b"%"); + // A lone digit at the end of the data gives no byte. + hex_case(b"0a1", 2, &[0x0a], b""); + hex_case(b"\r\n", 2, &[], b""); + // No byte to read takes nothing, not even the whitespace after the token. + hex_case(b"0a", 0, &[], b"\r\n0a"); +} + +/// The median of `runs`. +fn median(runs: &[Duration]) -> Duration { + let mut sorted = runs.to_vec(); + sorted.sort(); + sorted.get(sorted.len() / 2).copied().unwrap_or_default() +} + +/// Read all of `src`'s data with `reader` in strings of `n` bytes, `calls` times, and how long it +/// took. The interpreter is made before the clock starts. +fn timed<T>(src: &[u8], reader: Reader<T>, n: usize, calls: usize) -> (Vec<T>, Duration) { + let (mut it, f) = file_after(src); + let start = Instant::now(); + let got: Vec<T> = (0..calls).map(|_| reader(&mut it, &f, n).unwrap_or_else(|e| panic!("{e:?}"))).collect(); + let took = start.elapsed(); + it.release(); + (got, took) +} + +/// Time both readers on `src` in 7 runs, alternating which goes first, check that they read the +/// same, and print every run and the medians. +fn compare<T: PartialEq>(what: &str, src: &[u8], one_pass: Reader<T>, by_bytes: Reader<T>, n: usize, calls: usize) { + let (mut old, mut new) = (vec![], vec![]); + for run in 0..7 { + let order: [bool; 2] = if run % 2 == 0 { [false, true] } else { [true, false] }; + let mut got = vec![]; + for one in order { + let (read, took) = timed(src, if one { one_pass } else { by_bytes }, n, calls); + if one { + new.push(took) + } else { + old.push(took) + } + got.push(read); + } + assert!(got.first() == got.get(1), "{what}: the readers differ"); + } + let ms = |d: &Duration| format!("{:.1}", d.as_secs_f64() * 1000.0); + println!("{what}: {} bytes of data, {calls} calls of {n} bytes", src.len()); + println!(" byte by byte, ms: {}", old.iter().map(ms).collect::<Vec<_>>().join(" ")); + println!(" one pass, ms: {}", new.iter().map(ms).collect::<Vec<_>>().join(" ")); + let (o, w) = (median(&old), median(&new)); + println!(" median: byte by byte {} ms, one pass {} ms, {:.1}x", ms(&o), ms(&w), o.as_secs_f64() / w.as_secs_f64().max(1e-9)); +} + +/// Times the one-pass readers against the byte-at-a-time reference readers on the same data in one +/// process: the hexadecimal samples of a 1000 × 1000 RGB image in lines of 64 digits, read a row +/// of 3,000 bytes at a time, and 200,000 lines of 40 bytes read by `readline` into an 80-byte +/// string. Run it in release: +/// `cargo test --release -p vectorcraft-eps --lib tests_reads::one_pass_reads_timed -- --ignored --nocapture`. +#[test] +#[ignore = "manual timing probe; wall-clock performance depends on machine load"] +fn one_pass_reads_timed() { + let rgb: Vec<u8> = (0..3_000_000u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 24) as u8).collect(); + let digits = hex(&rgb); + let mut data = Vec::with_capacity(digits.len() + digits.len() / 64 + 1); + for line in digits.as_bytes().chunks(64) { + data.extend_from_slice(line); + data.push(b'\n'); + } + compare("readhexstring", &program(Form::Current(b"\n"), &data), hex_one_pass, hex_by_bytes, 3_000, 1_000); + let lines: Vec<u8> = (0..200_000).flat_map(|i| format!("{:<39}\n", format!("line {i}")).into_bytes()).collect(); + compare("readline", &program(Form::Current(b"\n"), &lines), line_one_pass, line_by_bytes, 80, 200_000); +} 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<u8>, 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/lib.rs b/crates/eps/src/lib.rs index e36422b759..39737dae3a 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -232,8 +232,8 @@ pub fn export(doc: &Document, opts: &EpsOptions, preview: Option<&Raster>, thumb } // Type in the document's composite fonts is drawn in them, whether or not an app has the document open. let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts); - let baked = - vectorcraft_effects::bake_document_placing_symbols(doc, true, vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true }); + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, true, layers); let doc = baked.as_ref().unwrap_or(doc); let page = scene::Scene::new(doc, opts).run(); let mut setting_notes = vec![]; 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<image::RgbaImage> { - 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<Vec<u8>, Str /// `img` as a PNG. pub(crate) fn png(img: &Raster) -> Result<Vec<u8>, 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/format/Cargo.toml b/crates/format/Cargo.toml index bd004d2d1e..e020dda9c3 100644 --- a/crates/format/Cargo.toml +++ b/crates/format/Cargo.toml @@ -12,6 +12,7 @@ workspace = true vectorcraft-doc = { workspace = true } vectorcraft-brush = { workspace = true } craft-vectorcraft-format = { workspace = true } +craft-gzip = { workspace = true } serde ={ workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 9add0798c7..a8c7358aa7 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -57,12 +57,14 @@ use vectorcraft_doc::{Document, ImageBlob}; #[cfg(not(target_arch = "wasm32"))] pub use atomic::{read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with}; +use craft_gzip::Gz; pub use craft_vectorcraft_format::base64::{decode as base64_decode, decoded_len as base64_decoded_len, encode as base64_encode}; +use craft_vectorcraft_format::stream::{FileHeader, Indent, KeyScan, write_file_json}; pub use craft_vectorcraft_format::{ BLOB_MAGIC, COMPRESSED_SINCE, EXTENSION, ICC_MIME, INLINE_MAX, LEGACY_EXTENSION, MIN_VERSION, PREVIEW_MAX, VERSION, is_compressed, json_part, sniff, }; -use stream::{Gz, Indent, KeyScan, Out}; +use stream::Out; /// Most bytes the JSON of a compressed file may unpack to (a guard against decompression bombs, /// as are [`MAX_BLOB`] and [`MAX_BLOBS`]). A compressed save refuses a document past any of them, @@ -367,35 +369,44 @@ pub fn save_to(doc: &Document, o: &SaveOptions, w: impl Write) -> Result<(), For let profiles: BTreeMap<&str, Image> = o.profiles.iter().map(|(name, icc)| (name.as_str(), out_blobs.image(ICC_MIME, icc, false))).collect(); let pdf = o.pdf.as_deref().map(|p| out_blobs.image("application/pdf", p, false)); let mut out = if o.compress { Out::Gz(Box::new(Gz::new(w).map_err(encode_err)?)) } else { Out::Plain(w) }; - let mut env = Envelope { pretty, first: true }; - // Older apps only know the name from before the rename. - env.field(&mut out, "format", &if o.version < 3 { LEGACY_EXTENSION } else { EXTENSION })?; - env.field(&mut out, "version", &o.version)?; - env.field(&mut out, "generator", &format!("VectorCraft {}", env!("CARGO_PKG_VERSION")))?; - if let Some(compatible) = o.pdf_compatible { - env.field(&mut out, "pdfCompatible", &compatible)?; - } - if let Some(png) = &o.preview { - env.field(&mut out, "preview", &Image::inline("image/png", png))?; - } - if !profiles.is_empty() { - env.field(&mut out, "profiles", &profiles)?; - } - if let Some(pdf) = &pdf { - env.field(&mut out, "pdf", pdf)?; - } - env.key(&mut out, "document")?; - let mut scan = KeyScan::new(Indent { inner: &mut out, on: pretty }); - // Without blobs no key matters. - scan.active = images.is_none() && !blobs.is_empty(); - let mut buffered = std::io::BufWriter::with_capacity(JSON_CHUNK, &mut scan); - write_body(&mut buffered, v1.as_ref(), &d, pretty)?; - buffered.flush().map_err(encode_err)?; - drop(buffered); - let used = std::mem::take(&mut scan.keys); - let images = images.unwrap_or_else(|| entries.images(&used, &mut out_blobs)); - env.field(&mut out, "images", &images)?; - env.finish(&mut out)?; + let generator = format!("VectorCraft {}", env!("CARGO_PKG_VERSION")); + let preview = o.preview.as_deref().map(|png| Image::inline("image/png", png)); + let header = FileHeader { + version: o.version, + generator: &generator, + pdf_compatible: o.pdf_compatible, + preview: preview.as_ref(), + profiles: &profiles, + pdf: pdf.as_ref(), + }; + write_file_json(&mut out, &header, pretty, |document| { + let mut scan = KeyScan::new(document); + // Without blobs no key matters. + scan.active = images.is_none() && !blobs.is_empty(); + let mut buffered = std::io::BufWriter::with_capacity(JSON_CHUNK, &mut scan); + match v1.as_ref() { + Some(v) => { + if pretty { + serde_json::to_writer_pretty(&mut buffered, v) + } else { + serde_json::to_writer(&mut buffered, v) + } + } + None => { + if pretty { + serde_json::to_writer_pretty(&mut buffered, &d) + } else { + serde_json::to_writer(&mut buffered, &d) + } + } + } + .map_err(std::io::Error::other)?; + buffered.flush()?; + drop(buffered); + let used = std::mem::take(&mut scan.keys); + Ok(images.unwrap_or_else(|| entries.images(&used, &mut out_blobs))) + }) + .map_err(encode_err)?; if o.compress { let json = out.written().unwrap_or(0); let tail: Vec<u64> = out_blobs.parts().iter().map(|p| p.bytes.len() as u64).collect(); @@ -409,13 +420,7 @@ pub fn save_to(doc: &Document, o: &SaveOptions, w: impl Write) -> Result<(), For return Err(FormatError::TooBigToCompress(format!("{} MB of images, at most {} MB", out_blobs.len() >> 20, MAX_BLOBS >> 20))); } } - if !out_blobs.is_empty() { - out.write_all(BLOB_MAGIC).map_err(encode_err)?; - for part in out_blobs.parts() { - out.packed(is_packed(&part.mime)).map_err(encode_err)?; - out.write_all(part.bytes).map_err(encode_err)?; - } - } + out_blobs.write_to_with(&mut out, |out, mime| out.packed(is_packed(mime))).map_err(encode_err)?; out.finish().map_err(encode_err) } @@ -450,10 +455,6 @@ fn encode_err(e: impl std::fmt::Display) -> FormatError { FormatError::Encode(e.to_string()) } -fn to_json(v: &impl Serialize, pretty: bool) -> Result<Vec<u8>, FormatError> { - if pretty { serde_json::to_vec_pretty(v) } else { serde_json::to_vec(v) }.map_err(encode_err) -} - /// The document's JSON: its version 1 form `v1`, else `d` (generic, not `dyn Write`: serde_json /// writes token by token). fn write_body(w: impl Write, v1: Option<&serde_json::Value>, d: &Document, pretty: bool) -> Result<(), FormatError> { @@ -467,33 +468,6 @@ fn write_json(w: impl Write, v: &impl Serialize, pretty: bool) -> Result<(), For if pretty { serde_json::to_writer_pretty(w, v) } else { serde_json::to_writer(w, v) }.map_err(encode_err) } -/// The file's top-level object, written member by member (the document is streamed in). -struct Envelope { - pretty: bool, - first: bool, -} - -impl Envelope { - fn field(&mut self, out: &mut impl Write, key: &str, value: &impl Serialize) -> Result<(), FormatError> { - let json = to_json(value, self.pretty)?; - self.key(out, key)?; - Indent { inner: out, on: self.pretty }.write_all(&json).map_err(encode_err) - } - - /// The start of member `key` (a plain name): its value follows, indented one level when - /// pretty (as serde_json would: see [`Indent`]). - fn key(&mut self, out: &mut impl Write, key: &str) -> Result<(), FormatError> { - let sep: &[u8] = if std::mem::take(&mut self.first) { b"{" } else { b"," }; - let indent: &[u8] = if self.pretty { b"\n " } else { b"" }; - let colon: &[u8] = if self.pretty { b"\": " } else { b"\":" }; - [sep, indent, b"\"", key.as_bytes(), colon].iter().try_for_each(|part| out.write_all(part)).map_err(encode_err) - } - - fn finish(self, out: &mut impl Write) -> Result<(), FormatError> { - out.write_all(if self.pretty { b"\n}" } else { b"}" }).map_err(encode_err) - } -} - pub fn load(bytes: &[u8]) -> Result<Document, FormatError> { load_info(bytes).map(|(doc, _)| doc) } diff --git a/crates/format/src/stream.rs b/crates/format/src/stream.rs index bed508601f..bc24a67aed 100644 --- a/crates/format/src/stream.rs +++ b/crates/format/src/stream.rs @@ -2,10 +2,9 @@ //! not) and the data after it is copied in from the document's own buffers, so a save holds no //! copy of the file in memory besides what the caller's writer keeps. -use std::collections::HashSet; use std::io::{self, Write}; -use flate2::{Compress, Compression, Crc, FlushCompress, Status}; +use craft_gzip::Gz; /// The output of a save: plain, or gzip ([`Gz`]). pub(crate) enum Out<W: Write> { @@ -26,7 +25,7 @@ impl<W: Write> Out<W> { pub(crate) fn written(&self) -> Option<u64> { match self { Out::Plain(_) => None, - Out::Gz(gz) => Some(gz.total), + Out::Gz(gz) => Some(gz.written()), } } @@ -61,299 +60,3 @@ impl<W: Write> Write for Out<W> { } } } - -/// Bytes of compressed output gathered before they go to the writer. -const OUT_CHUNK: usize = 64 << 10; - -/// A gzip stream, written as [`flate2::write::GzEncoder`] at the default level writes it (the -/// same header and the same data; the deflate blocks are the same too where flate2 deflates with -/// miniz_oxide, not with zlib-rs, which writes them by how the data is fed), except that data which -/// is compressed already ([`Gz::packed`]) is stored as it is: the default level spends a second -/// or more per photo on it for next to nothing, and makes it slower to unpack. Where the level -/// changes the deflate blocks so far end with a sync flush and a fresh compressor writes on, -/// which makes one valid deflate stream that every reader unpacks. -pub(crate) struct Gz<W: Write> { - out: W, - deflate: Compress, - /// What `deflate` writes: stored blocks (packed data), else the default level. - stored: bool, - crc: Crc, - buf: Vec<u8>, - /// Bytes written (unpacked). - total: u64, -} - -impl<W: Write> Gz<W> { - pub(crate) fn new(mut out: W) -> io::Result<Self> { - // flate2's header for the default level: no name, no time, unknown OS. - out.write_all(&[0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 0, 255])?; - Ok(Self { - out, - deflate: Compress::new(Compression::default(), false), - stored: false, - crc: Crc::new(), - buf: Vec::with_capacity(OUT_CHUNK), - total: 0, - }) - } - - /// Run the compressor over `input` with `flush` until it has taken it all (and, flushing, - /// written everything out). - fn deflate(&mut self, mut input: &[u8], flush: FlushCompress) -> io::Result<()> { - loop { - if self.buf.len() == self.buf.capacity() { - self.out.write_all(&self.buf)?; - self.buf.clear(); - } - let (before_in, before_out) = (self.deflate.total_in(), self.deflate.total_out()); - let status = self.deflate.compress_vec(input, &mut self.buf, flush).map_err(io::Error::other)?; - let taken = usize::try_from(self.deflate.total_in() - before_in).unwrap_or(input.len()).min(input.len()); - input = input.get(taken..).unwrap_or_default(); - let made = self.deflate.total_out() - before_out; - let full = self.buf.len() == self.buf.capacity(); - match flush { - FlushCompress::None if input.is_empty() => return Ok(()), - FlushCompress::Finish if status == Status::StreamEnd => return Ok(()), - // A flush is done once it left room in the output. - FlushCompress::Sync if input.is_empty() && !full => return Ok(()), - _ => {} - } - if taken == 0 && made == 0 && !full { - return Err(io::Error::other("the compressor made no progress")); - } - } - } - - /// What is written next is compressed already (stored as it is), or not (compressed at the - /// default level). - fn packed(&mut self, packed: bool) -> io::Result<()> { - if packed == self.stored { - return Ok(()); - } - self.deflate(&[], FlushCompress::Sync)?; - self.deflate = Compress::new(if packed { Compression::none() } else { Compression::default() }, false); - self.stored = packed; - Ok(()) - } - - fn finish(mut self) -> io::Result<()> { - self.deflate(&[], FlushCompress::Finish)?; - self.out.write_all(&self.buf)?; - self.out.write_all(&self.crc.sum().to_le_bytes())?; - self.out.write_all(&self.crc.amount().to_le_bytes())?; - self.out.flush() - } -} - -impl<W: Write> Write for Gz<W> { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - self.write_all(buf)?; - Ok(buf.len()) - } - - fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { - self.crc.update(buf); - self.total += buf.len() as u64; - self.deflate(buf, FlushCompress::None) - } - - fn flush(&mut self) -> io::Result<()> { - // Flushing would end a deflate block: the stream is flushed when it is finished. - Ok(()) - } -} - -/// Indents JSON text written through it one level (two spaces after each newline), as a member -/// of the file's top-level object; newlines only occur between tokens, inside strings they are -/// escaped. -pub(crate) struct Indent<W: Write> { - pub(crate) inner: W, - pub(crate) on: bool, -} - -impl<W: Write> Write for Indent<W> { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - self.write_all(buf)?; - Ok(buf.len()) - } - - fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { - if !self.on { - return self.inner.write_all(buf); - } - let mut lines = buf.split(|&b| b == b'\n'); - self.inner.write_all(lines.next().unwrap_or_default())?; - for line in lines { - self.inner.write_all(b"\n ")?; - self.inner.write_all(line)?; - } - Ok(()) - } - - fn flush(&mut self) -> io::Result<()> { - self.inner.flush() - } -} - -/// The member that names an image. -const TAG: &[u8] = b"\"key\":"; - -/// Passes JSON text through, collecting the string values of every `"key": "…"` member at any -/// depth (what the images a document uses are named by). Quotes inside JSON strings are escaped, -/// so every match is a real member. -pub(crate) struct KeyScan<W: Write> { - pub(crate) inner: W, - pub(crate) keys: HashSet<String>, - /// Looking for keys (else it only passes the text on). - pub(crate) active: bool, - /// How much of [`TAG`] the last bytes matched. - matched: usize, - /// Right after a tag: skipping whitespace to its value. - after_tag: bool, - /// The value string so far, quotes included. - value: Option<Vec<u8>>, - escaped: bool, -} - -impl<W: Write> KeyScan<W> { - pub(crate) fn new(inner: W) -> Self { - Self { inner, keys: HashSet::new(), active: true, matched: 0, after_tag: false, value: None, escaped: false } - } - - fn scan(&mut self, buf: &[u8]) { - if !self.active { - return; - } - let mut i = 0; - while let Some(&b) = buf.get(i) { - // Nothing in progress: skip to the next quote. - if self.matched == 0 && !self.after_tag && self.value.is_none() { - match buf.get(i..).and_then(|r| r.iter().position(|&c| c == b'"')) { - Some(at) => i += at, - None => return, - } - self.matched = 1; - i += 1; - continue; - } - self.step(b); - i += 1; - } - } - - fn step(&mut self, b: u8) { - if let Some(v) = self.value.as_mut() { - v.push(b); - if self.escaped { - self.escaped = false; - } else if b == b'\\' { - self.escaped = true; - } else if b == b'"' - && let Some(v) = self.value.take() - && let Ok(s) = serde_json::from_slice::<String>(&v) - { - self.keys.insert(s); - } - } else if self.after_tag && !b.is_ascii_whitespace() { - self.after_tag = false; - if b == b'"' { - self.value = Some(vec![b]); - } - } - if TAG.get(self.matched) == Some(&b) { - self.matched += 1; - if self.matched == TAG.len() { - self.matched = 0; - self.after_tag = true; - self.value = None; - self.escaped = false; - } - } else { - self.matched = usize::from(b == b'"'); - } - } -} - -impl<W: Write> Write for KeyScan<W> { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - self.write_all(buf)?; - Ok(buf.len()) - } - - fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { - self.scan(buf); - self.inner.write_all(buf) - } - - fn flush(&mut self) -> io::Result<()> { - self.inner.flush() - } -} - -#[cfg(test)] -mod tests { - use proptest::prelude::*; - - use super::*; - - /// How the keys were found before saves were streamed: in the whole JSON text at once. - fn string_members(json: &[u8]) -> HashSet<String> { - let mut out = HashSet::new(); - let mut rest = json; - while let Some(at) = rest.windows(TAG.len()).position(|w| w == TAG) { - rest = rest.get(at + TAG.len()..).unwrap_or_default(); - let value = rest.trim_ascii_start(); - if value.first() == Some(&b'"') - && let Some(Ok(s)) = serde_json::Deserializer::from_slice(value).into_iter::<String>().next() - { - out.insert(s); - } - } - out - } - - /// The keys `KeyScan` finds in `json` written in pieces of `chunk` bytes. - fn scanned(json: &[u8], chunk: usize) -> HashSet<String> { - let mut scan = KeyScan::new(Vec::new()); - for piece in json.chunks(chunk.max(1)) { - scan.write_all(piece).unwrap(); - } - assert_eq!(scan.inner, json, "the text passes through"); - scan.keys - } - - #[test] - fn finds_the_keys_the_whole_text_search_found() { - let v = serde_json::json!({"key": "a", "x": [{"key": "b \"q\" \\ é"}, {"monkey": "no"}, {"k": "key"}], "s": "\"key\": \"no\"", "key2": "n", "o": {"key": 3}}); - for json in [serde_json::to_vec(&v).unwrap(), serde_json::to_vec_pretty(&v).unwrap()] { - let want = string_members(&json); - assert_eq!(want, HashSet::from(["a".to_string(), "b \"q\" \\ é".to_string()])); - for chunk in [1, 2, 3, 7, 64, json.len()] { - assert_eq!(scanned(&json, chunk), want, "chunk {chunk}"); - } - } - } - - fn arb_json() -> impl Strategy<Value = serde_json::Value> { - let key = prop::sample::select(vec!["key", "k", "kkey", "key ", "x"]).prop_map(str::to_string); - let leaf = prop_oneof![ - Just(serde_json::Value::Null), - any::<i32>().prop_map(serde_json::Value::from), - "[a-z\"\\\\: ké\n]{0,8}".prop_map(serde_json::Value::from), - ]; - leaf.prop_recursive(4, 32, 6, move |inner| { - prop_oneof![ - prop::collection::vec(inner.clone(), 0..5).prop_map(serde_json::Value::from), - prop::collection::vec((key.clone(), inner), 0..5).prop_map(|m| serde_json::Value::Object(m.into_iter().collect())), - ] - }) - } - - proptest! { - #[test] - fn scanning_in_pieces_finds_what_the_whole_text_search_found(v in arb_json(), chunk in 1usize..40, pretty in any::<bool>()) { - let json = if pretty { serde_json::to_vec_pretty(&v) } else { serde_json::to_vec(&v) }.unwrap(); - prop_assert_eq!(scanned(&json, chunk), string_members(&json)); - } - } -} diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 8eb1a69e9c..76b9b71798 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -103,6 +103,38 @@ pub fn ellipse(r: Rect) -> PathData { PathData::single(SubPath::new(anchors, true)) } +/// Ellipse inscribed in `r` with `n` smooth anchors (at least 2) spaced evenly by angle, clockwise +/// on screen from the left one, as [`ellipse`] runs. Each segment is a cubic whose handles are +/// 4/3·tan(θ/4) of the tangent at its ends (θ = 360°/`n`), scaled along each axis; the path is then +/// fitted to `r`, so its bounds are `r` whatever the count. 4 anchors give [`ellipse`]. +pub fn ellipse_with_anchors(r: Rect, n: u32) -> PathData { + let n = n.max(2); + let r = r.abs(); + let c = r.center(); + let (rx, ry) = (r.width() / 2.0, r.height() / 2.0); + let step = TAU / f64::from(n); + let k = 4.0 / 3.0 * (step / 4.0).tan(); + let anchors = (0..n) + .map(|i| { + // From the left anchor (angle π). With y down, sin is negative just past π, so the next + // anchor is above the centre: left, then top, then right, as `ellipse` runs. + let a = PI + step * f64::from(i); + let p = Point::new(c.x + rx * a.cos(), c.y + ry * a.sin()); + let d = Vec2::new(-rx * a.sin(), ry * a.cos()) * k; + Anchor { p, h_in: p - d, h_out: p + d, kind: AnchorKind::Smooth } + }) + .collect(); + let path = PathData::single(SubPath::new(anchors, true)); + // Between anchors a curve can reach a little past the ellipse or stop short of it (0.15% of + // the height with 3 anchors): fit the bounds to `r` along each axis that has a size. + let Some(b) = path.bounds() else { return path }; + let fit = |want: f64, got: f64| if want > 0.0 && got > 0.0 { want / got } else { 1.0 }; + let (sx, sy) = (fit(r.width(), b.width()), fit(r.height(), b.height())); + path.transformed( + kurbo::Affine::translate(r.origin().to_vec2()) * kurbo::Affine::scale_non_uniform(sx, sy) * kurbo::Affine::translate(-b.origin().to_vec2()), + ) +} + /// How an ellipse or shape arc is closed or left open when cut between start and end angles. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -761,6 +793,29 @@ mod tests { assert!((area - PI * 50.0 * 30.0).abs() / area < 0.001); } + #[test] + fn ellipse_with_four_anchors_is_the_ellipse_and_others_fit_the_box() { + let r = Rect::new(10.0, 20.0, 110.0, 80.0); + let (four, plain) = (ellipse_with_anchors(r, 4), ellipse(r)); + for (a, b) in four.subpaths[0].anchors.iter().zip(&plain.subpaths[0].anchors) { + assert!(a.p.distance(b.p) < 1e-9 && a.h_in.distance(b.h_in) < 1e-9 && a.h_out.distance(b.h_out) < 1e-9, "{a:?} {b:?}"); + } + for n in [2, 3, 5, 7, 9, 1000] { + let p = ellipse_with_anchors(r, n); + assert_eq!(p.anchor_count(), n as usize); + let b = p.bounds().unwrap(); + assert!( + (b.x0 - r.x0).abs() < 1e-9 && (b.y0 - r.y0).abs() < 1e-9 && (b.x1 - r.x1).abs() < 1e-9 && (b.y1 - r.y1).abs() < 1e-9, + "{n}: {b:?}" + ); + let area = p.subpaths[0].area().abs(); + assert!((area - PI * 50.0 * 30.0).abs() / area < if n == 2 { 0.1 } else { 0.01 }, "{n}: {area}"); + } + // A box with no height leaves the path flat rather than dividing by zero. + let flat = ellipse_with_anchors(Rect::new(0.0, 5.0, 40.0, 5.0), 6); + assert!(flat.subpaths[0].anchors.iter().all(|a| a.p.y == 5.0 && a.p.x.is_finite())); + } + #[test] fn rounded_rect_clamps() { let p = rounded_rectangle(Rect::new(0.0, 0.0, 20.0, 10.0), 100.0); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index aa4a4c5c78..7e21bf9fdf 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -310,6 +310,10 @@ pub(crate) const MAX_APPLY_ARGS: usize = 1 << 16; /// The estimated bytes of a name's entries in the list and the set `for-in` builds. const KEY_ENTRY_BYTES: usize = 32; +/// The most units of a computed property name an error about a property of `null` or `undefined` +/// names; a longer name is left out of the message. +const NAMED_KEY_UNITS: usize = 256; + #[cfg(test)] thread_local! { /// Tests: the [`Interp::finally_sites`] entries that leaving a block or a frame has looked at. @@ -1077,8 +1081,8 @@ impl Interp { } fn not_defined(&mut self, name: &[u16]) -> Abrupt { - let message = format!("{} is not defined", String::from_utf16_lossy(name)); - self.throw(ErrorType::Reference, &message) + let ident = String::from_utf16_lossy(name); + self.throw(ErrorType::Reference, &format!("{ident} is not defined")) } fn get_var(&mut self, name: &Key) -> JsResult<(Value, Value)> { @@ -1332,12 +1336,9 @@ impl Interp { Value::Number(_) => Ok(self.intrinsics.number_proto), Value::Bool(_) => Ok(self.intrinsics.boolean_proto), Value::Undefined | Value::Null => { - let message = format!( - "cannot read property '{}' of {}", - String::from_utf16_lossy(k), - if matches!(v, Value::Null) { "null" } else { "undefined" } - ); - Err(self.type_error(&message)) + let key = String::from_utf16_lossy(k); + let base = if matches!(v, Value::Null) { "null" } else { "undefined" }; + Err(self.type_error(&format!("cannot read property '{key}' of {base}"))) } } } @@ -1434,8 +1435,8 @@ impl Interp { fn reject_bool(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult<bool> { if throw { - let message = format!("cannot define property '{}': {why}", String::from_utf16_lossy(k)); - return Err(self.type_error(&message)); + let key = String::from_utf16_lossy(k); + return Err(self.type_error(&format!("cannot define property '{key}': {why}"))); } Ok(false) } @@ -1588,8 +1589,8 @@ impl Interp { fn reject(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult<()> { if throw { - let message = format!("cannot assign to property '{}': {why}", String::from_utf16_lossy(k)); - return Err(self.type_error(&message)); + let key = String::from_utf16_lossy(k); + return Err(self.type_error(&format!("cannot assign to property '{key}': {why}"))); } Ok(()) } @@ -1684,8 +1685,8 @@ impl Interp { Ok(true) } Some(_) if throw => { - let message = format!("cannot delete property '{}'", String::from_utf16_lossy(k)); - Err(self.type_error(&message)) + let key = String::from_utf16_lossy(k); + Err(self.type_error(&format!("cannot delete property '{key}'"))) } Some(_) => Ok(false), } @@ -1703,12 +1704,9 @@ impl Interp { self.put(*o, k, v, throw) } Value::Undefined | Value::Null => { - let message = format!( - "cannot set property '{}' of {}", - String::from_utf16_lossy(&k), - if matches!(base, Value::Null) { "null" } else { "undefined" } - ); - Err(self.type_error(&message)) + let key = String::from_utf16_lossy(&k); + let base = if matches!(base, Value::Null) { "null" } else { "undefined" }; + Err(self.type_error(&format!("cannot set property '{key}' of {base}"))) } _ => { let proto = self.primitive_proto(base, &k)?; @@ -1742,16 +1740,30 @@ impl Interp { self.replace(2, v) } - fn check_coercible(&mut self, base: &Value, k: &[u16]) -> JsResult<()> { - if base.is_nullish() { - self.primitive_proto(base, k)?; + /// Throws when `base` is `null` or `undefined`, naming the property `k` when it is a primitive + /// of at most [`NAMED_KEY_UNITS`] units, which converts without running script code, and the + /// access as a read, or as a write when `set`. + fn check_coercible(&mut self, base: &Value, k: Option<&Value>, set: bool) -> JsResult<()> { + if !base.is_nullish() { + return Ok(()); } - Ok(()) + let key = match k { + Some(Value::String(s)) if s.len() > NAMED_KEY_UNITS => None, + Some(Value::Object(_)) | None => None, + Some(k) => Some(self.to_str(k)?.to_rust_string()), + }; + let base = if matches!(base, Value::Null) { "null" } else { "undefined" }; + Err(match (key, set) { + (Some(key), false) => self.type_error(&format!("cannot read property '{key}' of {base}")), + (Some(key), true) => self.type_error(&format!("cannot set property '{key}' of {base}")), + (None, false) => self.type_error(&format!("cannot read a property of {base}")), + (None, true) => self.type_error(&format!("cannot set a property of {base}")), + }) } fn op_check_object(&mut self) -> JsResult<()> { let base = self.peek(0)?; - self.check_coercible(&base, &[]) + self.check_coercible(&base, None, true) } fn op_to_key(&mut self) -> JsResult<()> { @@ -1760,7 +1772,7 @@ impl Interp { if self.is_xml_access(&base, &k) { return Ok(()); } - self.check_coercible(&base, &[])?; + self.check_coercible(&base, Some(&k), true)?; let name = self.to_key(&k)?; self.replace(1, Value::String(Str::from_rc(name))) } @@ -1778,7 +1790,7 @@ impl Interp { let v = self.xml_get(&base, &k)?; return self.replace(2, v); } - self.check_coercible(&base, &[])?; + self.check_coercible(&base, Some(&k), false)?; let v = self.with_key(&k, |i, name| i.get_value(&base, &name))?; self.replace(2, v)?; if with_this { self.push(base) } else { Ok(()) } @@ -1817,7 +1829,7 @@ impl Interp { let r = self.xml_delete(&base, &k)?; return self.replace(2, Value::Bool(r)); } - self.check_coercible(&base, &[])?; + self.check_coercible(&base, Some(&k), false)?; let name = self.to_key(&k)?; let o = self.to_object(&base)?; let strict = self.strict(); @@ -1850,7 +1862,7 @@ impl Interp { self.xml_put(&base, &k, &Value::Number(new))?; return self.replace(2, Value::Number(if prefix { new } else { old })); } - self.check_coercible(&base, &[])?; + self.check_coercible(&base, Some(&k), false)?; let r = self.with_key(&k, |i, name| i.inc_property(&base, name, prefix, dec))?; self.replace(2, r) } @@ -2573,8 +2585,8 @@ impl Interp { self.put(object, name.clone(), v, true) } Some(_) => { - let message = format!("cannot declare function {}", String::from_utf16_lossy(name)); - Err(self.type_error(&message)) + let ident = String::from_utf16_lossy(name); + Err(self.type_error(&format!("cannot declare function {ident}"))) } } } diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index 93c487b378..9f9c59a96f 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -239,6 +239,27 @@ fn errors_carry_line_and_column() { assert_eq!(e.message, "42"); } +/// An error about a property of `null` or `undefined` names a computed property whose name is a +/// primitive, and says whether the script read or set it, never naming an empty property; a +/// member assignment, an object key and a long name leave the name out. +#[test] +fn errors_about_null_and_undefined_name_the_property() { + for (source, message) in [ + ("null[1]", "TypeError: cannot read property '1' of null"), + ("var u; u['k'] += 1", "TypeError: cannot set property 'k' of undefined"), + ("var u; u['k']++", "TypeError: cannot read property 'k' of undefined"), + ("delete null[true]", "TypeError: cannot read property 'true' of null"), + ("var u; u['k'] = 1", "TypeError: cannot set property 'k' of undefined"), + ("null.x", "TypeError: cannot read property 'x' of null"), + ("var u; u.y = 1", "TypeError: cannot set a property of undefined"), + ("var u; u[{}] = 1", "TypeError: cannot set a property of undefined"), + ("null[new Array(300).join('a')]", "TypeError: cannot read a property of null"), + ] { + assert_eq!(fail(source).message, message, "{source}"); + } + truth("var k = {toString: function () { throw 1; }}; try { null[k]; false } catch (e) { e instanceof TypeError }"); +} + #[test] fn host_functions_receive_arguments_and_return_values() { let mut realm = Realm::new(); 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 b5fd1135aa..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<Value, String> { - 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<u8>| p[0] < 60 && p[1] < 60 && p[2] < 60; let white = |p: &image::Rgba<u8>| p[0] > 245 && p[1] > 245 && p[2] > 245; @@ -1544,6 +1555,8 @@ fn headless_backend_methods() { let selected = h.call("ui.tool.select", json!({"tool": tool.id})).unwrap(); assert_eq!(selected["tool"], tool.id); } + let polygonal = groups.iter().flat_map(|group| group.as_array().unwrap()).find(|entry| entry["id"] == "polygonalLasso"); + assert_eq!(polygonal.map(|entry| entry["label"].clone()), Some(json!("Polygonal Lasso Tool"))); assert!(h.call("ui.resize", json!({})).is_err()); } 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/tests/gradient.rs b/crates/mcp/src/tests/gradient.rs index 302926ed1c..e5d8925006 100644 --- a/crates/mcp/src/tests/gradient.rs +++ b/crates/mcp/src/tests/gradient.rs @@ -44,10 +44,15 @@ fn gradient_annotator_end_to_end() { let r = ok(&mut h, "press_key", json!({"key": "Delete"})); assert_eq!(r["handledBy"], "tool", "{r}"); assert_eq!(offsets(&gradient(&h)), vec![0.0, 100.0]); - // The end handle changes only the end. + // The end handle changes only the length: the end stays on the bar's line. let end = json!({"events": [{"kind": "down", "x": 200, "y": 150}, {"kind": "drag", "x": 230, "y": 120}, {"kind": "up", "x": 230, "y": 120}]}); ok(&mut h, "pointer_gesture", end); let g = gradient(&h).geom.unwrap(); + assert_eq!((g.start, g.end), (Point::new(100.0, 150.0), Point::new(230.0, 150.0))); + // Alt-dragged, it changes the length and the angle together. + let end = json!({"mods": {"alt": true}, "events": [{"kind": "down", "x": 230, "y": 150}, {"kind": "drag", "x": 230, "y": 120}, {"kind": "up", "x": 230, "y": 120}]}); + ok(&mut h, "pointer_gesture", end); + let g = gradient(&h).geom.unwrap(); assert_eq!((g.start, g.end), (Point::new(100.0, 150.0), Point::new(230.0, 120.0))); // Double-clicking a stop asks for its popover. let dbl = ok(&mut h, "pointer_gesture", json!({"events": [{"kind": "doubleclick", "x": 100, "y": 160}]})); diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index 4b55d6aff1..1b86095c6e 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -209,7 +209,7 @@ pub fn tool_definitions() -> Vec<Value> { "x": num("Document x (pt)"), "y": num("Document y (pt)"), "mods": mods_schema(), - "backquote": {"type": "boolean", "description": "Backquote held for this event: Selection and transform tool drags transform only pattern paint"}, + "backquote": {"type": "boolean", "description": "Backquote held for this event: Selection and transform tool drags transform only pattern paint; Rectangle, Rounded Rectangle, Ellipse, Polygon, Star and Line Segment drags leave copies of the shape being drawn"}, "pressure": num("Pen pressure 0..1 (default 1): the Liquify tools' intensity with Use Pressure Pen on, and the pressure the Paintbrush records"), "tiltX": num("Pen tilt in degrees −90..90, positive leaning right (document axes); with tiltY, the tilt the Paintbrush records for Tilt and Bearing brushes. One without the other is 0"), "tiltY": num("Pen tilt in degrees −90..90, positive leaning down the page"), @@ -218,7 +218,7 @@ pub fn tool_definitions() -> Vec<Value> { }), &["kind", "x", "y"]), }, "mods": mods_schema(), - "backquote": {"type": "boolean", "description": "Default backquote held state for events: Selection and transform tool drags transform only pattern paint"}, + "backquote": {"type": "boolean", "description": "Default backquote held state for events: Selection and transform tool drags transform only pattern paint; Rectangle, Rounded Rectangle, Ellipse, Polygon, Star and Line Segment drags leave copies of the shape being drawn"}, }), &["events"], ), @@ -244,7 +244,7 @@ pub fn tool_definitions() -> Vec<Value> { tool( "draw_shape", "Draw shape", - "Create a live shape and apply optional paint. rectangle/ellipse: x, y, width, height (rectangle: radius = corner radius). polygon: cx, cy, radius, sides. star: cx, cy, radius1, radius2, points. line: x1, y1, x2, y2. Omitted paint fields inherit the current new-art appearance (initially white fill and 1 pt black stroke); lines start with no fill and a visible stroke. For a filled shape without an outline, pass an explicit fill and stroke:\"none\". Stroke dash/cap/join, opacity, name and live effects apply to the new shape as in draw_path. Returns the new object id.", + "Create a live shape and apply optional paint. rectangle/ellipse: x, y, width, height (rectangle: radius = corner radius; ellipse: anchors, default 4, where any other count from 2 to 1000 draws a plain path rather than a live shape). polygon: cx, cy, radius, sides. star: cx, cy, radius1, radius2, points. line: x1, y1, x2, y2. Omitted paint fields inherit the current new-art appearance (initially white fill and 1 pt black stroke); lines start with no fill and a visible stroke. For a filled shape without an outline, pass an explicit fill and stroke:\"none\". Stroke dash/cap/join, opacity, name and live effects apply to the new shape as in draw_path. Returns the new object id.", obj( with_draw_options(json!({ "shape": {"type": "string", "enum": ["rectangle", "ellipse", "polygon", "star", "line"]}, @@ -253,6 +253,7 @@ pub fn tool_definitions() -> Vec<Value> { "width": num("Width (rectangle/ellipse)"), "height": num("Height (rectangle/ellipse)"), "radius": num("Corner radius (rectangle) or radius (polygon)"), + "anchors": {"type": "integer", "minimum": 2, "maximum": 1000, "description": "Ellipse anchors, spaced evenly by angle (default 4, a live ellipse; any other count draws a plain path)"}, "cx": num("Centre x (polygon/star)"), "cy": num("Centre y (polygon/star)"), "sides": {"type": "integer", "minimum": 3, "description": "Polygon sides (default 6)"}, 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<ToolResult, String> { // 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<image::DynamicImage, image::ImageError> { - 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<image::DynamicImage, String> { + 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<u8>, max: Option<u32>, info: &mut Value) -> Result<Vec<u let img = fitted(img, max, max, Resample::Average); info["width"] = json!(img.width()); info["height"] = json!(img.height()); - let mut out = std::io::Cursor::new(Vec::new()); - img.write_to(&mut out, image::ImageFormat::Png).map_err(|e| format!("encode capture: {e}"))?; - Ok(out.into_inner()) + 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 capture: {e}"))?; + craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map_err(|e| format!("encode capture: {e}")) } pub(super) fn image_result(png: &[u8], info: Value) -> 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/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index ecbdf780fb..f81ea2f7f9 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -167,6 +167,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} toggle a red underline under the words of the document's type its dictionaries don't know (text.spelling.check lists them), kept up to date as the type changes; type with effects isn't underlined → whether Auto Spell Check is on", ), + ( + "ui.checkSpelling", + "Check Spelling…", + "Cmd+I", + "{} open the Check Spelling dialog to walk through unrecognized words with suggestions, ignore, change and dictionary options", + ), ("shortcuts.set", "Set Keyboard Shortcut", "", "{id: command id or tool:<id>, shortcut: \"Cmd+Shift+K\" | \"\" (none) | null (default), force?}"), ("shortcuts.list", "List Keyboard Shortcuts", "", "{query?} → [{id, label, group, shortcut, default, overridden}]"), ("shortcuts.conflicts", "Keyboard Shortcut Conflicts", "", "{} → [{shortcut, ids}]"), @@ -182,7 +188,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "shortcuts.exportText", "Export Keyboard Shortcuts as Text…", "", - "{path?} save the current set's tools and menu commands with their shortcuts as a UTF-8 text file (Keyboard Shortcuts › Export Text…): the set's name, then a Tools and a Menu Commands section in the dialog's order, one `name<TAB>shortcut` line per row, empty after the tab when it has none; without `path`, pick a file", + "{path?, format?: \"text\"|\"sheet\"|\"csv\" (default text), pageSize?: \"letter\"|\"a4\" (sheet only; default A4 when the current document prints on A4, else letter)} save the current set's tools and menu commands with their shortcuts (Keyboard Shortcuts › Export Text…). text: a UTF-8 text file: the set's name, then a Tools and a Menu Commands section in the dialog's order, one `name<TAB>shortcut` line per row, empty after the tab when it has none. sheet: a printable PDF on landscape pages that lists the rows with a shortcut, Tools and then a group per top-level menu, under a colored band per group, shortcut then name, in four columns. csv: a UTF-8 CSV file (RFC 4180 quoting, CRLF) with a `Group,Command,Shortcut` header and one record per row in the sheet's groups, in the UI language; a field that starts with = + - @ and has more after it starts with '. A `path` is written as given. Without it, pick a file: the desktop save dialog offers the three formats (text first) unless `format` names one, and the file type picked decides and gives the name its extension; with no dialog, writer or download, returns {text} (text, csv) or {pdf: base64} (sheet); a bad `format` or `pageSize` is an error", ), ("shortcuts.import", "Import Keyboard Shortcuts…", "", "{path? | data?}"), ( @@ -650,6 +656,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{panel, collapsed?: bool} minimize the group holding a panel to its tabs (in a floating window, the window to its title bar), or restore it, as a double-click on a tab or the drag bar does; the same as window.panel.minimize {panel, minimized}. Without `collapsed` it toggles. Returns {panel, collapsed, layout}", ), + ( + "window.panel.cycleOptions", + "Cycle Display Sizes", + "", + "{panel} show a panel at its next display size, as the double triangle at the right end of its tab strip does: the sizes are the states of its panel menu's Show/Hide Options (Transparency: options and thumbnails, thumbnails alone, neither), largest first, and the smallest goes back to the largest; Align, Attributes, Character, Color, Flattener Preview, Gradient, Info, Paragraph, Stroke, Transform and Transparency have them. An unknown panel or one without display sizes is an error and changes nothing. Returns {panel, size: 0 for the largest, sizes: how many it has}", + ), ( "window.panel.float", "Float Panel", @@ -842,7 +854,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.cropImage", "Crop Image", "", - "{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect}), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box. → {tool}; a tool that cannot be chosen returns the error", + "{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect, ppi?}: ppi when a resolution that changes the image's pixels is set, and for a turned or skewed image its own when none is and it can be cropped to it), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box; {key: \"ppi\", value: 1 to 2400 and at most the selected image's own resolution (300 for a linked image), or null for the image's own} the cropped image's resolution; {key: \"reference\", value: 0 to 8, left to right and top to bottom; 4, the center, by default} the point the Control bar's X and Y name and its W and H resize about; {key: \"linked\", value: true or false (default false)} whether W and H keep the box's proportions. → {tool}; a tool that cannot be chosen returns the error", ), ("effect.applyLast", "Apply Last Effect", "Cmd+Shift+E", "{}"), ( @@ -967,7 +979,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront and filledLines held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", @@ -1378,7 +1390,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "file.exportAs", "Export As…", "", - "{format?, useArtboards?, range?} opens Export As (then the format's options); with {path, …document.export options} writes the file(s) → {path, warnings, files?}; exportSelection: true writes the selection alone, cropped to it, as document.exportSelection writes it (artboard options are not used); under automation read roots, an SVG or SVGZ is refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them, as document.export refuses it", + "{format?, useArtboards?, range?} opens Export As (then the format's options); with {path, …document.export options} writes the file(s) → {path, warnings, files?}; exportSelection: true writes the selection alone, cropped to it, as document.exportSelection writes it (artboard options are not used); under automation read roots, an SVG or SVGZ, or a file that carries the native document, is refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them, as document.export refuses it", ), ( "ui.fileInfoDialog", @@ -1635,6 +1647,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{set?: index, action?: index} copy the Actions panel's action at action in set (0 is the top set) to right after it in the same set; without action, copy set with all its actions to right after it (default: the current set). The copy is named after the original with \" copy\" added, a copied set gets an id of its own, and the copy is selected. The panel menu's Duplicate runs this for the selected action, else the current set. An index past the last set or action, or a copy that would give its set more than 1,000 actions or an action set file larger than 8 MiB, is an error and copies nothing → {set, action?}", ), + ( + "ui.actionSet.reset", + "Reset Actions", + "", + "{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `resetActions`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}", + ), ("file.showPackage", "Show Package", "", "{folder} show a package folder (file.package's folder) in the file manager → {folder}"), ( "docInfo.save", 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<Vec<u8>, 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<Rgba, &'static str> { - 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/lib.rs b/crates/metafile/src/lib.rs index 86d268cee1..61126ef228 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -74,15 +74,18 @@ pub struct Output { } /// Write the visible art of `doc` over `region` (document space: its top-left corner is the -/// picture's origin, its size the picture's) as `kind`. Live geometry effects are applied first; -/// template layers, hidden objects and guides are left out. Raster effects should be turned into -/// images before (the engine does); the ones left are reported and left out. +/// picture's origin, its size the picture's) as `kind`. Live geometry effects are applied first, +/// in symbols' art too, where each instance places that art (EMF clips 9-slice cells, WMF does +/// not); template layers, hidden objects and guides are left out. Raster effects should be turned +/// into images before (the engine does); the ones left are reported and left out. pub fn export(doc: &Document, region: Rect, kind: Kind) -> Result<Output, String> { let r = region.abs(); if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0 { return Err("the export region is empty".into()); } - let baked = vectorcraft_effects::bake_document(doc); + // The scene writes layers that do not print and leaves hidden layers and objects out. + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, kind == Kind::Emf, layers); let doc = baked.as_ref().unwrap_or(doc); let (ops, mut warnings) = scene::Scene::new(doc, r, kind == Kind::Emf).run(); let bytes = match kind { 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<u8> { - 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<u8> { - 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 f5870c5f95..d8f4e8cce0 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -85,6 +85,43 @@ fn wmf_output_round_trips() { assert!(near(ellipse.geometric_bounds().unwrap(), Rect::new(100.0, 20.0, 180.0, 80.0), 0.1)); } +/// A symbol's square that a Transform effect moves 100 pt right is written where the canvas draws +/// it, in EMF and in WMF, read back: art whose own place is off the artboard is written where the +/// effect moves it onto it, and an instance that doubles the art's width places it first, so the +/// effect still moves it 100 pt (to x = 120, not 220). A stained instance keeps its stain. +#[test] +fn symbol_art_effects_are_written_where_they_draw() { + let moved = |rect: Rect| { + let mut art = path(shapes::rectangle(rect), red(), Paint::None, 0.0); + art.appearance.effects.push(vectorcraft_doc::Effect { + id: "distort.transform".into(), + params: [("moveH", 100.0)].into_iter().collect(), + visible: true, + }); + art + }; + // The art's square, the instance's transform and fill, and the square and color it draws. + let cases = [ + (Rect::new(-90.0, 10.0, -80.0, 20.0), Affine::IDENTITY, None, Rect::new(10.0, 10.0, 20.0, 20.0), [255, 0, 0]), + (Rect::new(10.0, 30.0, 20.0, 40.0), Affine::scale_non_uniform(2.0, 1.0), Some(blue()), Rect::new(120.0, 30.0, 140.0, 40.0), [0, 0, 255]), + ]; + for (square, xf, stain, want, rgb) in cases { + let mut inst = Node::new(vectorcraft_doc::NodeId(0), NodeKind::SymbolInstance { symbol: "Moved".into(), xf }); + if let Some(p) = stain { + inst.appearance = vectorcraft_doc::Appearance::basic(p, Paint::None, 0.0).into(); + } + let mut d = doc_with(200.0, 100.0, vec![inst]); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: std::sync::Arc::new(moved(square)) }); + for kind in [Kind::Emf, Kind::Wmf] { + let back = import(&export(&d, d.artboards[0].rect, kind).unwrap().bytes).unwrap(); + let drawn: Vec<(Option<Rect>, Option<[u8; 3]>)> = paths(&back.document).iter().map(|n| (n.geometric_bounds(), fill_rgb(n))).collect(); + assert_eq!(drawn.len(), 1, "{kind:?} {xf:?}: {drawn:?}"); + assert!(drawn[0].0.is_some_and(|b| near(b, want, 0.1)), "{kind:?} {xf:?}: {drawn:?}"); + assert_eq!(drawn[0].1, Some(rgb), "{kind:?} {xf:?}"); + } + } +} + #[test] fn freeform_points_that_share_a_model_are_written_as_their_mix() { use vectorcraft_color::{Color, Freeform, FreeformPoint, GradientKind}; @@ -102,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); @@ -144,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<u8> { - 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/pathops/README.md b/crates/pathops/README.md index 08380830b2..2397045a84 100644 --- a/crates/pathops/README.md +++ b/crates/pathops/README.md @@ -61,6 +61,14 @@ Unlike `regions`, which splits the filled areas of closed shapes, `live_paint` t `shape_builder` gives the Shape Builder's regions. With closed paths only, they are the `regions`. Once an open path is among them, they are the `live_paint` faces, so a stroke-only line across a shape splits it and lines can enclose a region of their own. The second list holds the pieces of each path that has no closed subpath, keyed by its index, so the Shape Builder can delete them one by one. The caller closes any open path whose fill should count. Inputs with more than `SHAPE_BUILDER_MAX_SEGMENTS` segments fall back to the filled areas. +```rust +pub struct Adjacency { pub faces: Vec<MapFace>, pub edges: Vec<MapEdge>, pub slivers: Vec<PathData>, pub outlines: Vec<MapOutline> } +pub struct MapEdge { pub path: PathData, pub sources: Vec<usize>, pub left: Option<usize>, pub right: Option<usize>, pub piece: usize } +pub fn adjacency(shapes: &[Shape], precision: f64) -> Option<Adjacency>; +``` + +`adjacency` maps the paths as `live_paint` does and also reports, for each edge, every input it lies on and the faces on its left and right as it runs along its path (document coordinates, y down). A line drawn on top of another keeps both inputs on the edge, whatever the input order. A piece of line that ends inside a face has that face on both sides. Faces narrower than `precision` are listed as slivers, and `outlines` holds the outer boundary of each connected piece of the paths. It returns `None` for more than `SHAPE_BUILDER_MAX_SEGMENTS` segments, non-finite input or a `precision` that is not a positive number. + ## Offset / stroke ```rust diff --git a/crates/pathops/src/addons/pathtools.rs b/crates/pathops/src/addons/pathtools.rs index a20a4a5b36..87cc5ba56f 100644 --- a/crates/pathops/src/addons/pathtools.rs +++ b/crates/pathops/src/addons/pathtools.rs @@ -4,7 +4,9 @@ //! tool shows over a path, open paths lengthened or shortened at an end ([`extend`]), the places //! where paths cross ([`crossings`]), the stretches between them ([`spans`]), anchors slid along //! their path ([`slide`]), touching edges merged ([`shared_edge`]), paths divided into dashes -//! ([`divide_dashes`]) and the Parametric Shape Tool's shapes ([`shapes`]). +//! ([`divide_dashes`]), the common tangents of two convex outlines ([`common_tangents`]), the +//! Parametric Shape Tool's shapes ([`shapes`]) and the circles that touch two or three shapes +//! ([`tangent_circles`]). mod crossings; mod dashes; @@ -12,6 +14,8 @@ mod extend; pub mod shapes; mod shared_edge; mod slide; +mod tangent_circle; +mod tangents; #[cfg(test)] mod tests; mod trim; @@ -28,6 +32,8 @@ pub use shared_edge::{ COINCIDENCE, EndSide, Follow, MAX_COINCIDENCE, MergePlan, MergePreview, Stretch, apply_merge, ends_at, merge_preview, stretches_at, }; pub use slide::{MAX_SLIDE, slide_anchor, slide_stops, slide_t_at}; +pub use tangent_circle::{Circle, MAX_TANGENT_CIRCLE_SEGMENTS, MAX_TANGENT_CIRCLES, TangentCircleError, tangent_circle_segments, tangent_circles}; +pub use tangents::{Coincide, MAX_TANGENT_SEGMENTS, Outline, OutlineError, Tangent, TangentKind, common_tangents}; pub use trim::{Span, slice, span_at, spans, without_spans}; use crate::fit::{end_tangent, start_tangent}; diff --git a/crates/pathops/src/addons/pathtools/crossings.rs b/crates/pathops/src/addons/pathtools/crossings.rs index c20e559d96..bcc254aa82 100644 --- a/crates/pathops/src/addons/pathtools/crossings.rs +++ b/crates/pathops/src/addons/pathtools/crossings.rs @@ -226,6 +226,27 @@ impl Default for Work { } } +impl Work { + /// One `n`th of the work of [`Work::default`] (all of it for `n` of 0 or 1). + pub const fn share(n: usize) -> Work { + let n = if n == 0 { 1 } else { n }; + Work { pairs: MAX_PAIRS / n, steps: MAX_STEPS / n } + } + + /// The work done since the budget was `before`. + pub fn spent_since(self, before: Work) -> Work { + Work { pairs: before.pairs.saturating_sub(self.pairs), steps: before.steps.saturating_sub(self.steps) } + } + + /// Take `cost` (from [`Work::spent_since`]) out of what is left, as if that work were done + /// again. `None`, leaving the budget as it was, when less than `cost` is left. + pub fn draw(&mut self, cost: Work) -> Option<()> { + let (pairs, steps) = (self.pairs.checked_sub(cost.pairs)?, self.steps.checked_sub(cost.steps)?); + *self = Work { pairs, steps }; + Some(()) + } +} + /// Where `others` cross `path`, and where `path` crosses itself (a segment that loops over itself /// included): the places on `path`, in order, within the work of [`Work::default`]. pub fn crossings_on(path: &PathData, others: &[&PathData]) -> Option<Vec<Place>> { diff --git a/crates/pathops/src/addons/pathtools/tangent_circle.rs b/crates/pathops/src/addons/pathtools/tangent_circle.rs new file mode 100644 index 0000000000..b17a52cac6 --- /dev/null +++ b/crates/pathops/src/addons/pathtools/tangent_circle.rs @@ -0,0 +1,744 @@ +//! Tangent Circle: the circles that touch two shapes and have a given radius, or that touch three +//! shapes. A circle touches a shape when it meets the shape's outline without crossing it: the +//! whole outline lies outside the circle (its nearest point is on the circle) or inside it (its +//! farthest point is on the circle). At a smooth point of the outline the circle is tangent there; +//! at a corner or an open end it passes through that point. +//! +//! When every shape is a four-segment Bézier circle the answer is closed-form (the problem of +//! Apollonius for three), then moved onto the drawn outlines. +//! Otherwise the centers are isolated on a grid that is split where a root can be: the distance +//! from a point to an outline changes by at most the distance the point moves, so a cell whose +//! center is too far from every condition holds no center and is dropped. The cells left are +//! refined with Newton's method on the exact curves. + +use kurbo::{CubicBez, ParamCurve, Point, Vec2}; +use vectorcraft_geom::PathData; + +#[cfg(test)] +mod tests; + +/// Most segments the shapes may hold together, counted by [`tangent_circle_segments`]. +pub const MAX_TANGENT_CIRCLE_SEGMENTS: usize = 2_000; + +/// The segments of `p`'s subpaths, a lone anchor counting as one. +pub fn tangent_circle_segments(p: &PathData) -> usize { + p.subpaths.iter().map(|sp| sp.segment_count().max(usize::from(!sp.anchors.is_empty()))).sum() +} +/// Most circles one call returns. +pub const MAX_TANGENT_CIRCLES: usize = 64; +/// With three shapes, the largest radius looked for, as a multiple of the diagonal of the box +/// around the shapes' anchors and handles. +const MAX_RADIUS_FACTOR: f64 = 64.0; + +/// A circle by its center and radius. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Circle { + pub center: Point, + pub radius: f64, +} + +/// Why [`tangent_circles`] gives no answer. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TangentCircleError { + /// Not two shapes with a radius above 0, nor three shapes without one; or a shape with no + /// outline, or values that are not finite. + BadInput, + /// More than [`MAX_TANGENT_CIRCLE_SEGMENTS`] segments, or a search that would take too long. + TooComplex, + /// More than [`MAX_TANGENT_CIRCLES`] circles: the shapes may be touched along a whole curve + /// (two concentric circles, for example). + TooMany, +} + +/// The circles that touch every one of `shapes` (document coordinates): two shapes and `radius`, +/// or three shapes and no radius. They are listed by radius, then top to bottom, then left to +/// right; an empty list when no circle touches them all. +pub fn tangent_circles(shapes: &[&PathData], radius: Option<f64>) -> Result<Vec<Circle>, TangentCircleError> { + use TangentCircleError::*; + match (shapes.len(), radius) { + (2, Some(r)) if r.is_finite() && r > 0.0 => {} + (3, None) => {} + _ => return Err(BadInput), + } + if shapes.iter().map(|p| tangent_circle_segments(p)).sum::<usize>() > MAX_TANGENT_CIRCLE_SEGMENTS { + return Err(TooComplex); + } + let mut bounds = None::<kurbo::Rect>; + // The smallest shape's diagonal. + let mut smallest = f64::INFINITY; + for p in shapes { + if p.subpaths.iter().all(|sp| sp.anchors.is_empty()) { + return Err(BadInput); + } + let b = p.control_bounds().ok_or(BadInput)?; + smallest = smallest.min(b.width().hypot(b.height())); + bounds = Some(bounds.map_or(b, |a| a.union(b))); + } + let bounds = bounds.ok_or(BadInput)?; + let finite = [bounds.x0, bounds.y0, bounds.x1, bounds.y1].iter().all(|v| v.is_finite()); + // The work is done about the bounds' center and in units of their diagonal. + let origin = bounds.center(); + let scale = bounds.width().hypot(bounds.height()); + if !finite || !scale.is_finite() || scale <= 0.0 { + return Err(BadInput); + } + let local = |p: Point| Point::new((p.x - origin.x) / scale, (p.y - origin.y) / scale); + let r = radius.map(|r| r / scale); + if r.is_some_and(|r| !r.is_finite()) { + // Shapes so small that the radius is past any number in their units. + return Err(BadInput); + } + let circles: Option<Vec<Circle>> = + shapes.iter().map(|p| as_circle(p).map(|c| Circle { center: local(c.center), radius: c.radius / scale })).collect(); + // Two of three shapes the same circle up to rounding, or two copies of the same path: every + // circle touching it and the third touches all three. + let same = |a: &Circle, b: &Circle| (a.center - b.center).hypot() <= COPY && (a.radius - b.radius).abs() <= COPY; + if shapes.len() == 3 + && (0..3).any(|i| match &circles { + Some(c) => same(&c[i], &c[(i + 1) % 3]), + None => shapes[i] == shapes[(i + 1) % 3], + }) + { + return Err(TooMany); + } + let outlines: Vec<Outline> = shapes.iter().map(|p| Outline::new(p, &local)).collect(); + let found = match circles { + Some(c) => { + let exact = match r { + Some(r) => two_circles(c[0], c[1], r)?, + None => apollonius(c[0], c[1], c[2]).into_iter().filter(|c| c.radius <= MAX_RADIUS_FACTOR).collect(), + }; + // The paths are Bézier circles: each answer is polished on their outlines. + exact.into_iter().map(|found| on_outlines(&outlines, &c, r, found)).collect() + } + None => numeric(&outlines, r)?, + }; + // Answers about a shape far smaller than the gaps between the shapes can be closer together than + // `SAME`: the tolerance shrinks with that shape. + let tolerance = SAME.min(smallest / scale * 1e-3).max(COPY); + let mut out = dedup(found, tolerance); + if out.len() > MAX_TANGENT_CIRCLES { + return Err(TooMany); + } + sort(&mut out, tolerance); + Ok(out + .into_iter() + .map(|c| Circle { center: Point::new(origin.x + c.center.x * scale, origin.y + c.center.y * scale), radius: c.radius * scale }) + .filter(|c| c.center.x.is_finite() && c.center.y.is_finite() && c.radius.is_finite()) + .collect()) +} + +/// `found`, an answer for the ideal circles `ideal`, moved by Newton's method to touch the +/// `outlines` of the paths themselves in the same way: each circle's outline lies outside the answer +/// (nearest point), or inside it when the answer holds that circle (farthest point). `found` as it +/// is when the method does not settle nearby: where the answer is within the Bézier circles' own +/// error (0.0273% of the radius) of touching them in two places or none, it follows the true +/// circles. +fn on_outlines(outlines: &[Outline], ideal: &[Circle], r: Option<f64>, found: Circle) -> Circle { + let mut combo = 0; + for (i, c) in ideal.iter().enumerate() { + let d = (found.center - c.center).hypot(); + let holds = (d + c.radius - found.radius).abs(); + if holds < (d - c.radius - found.radius).abs() && holds < (c.radius - d - found.radius).abs() { + combo |= 1 << i; + } + } + newton(outlines, r, combo, found.center, 1e-4, &mut 0.0) + .filter(|c| (c.center - found.center).hypot() <= 1e-3 && (c.radius - found.radius).abs() <= 1e-3) + .unwrap_or(found) +} + +/// `path` as a circle when it is a four-segment Bézier circle: one closed subpath of four curved +/// segments with a square bounding box, lying within 0.03% of the radius of a circle (its largest +/// error is 0.0273%). +fn as_circle(path: &PathData) -> Option<Circle> { + let [sp] = path.subpaths.as_slice() else { return None }; + if !sp.closed || sp.segment_count() != 4 || (0..4).any(|i| sp.segment_is_line(i)) { + return None; + } + let b = path.bounds()?; + let radius = (b.width() + b.height()) / 4.0; + if !radius.is_finite() || radius <= 0.0 || (b.width() - b.height()).abs() > 1e-6 * radius { + return None; + } + let center = b.center(); + let near = |p: Point| ((p - center).hypot() - radius).abs() <= 3e-4 * radius; + let round = (0..sp.segment_count()).all(|i| { + let seg = sp.segment(i); + (0..=16).all(|k| near(seg.eval(k as f64 / 16.0))) + }); + round.then_some(Circle { center, radius }) +} + +/// Below this (in units of the bounds' diagonal) two values are the same. +const EPS: f64 = 1e-9; + +/// The circles of radius `r` touching circles `a` and `b`: their centers are `a.radius + r` from +/// `a`'s center (outside it) or `|a.radius - r|` (inside it, or holding it), and the same for `b`. +/// A distance of 0 (`r` equal to that circle's radius) puts the center on that circle's center. +/// Concentric circles at a distance both allow touch along a whole circle: [`TangentCircleError::TooMany`]. +fn two_circles(a: Circle, b: Circle, r: f64) -> Result<Vec<Circle>, TangentCircleError> { + let mut out = vec![]; + let apart = (a.center - b.center).hypot(); + let only = |ok: bool, p: Point| if ok { vec![p] } else { vec![] }; + for da in [a.radius + r, (a.radius - r).abs()] { + for db in [b.radius + r, (b.radius - r).abs()] { + let centers = match (da <= EPS, db <= EPS) { + (true, true) => only(apart <= EPS, a.center), + (true, false) => only((apart - db).abs() <= EPS, a.center), + (false, true) => only((apart - da).abs() <= EPS, b.center), + (false, false) if apart <= EPS && (da - db).abs() <= EPS => return Err(TangentCircleError::TooMany), + (false, false) => circle_crossings(a.center, da, b.center, db), + }; + out.extend(centers.into_iter().map(|center| Circle { center, radius: r })); + } + } + Ok(out) +} + +/// Where the circle about `c1` of radius `r1` meets the one about `c2` of radius `r2`: none, one +/// where they touch, or two. +fn circle_crossings(c1: Point, r1: f64, c2: Point, r2: f64) -> Vec<Point> { + let v = c2 - c1; + let d = v.hypot(); + if d <= EPS || d > r1 + r2 + EPS || d < (r1 - r2).abs() - EPS { + return vec![]; + } + let along = (d * d + r1 * r1 - r2 * r2) / (2.0 * d); + let h2 = r1 * r1 - along * along; + let u = v / d; + let foot = c1 + u * along; + // Only rounding takes a touching pair below 0; two crossings closer than `SAME` become one later. + if h2 <= 0.0 { + return vec![foot]; + } + let n = Vec2::new(-u.y, u.x) * h2.sqrt(); + vec![foot + n, foot - n] +} + +/// The circles touching circles `c` (the problem of Apollonius): for each choice of outside (+) +/// or inside (−) per circle, `|center − cᵢ|² = (r ± rᵢ)²`. Subtracting the first equation from the +/// others leaves two linear equations in x, y and r; two of the three unknowns follow from the +/// third, and the first equation gives a quadratic in it. +fn apollonius(a: Circle, b: Circle, c: Circle) -> Vec<Circle> { + let cs = [a, b, c]; + let mut out = vec![]; + for signs in 0..8u8 { + let s = [0, 1, 2].map(|i| if signs & (1 << i) == 0 { 1.0 } else { -1.0 }); + let (x1, y1, r1) = (cs[0].center.x, cs[0].center.y, cs[0].radius * s[0]); + let row = |i: usize| { + let (x, y, ri) = (cs[i].center.x, cs[i].center.y, cs[i].radius * s[i]); + ([2.0 * (x - x1), 2.0 * (y - y1), 2.0 * (ri - r1)], (x * x + y * y - ri * ri) - (x1 * x1 + y1 * y1 - r1 * r1)) + }; + let (m1, b1) = row(1); + let (m2, b2) = row(2); + // Keep the third unknown free whose 2×2 minor is largest. + let minor = |i: usize, j: usize| m1[i] * m2[j] - m1[j] * m2[i]; + let Some((free, (i, j))) = + [(2, (0, 1)), (1, (0, 2)), (0, (1, 2))].into_iter().max_by(|p, q| minor(p.1.0, p.1.1).abs().total_cmp(&minor(q.1.0, q.1.1).abs())) + else { + continue; + }; + let det = minor(i, j); + if det.abs() <= EPS { + continue; + } + // vᵢ = αᵢ + βᵢ t, vⱼ = αⱼ + βⱼ t, with t the free unknown. + let alpha_i = (b1 * m2[j] - b2 * m1[j]) / det; + let beta_i = (-m1[free] * m2[j] + m2[free] * m1[j]) / det; + let alpha_j = (m1[i] * b2 - m2[i] * b1) / det; + let beta_j = (-m1[i] * m2[free] + m2[i] * m1[free]) / det; + let unknowns = |t: f64| { + let mut v = [0.0; 3]; + v[free] = t; + v[i] = alpha_i + beta_i * t; + v[j] = alpha_j + beta_j * t; + v + }; + // (x − x1)² + (y − y1)² − (r + r1)² as a quadratic in t. + let [v0, v1] = [unknowns(0.0), unknowns(1.0)]; + let lin = [v0[0] - x1, v0[1] - y1, v0[2] + r1]; + let dir = [v1[0] - v0[0], v1[1] - v0[1], v1[2] - v0[2]]; + let qa = dir[0] * dir[0] + dir[1] * dir[1] - dir[2] * dir[2]; + let qb = 2.0 * (lin[0] * dir[0] + lin[1] * dir[1] - lin[2] * dir[2]); + let qc = lin[0] * lin[0] + lin[1] * lin[1] - lin[2] * lin[2]; + for t in quadratic_roots(qa, qb, qc) { + let [x, y, r] = unknowns(t); + if r > EPS && [x, y, r].iter().all(|v| v.is_finite()) { + out.push(Circle { center: Point::new(x, y), radius: r }); + } + } + } + out +} + +/// The real roots of `a t² + b t + c`, a double root once; none when every coefficient is 0. +fn quadratic_roots(a: f64, b: f64, c: f64) -> Vec<f64> { + let size = a.abs().max(b.abs()).max(c.abs()); + if size == 0.0 { + return vec![]; + } + let (a, b, c) = (a / size, b / size, c / size); + if a.abs() <= EPS { + return if b.abs() <= EPS { vec![] } else { vec![-c / b] }; + } + let disc = b * b - 4.0 * a * c; + if disc < -1e-12 { + return vec![]; + } + if disc <= 1e-12 { + return vec![-b / (2.0 * a)]; + } + // The root that adds magnitudes first; with b = 0 either sign does. + let q = if b < 0.0 { -0.5 * (b - disc.sqrt()) } else { -0.5 * (b + disc.sqrt()) }; + vec![q / a, c / q] +} + +/// Circles closer than this (in units of the bounds' diagonal) are one. +const SAME: f64 = 1e-6; +/// Given circles closer than this (in units of the bounds' diagonal) are copies of one circle. +const COPY: f64 = 1e-12; + +/// Sorts `circles` (local units) by radius, then top to bottom, then left to right. Values within +/// `tolerance` of each other (the radii of mirror images, for example) sort as equal. +fn sort(circles: &mut [Circle], tolerance: f64) { + let key = |v: f64| (v / tolerance).round(); + circles.sort_by(|a, b| { + key(a.radius).total_cmp(&key(b.radius)).then(key(a.center.y).total_cmp(&key(b.center.y))).then(key(a.center.x).total_cmp(&key(b.center.x))) + }); +} + +/// `found` with each circle within `tolerance` of an earlier one left out. +fn dedup(found: Vec<Circle>, tolerance: f64) -> Vec<Circle> { + let mut out: Vec<Circle> = vec![]; + for c in found { + if !out.iter().any(|o| (o.center - c.center).hypot() <= tolerance && (o.radius - c.radius).abs() <= tolerance) { + out.push(c); + } + } + out +} + +/// A shape's outline, in local units: its segments, and chords that lie within `slack` of them. +struct Outline { + segments: Vec<CubicBez>, + /// Each segment's neighbors along its subpath (before, after), where it has them. + beside: Vec<(Option<usize>, Option<usize>)>, + /// (start, end, segment, t at start, t at end). + chords: Vec<(Point, Point, usize, f64, f64)>, + /// The farthest the chords are from the segments. + slack: f64, +} + +/// How far chords may stray from their segment, at most (local units); each segment is cut into +/// at most [`MAX_CHORDS`] chords, so a tightly bent one may stray more. +const CHORD_SLACK: f64 = 1e-3; +const MAX_CHORDS: usize = 64; + +impl Outline { + fn new(path: &PathData, local: &dyn Fn(Point) -> Point) -> Self { + let mut o = Outline { segments: vec![], beside: vec![], chords: vec![], slack: 0.0 }; + for sp in &path.subpaths { + let n = sp.segment_count(); + if n == 0 { + if let Some(a) = sp.anchors.first() { + // A lone anchor: a segment that stays on its point. + let p = local(a.p); + o.segments.push(CubicBez::new(p, p, p, p)); + o.beside.push((None, None)); + o.chords.push((p, p, o.segments.len() - 1, 0.0, 1.0)); + } + continue; + } + let first = o.segments.len(); + for i in 0..n { + let s = sp.segment(i); + let seg = CubicBez::new(local(s.p0), local(s.p1), local(s.p2), local(s.p3)); + let k = o.segments.len(); + let before = if i > 0 { Some(k - 1) } else { sp.closed.then_some(first + n - 1) }; + let after = if i + 1 < n { Some(k + 1) } else { sp.closed.then_some(first) }; + // |B''| is at most 6 × the larger second difference; a chord over a parameter step + // h strays at most |B''| h² / 8. + let bend = 6.0 + * (seg.p0.to_vec2() - 2.0 * seg.p1.to_vec2() + seg.p2.to_vec2()) + .hypot() + .max((seg.p1.to_vec2() - 2.0 * seg.p2.to_vec2() + seg.p3.to_vec2()).hypot()); + let pieces = ((bend / (8.0 * CHORD_SLACK)).sqrt().ceil() as usize).clamp(1, MAX_CHORDS); + o.slack = o.slack.max(bend / (8.0 * (pieces * pieces) as f64)); + let mut prev = seg.p0; + for j in 1..=pieces { + let t = j as f64 / pieces as f64; + let p = if j == pieces { seg.p3 } else { seg.eval(t) }; + o.chords.push((prev, p, k, (j - 1) as f64 / pieces as f64, t)); + prev = p; + } + o.segments.push(seg); + o.beside.push((before, after)); + } + } + o + } + + /// The chords' nearest and farthest distance from `q`. + fn reach(&self, q: Point) -> Reach { + let mut r = Reach { near: f64::INFINITY, far: -1.0 }; + for &(a, b, ..) in &self.chords { + r.near = r.near.min(chord_near(q, a, b).0); + r.far = r.far.max((q - a).hypot()).max((q - b).hypot()); + } + r + } + + /// The point of the curves nearest `q` (or farthest, `far`) and its distance. Every segment + /// whose chords come within twice the slack of the chords' best answer may hold the true one, + /// so each is polished from its own best chord point, and the best result is kept. + fn extreme(&self, q: Point, far: bool) -> (Point, f64) { + let better = |a: f64, b: f64| if far { a > b } else { a < b }; + let worst = if far { -1.0 } else { f64::INFINITY }; + // Each segment's best chord distance and the parameter where it is reached. + let mut per = vec![(worst, 0.0); self.segments.len()]; + for &(a, b, seg, t0, t1) in &self.chords { + let (d, u) = if far { + let (da, db) = ((q - a).hypot(), (q - b).hypot()); + if db > da { (db, 1.0) } else { (da, 0.0) } + } else { + chord_near(q, a, b) + }; + if let Some(slot) = per.get_mut(seg) + && better(d, slot.0) + { + *slot = (d, t0 + (t1 - t0) * u); + } + } + let best = per.iter().fold(worst, |m, p| if better(p.0, m) { p.0 } else { m }); + let window = 2.0 * self.slack + 1e-12; + let mut out: Option<(Point, f64)> = None; + for (seg, &(d, t)) in per.iter().enumerate() { + if (d - best).abs() > window { + continue; + } + let mut tries = vec![(seg, t)]; + let (before, after) = self.beside.get(seg).copied().unwrap_or((None, None)); + if t <= 0.0 + && let Some(b) = before + { + tries.push((b, 1.0)); + } + if t >= 1.0 + && let Some(a) = after + { + tries.push((a, 0.0)); + } + for (s, t) in tries { + let Some(curve) = self.segments.get(s) else { continue }; + let (p, d) = polish(*curve, q, t, far); + if out.is_none_or(|(_, od)| better(d, od)) { + out = Some((p, d)); + } + } + } + out.unwrap_or((q, 0.0)) + } +} + +/// The distance from `q` to the chord from `a` to `b`, and the parameter along it where it is reached. +fn chord_near(q: Point, a: Point, b: Point) -> (f64, f64) { + let ab = b - a; + let len2 = ab.hypot2(); + let u = if len2 > 0.0 { ((q - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 }; + ((q - (a + ab * u)).hypot(), u) +} + +struct Reach { + near: f64, + far: f64, +} + +/// The nearest (or farthest) point to `q` on `seg` near parameter `t`: Newton's method on +/// (B(t) − q)·B′(t) = 0, kept in 0..1, keeping only steps that improve the distance. +fn polish(seg: CubicBez, q: Point, t: f64, far: bool) -> (Point, f64) { + let dist = |t: f64| (seg.eval(t) - q).hypot(); + let better = |a: f64, b: f64| if far { a > b } else { a < b }; + let (mut t, mut d) = (t, dist(t)); + let [p0, p1, p2, p3] = [seg.p0, seg.p1, seg.p2, seg.p3].map(Point::to_vec2); + for _ in 0..16 { + let mt = 1.0 - t; + let d1 = 3.0 * (mt * mt * (p1 - p0) + 2.0 * mt * t * (p2 - p1) + t * t * (p3 - p2)); + let d2 = 6.0 * (mt * (p2 - 2.0 * p1 + p0) + t * (p3 - 2.0 * p2 + p1)); + let w = seg.eval(t) - q; + let f = w.dot(d1); + let df = d1.hypot2() + w.dot(d2); + if df == 0.0 || !df.is_finite() { + break; + } + let next = (t - f / df).clamp(0.0, 1.0); + let nd = dist(next); + if !better(nd, d) && nd != d { + break; + } + let moved = (next - t).abs(); + (t, d) = (next, nd); + if moved < 1e-15 { + break; + } + } + (seg.eval(t), d) +} + +/// Most grid cells the search looks at, over all levels. +const MAX_CELLS: usize = 400_000; +/// Most cells × chords the search may measure. +const MAX_WORK: f64 = 1.5e8; +/// Most cells Newton's method starts from. +const MAX_TRIES: usize = 4_000; +/// Most chords Newton's method may measure, over all its starts. +const MAX_NEWTON_WORK: f64 = 1.5e8; + +/// Which of a shape's two distances a condition uses: the nearest point (the outline outside the +/// circle) or the farthest (the outline inside it). +fn far_of(combo: usize, shape: usize) -> bool { + combo & (1 << shape) != 0 +} + +/// The circles touching `outlines` (local units): two outlines and radius `r`, or three and none. +fn numeric(outlines: &[Outline], r: Option<f64>) -> Result<Vec<Circle>, TangentCircleError> { + let n = outlines.len(); + let combos = 1usize << n; + let slack = outlines.iter().map(|o| o.slack).fold(0.0, f64::max); + let chords: usize = outlines.iter().map(|o| o.chords.len()).sum(); + let reach = match r { + Some(r) => r, + None => MAX_RADIUS_FACTOR, + }; + // A center is within the radius of a point of every outline, so within its bounds grown by it. + let mut area: Option<kurbo::Rect> = None; + let mut whole: Option<kurbo::Rect> = None; + for o in outlines { + let b = o.chords.iter().fold(None::<kurbo::Rect>, |b, &(p, q, ..)| { + let c = kurbo::Rect::from_points(p, q); + Some(b.map_or(c, |b| b.union(c))) + }); + let Some(b) = b else { return Err(TangentCircleError::BadInput) }; + whole = Some(whole.map_or(b, |w| w.union(b))); + let b = b.inflate(reach + slack, reach + slack); + area = Some(area.map_or(b, |a| a.intersect(b))); + } + let whole = whole.ok_or(TangentCircleError::BadInput)?.inflate(slack, slack); + let span = whole.width().hypot(whole.height()); + let Some(area) = area.filter(|a| a.width() >= 0.0 && a.height() >= 0.0) else { return Ok(vec![]) }; + let side = area.width().max(area.height()).max(1e-12); + let leaf = 2.0 * slack.max(1e-4); + let mut half = side / 2.0; + // The cells alive at the current level: (center, combos still possible). + let all = (1u32 << combos) - 1; + let mut cells = vec![(area.center(), all)]; + let mut looked = 0usize; + let test = |c: Point, half: f64, alive: u32| -> u32 { + let corner = half * std::f64::consts::SQRT_2; + let e = corner + slack; + // Seen from far off, the directions to any two points of the outlines differ little, and + // so do the gradients of their distances: the difference of two distances changes by at + // most 2 × span / (distance to the outlines) per unit moved, rather than 2. + let off = { + let dx = (whole.x0 - c.x).max(c.x - whole.x1).max(0.0); + let dy = (whole.y0 - c.y).max(c.y - whole.y1).max(0.0); + dx.hypot(dy) - corner + }; + let steep = if off > 0.0 { (2.0 * span / off).min(2.0) } else { 2.0 }; + let apart = steep * corner + 2.0 * slack; + let reach: Vec<Reach> = outlines.iter().map(|o| o.reach(c)).collect(); + let d = |i: usize, combo: usize| if far_of(combo, i) { reach[i].far } else { reach[i].near }; + let mut keep = 0; + for combo in 0..combos { + if alive & (1 << combo) == 0 { + continue; + } + let ok = match r { + Some(r) => (0..n).all(|i| (d(i, combo) - r).abs() <= e), + None => { + let (d0, d1, d2) = (d(0, combo), d(1, combo), d(2, combo)); + (d0 - d1).abs() <= apart && (d0 - d2).abs() <= apart && (d1 - d2).abs() <= apart && d0 - e <= MAX_RADIUS_FACTOR + } + }; + if ok { + keep |= 1 << combo; + } + } + keep + }; + loop { + looked += cells.len(); + if looked > MAX_CELLS || looked as f64 * chords as f64 > MAX_WORK { + return Err(TangentCircleError::TooComplex); + } + cells = cells.into_iter().filter_map(|(c, alive)| Some((c, test(c, half, alive))).filter(|x| x.1 != 0)).collect(); + if half * std::f64::consts::SQRT_2 <= leaf || cells.is_empty() { + break; + } + let q = half / 2.0; + cells = cells + .into_iter() + .flat_map(|(c, alive)| [(-q, -q), (q, -q), (-q, q), (q, q)].map(|(dx, dy)| (Point::new(c.x + dx, c.y + dy), alive))) + .collect(); + half = q; + } + // The leaf cells of each combination, in clusters of touching cells. Newton's method starts + // from up to [`SEEDS`] cells of each cluster, each the farthest from those before it. A cluster + // around one center (or two that nearly meet) gives one or two circles; three or more far apart + // mean the shapes are touched along a whole curve. + let step = 2.0 * half; + let mut out = vec![]; + let mut tries = 0usize; + let mut work = 0.0; + let same = |a: &Circle, b: &Circle| (a.center - b.center).hypot() <= SAME && (a.radius - b.radius).abs() <= SAME; + let mut solve = |seed: Point, combo: usize| -> Result<Option<Circle>, TangentCircleError> { + tries += 1; + let c = newton(outlines, r, combo, seed, half, &mut work); + if tries > MAX_TRIES || work > MAX_NEWTON_WORK { + return Err(TangentCircleError::TooComplex); + } + Ok(c) + }; + for combo in 0..combos { + let leaves: Vec<Point> = cells.iter().filter(|(_, a)| a & (1 << combo) != 0).map(|(c, _)| *c).collect(); + let mut found: Vec<Circle> = vec![]; + for cluster in clusters(&leaves, step) { + let mut seeds: Vec<Point> = vec![]; + let mut here: Vec<Circle> = vec![]; + while seeds.len() < SEEDS { + let next = cluster + .iter() + .copied() + .map(|c| (c, seeds.iter().map(|s| (*s - c).hypot()).fold(f64::INFINITY, f64::min))) + .max_by(|a, b| a.1.total_cmp(&b.1)); + let Some((seed, gap)) = next else { break }; + if !seeds.is_empty() && gap <= 2.0 * step { + break; + } + seeds.push(seed); + if let Some(c) = solve(seed, combo)? + && !here.iter().any(|o| same(o, &c)) + { + here.push(c); + } + } + if here.len() > 2 { + return Err(TangentCircleError::TooMany); + } + for c in here { + if !found.iter().any(|o| same(o, &c)) { + found.push(c); + } + } + if found.len() > MAX_TANGENT_CIRCLES { + return Err(TangentCircleError::TooMany); + } + } + out.extend(found); + } + Ok(out) +} + +/// Seeds Newton's method starts from in one cluster of cells, at most. +const SEEDS: usize = 4; + +/// `cells`, centers on a grid `step` apart, in groups of cells that touch (sides or corners). +fn clusters(cells: &[Point], step: f64) -> Vec<Vec<Point>> { + use std::collections::HashMap; + let Some(first) = cells.first() else { return vec![] }; + let key = |p: &Point| (((p.x - first.x) / step).round() as i64, ((p.y - first.y) / step).round() as i64); + let mut at: HashMap<(i64, i64), usize> = cells.iter().enumerate().map(|(i, p)| (key(p), i)).collect(); + let mut out = vec![]; + for p in cells { + let Some(start) = at.remove(&key(p)) else { continue }; + let mut group = vec![]; + let mut stack = vec![start]; + while let Some(i) = stack.pop() { + let Some(c) = cells.get(i) else { continue }; + group.push(*c); + let (kx, ky) = key(c); + for dx in -1..=1 { + for dy in -1..=1 { + if let Some(j) = at.remove(&(kx + dx, ky + dy)) { + stack.push(j); + } + } + } + } + out.push(group); + } + out +} + +/// Newton's method from `seed` on the conditions of `combo`: with `r`, distance(i) = r for both +/// outlines; without, the three distances equal (the radius). Adds the chords it measures to `work`. +fn newton(outlines: &[Outline], r: Option<f64>, combo: usize, seed: Point, step: f64, work: &mut f64) -> Option<Circle> { + let mut c = seed; + let n = outlines.len(); + let cost: f64 = outlines.iter().map(|o| o.chords.len() as f64).sum(); + let limit = (step * 8.0).max(1e-3); + // A radius the search sets itself (three shapes) is kept within its limit. + let fits = |radius: f64| radius > EPS && (r.is_some() || radius <= MAX_RADIUS_FACTOR); + for _ in 0..60 { + *work += cost; + let mut d = [0.0; 3]; + let mut u = [Vec2::ZERO; 3]; + for i in 0..n { + let (p, di) = outlines[i].extreme(c, far_of(combo, i)); + if di <= EPS { + return None; + } + d[i] = di; + u[i] = (c - p) / di; + } + let (f, rows, radius) = match r { + Some(r) => ([d[0] - r, d[1] - r], [u[0], u[1]], r), + None => ([d[0] - d[1], d[0] - d[2]], [u[0] - u[1], u[0] - u[2]], d[0]), + }; + if f[0].abs().max(f[1].abs()) <= 1e-12 { + return fits(radius).then_some(Circle { center: c, radius }); + } + let det = rows[0].cross(rows[1]); + let mut delta = if det.abs() > 1e-9 { + // J Δ = −f, with J's rows the gradients. + Vec2::new(-(f[0] * rows[1].y - f[1] * rows[0].y) / det, -(rows[0].x * f[1] - rows[1].x * f[0]) / det) + } else { + // Rows (nearly) parallel: the least-squares step (JᵀJ + λI) Δ = −Jᵀf, which still + // closes the residual along the rows' direction. + let g = rows[0] * f[0] + rows[1] * f[1]; + let lambda = 1e-12; + let (a, b, d) = ( + rows[0].x * rows[0].x + rows[1].x * rows[1].x + lambda, + rows[0].x * rows[0].y + rows[1].x * rows[1].y, + rows[0].y * rows[0].y + rows[1].y * rows[1].y + lambda, + ); + let m = a * d - b * b; + if !m.is_finite() || m == 0.0 { + break; + } + Vec2::new(-(d * g.x - b * g.y) / m, -(a * g.y - b * g.x) / m) + }; + let len = delta.hypot(); + if !len.is_finite() { + return None; + } + if len > limit { + delta *= limit / len; + } + c += delta; + if delta.hypot() <= 1e-15 { + break; + } + } + // Stopped short of 1e-12: keep it only when it is close (a double root converges slowly). + *work += cost; + let mut d = [0.0; 3]; + for i in 0..n { + d[i] = outlines[i].extreme(c, far_of(combo, i)).1; + } + let (worst, radius) = match r { + Some(r) => ((d[0] - r).abs().max((d[1] - r).abs()), r), + None => ((d[0] - d[1]).abs().max((d[0] - d[2]).abs()), d[0]), + }; + (worst <= 1e-8 && fits(radius)).then_some(Circle { center: c, radius }) +} diff --git a/crates/pathops/src/addons/pathtools/tangent_circle/tests.rs b/crates/pathops/src/addons/pathtools/tangent_circle/tests.rs new file mode 100644 index 0000000000..8b63d29873 --- /dev/null +++ b/crates/pathops/src/addons/pathtools/tangent_circle/tests.rs @@ -0,0 +1,487 @@ +use kurbo::{Affine, Point, Rect}; +use vectorcraft_geom::{PathData, SubPath, shapes}; + +use super::*; + +fn circle(x: f64, y: f64, r: f64) -> PathData { + shapes::ellipse(Rect::new(x - r, y - r, x + r, y + r)) +} + +fn square(x: f64, y: f64, half: f64) -> PathData { + shapes::rectangle(Rect::new(x - half, y - half, x + half, y + half)) +} + +/// Is `c` touching the ideal circle about `center` of radius `r`: `|c − center| = c.r ± r`? +fn touches_circle(c: &Circle, center: Point, r: f64, tol: f64) -> bool { + let d = (c.center - center).hypot(); + (d - (c.radius + r)).abs() <= tol || (d - (c.radius - r).abs()).abs() <= tol +} + +/// The nearest and farthest distance from `q` to points `pts`, a dense sampling of a curve. +fn reach(pts: &[Point], q: Point) -> (f64, f64) { + pts.iter().fold((f64::INFINITY, 0.0), |(lo, hi), p| { + let d = (*p - q).hypot(); + (lo.min(d), hi.max(d)) + }) +} + +/// Does circle `c` touch the densely sampled outline `pts`: its nearest or farthest point on the circle? +fn touches(c: &Circle, pts: &[Point], tol: f64) -> bool { + let (lo, hi) = reach(pts, c.center); + (lo - c.radius).abs() <= tol || (hi - c.radius).abs() <= tol +} + +/// Points along every segment of `path`, `n` per segment. +fn samples(path: &PathData, n: usize) -> Vec<Point> { + path.subpaths + .iter() + .flat_map(|sp| (0..sp.segment_count()).flat_map(move |i| (0..n).map(move |k| sp.segment(i).eval(k as f64 / n as f64)))) + .collect() +} + +fn has(found: &[Circle], center: Point, r: f64, tol: f64) -> bool { + found.iter().any(|c| (c.center - center).hypot() <= tol && (c.radius - r).abs() <= tol) +} + +#[test] +fn three_circles_give_the_eight_apollonius_circles() { + // Equal circles about the corners of a 3-4-5 triangle: the circumcenter (2, 1.5) at 2.5 from + // each center gives the circle outside all three (r = 2.5 − 1) and the one holding all three + // (r = 2.5 + 1). + let shapes = [circle(0.0, 0.0, 1.0), circle(4.0, 0.0, 1.0), circle(0.0, 3.0, 1.0)]; + let found = tangent_circles(&[&shapes[0], &shapes[1], &shapes[2]], None).unwrap(); + // The answers are polished on the Bézier circles, which stray up to 0.0273% of their radius + // from the ideal ones. + let tol = 2e-3; + assert_eq!(found.len(), 8, "{found:?}"); + assert!(has(&found, Point::new(2.0, 1.5), 1.5, tol), "{found:?}"); + assert!(has(&found, Point::new(2.0, 1.5), 3.5, tol), "{found:?}"); + for c in &found { + for (center, r) in [(Point::new(0.0, 0.0), 1.0), (Point::new(4.0, 0.0), 1.0), (Point::new(0.0, 3.0), 1.0)] { + assert!(touches_circle(c, center, r, tol), "{c:?} and {center:?}"); + } + } + // Listed by radius. + assert!(found.windows(2).all(|w| w[0].radius <= w[1].radius + 1e-9)); +} + +#[test] +fn answers_for_circles_touch_the_drawn_bezier_outlines() { + // Radius-100 Bézier circles stray up to 0.027 pt from the ideal circles; the answers touch the + // drawn outlines far closer than that. + let shapes = [circle(0.0, 0.0, 100.0), circle(500.0, 40.0, 100.0), circle(180.0, 420.0, 100.0)]; + let found = tangent_circles(&[&shapes[0], &shapes[1], &shapes[2]], None).unwrap(); + assert_eq!(found.len(), 8, "{found:?}"); + let dense: Vec<Vec<Point>> = shapes.iter().map(|s| samples(s, 20_000)).collect(); + for c in &found { + for pts in &dense { + assert!(touches(c, pts, 1e-3), "{c:?}"); + } + } + let pair = tangent_circles(&[&shapes[0], &shapes[1]], Some(250.0)).unwrap(); + assert!(!pair.is_empty()); + for c in &pair { + assert!(touches(c, &dense[0], 1e-3) && touches(c, &dense[1], 1e-3), "{c:?}"); + } +} + +#[test] +fn three_circles_of_different_sizes() { + // A worked case: circles (0,0) r 1, (10,0) r 2, (5,8) r 3. Every answer satisfies the + // tangency equations, and there are eight since no circle holds or crosses another. + let defs = [(0.0, 0.0, 1.0), (10.0, 0.0, 2.0), (5.0, 8.0, 3.0)]; + let shapes = defs.map(|(x, y, r)| circle(x, y, r)); + let found = tangent_circles(&[&shapes[0], &shapes[1], &shapes[2]], None).unwrap(); + assert_eq!(found.len(), 8, "{found:?}"); + for c in &found { + for (x, y, r) in defs { + assert!(touches_circle(c, Point::new(x, y), r, 5e-3), "{c:?}"); + } + } +} + +#[test] +fn only_true_circles_take_the_closed_form() { + assert!(as_circle(&circle(0.0, 0.0, 100.0)).is_some()); + // Turned, a Bézier circle keeps its square box. + assert!(as_circle(&circle(0.0, 0.0, 100.0).transformed(Affine::rotate(0.35))).is_some()); + // A 200 × 200.1 ellipse is searched along its own outline. + assert!(as_circle(&shapes::ellipse(Rect::new(0.0, 0.0, 200.0, 200.1))).is_none()); + assert!(as_circle(&square(0.0, 0.0, 10.0)).is_none()); + // A 720-sided polygon lies within 0.03% of its circle, but is searched as drawn. + let polygon: Vec<Point> = (0..720) + .map(|k| Point::new(100.0 * (k as f64 / 360.0 * std::f64::consts::PI).cos(), 100.0 * (k as f64 / 360.0 * std::f64::consts::PI).sin())) + .collect(); + assert!(as_circle(&PathData::single(SubPath::polyline(&polygon, true))).is_none()); +} + +#[test] +fn quadratics_without_a_linear_term_give_both_roots() { + let mut roots = quadratic_roots(1.0, 0.0, -1.0); + roots.sort_by(f64::total_cmp); + assert_eq!(roots, vec![-1.0, 1.0]); + let mut roots = quadratic_roots(2.0, -0.0, -8.0); + roots.sort_by(f64::total_cmp); + assert_eq!(roots, vec![-2.0, 2.0]); +} + +#[test] +fn three_circles_keep_the_radius_limit() { + // Nearly in a row: some answers have radii near 1250, past 64 × the bounds' diagonal (about 770). + let shapes = [circle(0.0, 0.0, 1.0), circle(10.0, 0.0, 1.0), circle(5.0, 0.01, 1.0)]; + let found = tangent_circles(&[&shapes[0], &shapes[1], &shapes[2]], None).unwrap(); + let b = shapes.iter().map(|s| s.control_bounds().unwrap()).reduce(|a, b| a.union(b)).unwrap(); + let limit = MAX_RADIUS_FACTOR * b.width().hypot(b.height()); + assert!(!found.is_empty() && found.len() < 8, "{found:?}"); + assert!(found.iter().all(|c| c.radius <= limit), "{found:?}"); +} + +#[test] +fn two_circles_and_a_radius() { + let a = circle(0.0, 0.0, 10.0); + let b = circle(30.0, 0.0, 10.0); + // Polished on the Bézier circles (see above). + let tol = 0.02; + // Radius 5: only the circle in the gap, touching both at once. + let found = tangent_circles(&[&a, &b], Some(5.0)).unwrap(); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(has(&found, Point::new(15.0, 0.0), 5.0, tol)); + // Radius 20: two outside both, two holding the first and two holding the second. + let found = tangent_circles(&[&a, &b], Some(20.0)).unwrap(); + assert_eq!(found.len(), 6, "{found:?}"); + let h = (30.0f64 * 30.0 - 15.0 * 15.0).sqrt(); + assert!(has(&found, Point::new(15.0, -h), 20.0, tol) && has(&found, Point::new(15.0, h), 20.0, tol)); + for c in &found { + assert!(touches_circle(c, Point::new(0.0, 0.0), 10.0, tol) && touches_circle(c, Point::new(30.0, 0.0), 10.0, tol)); + } + // Top to bottom for one radius. + assert!(found.windows(2).all(|w| w[0].center.y <= w[1].center.y + 1e-9)); + // Radius 10, the circles' own, 20 apart: each circle itself touches the other at one point; with + // the two outside both, four in all. + let c = circle(20.0, 0.0, 10.0); + let found = tangent_circles(&[&a, &c], Some(10.0)).unwrap(); + assert_eq!(found.len(), 4, "{found:?}"); + assert!(has(&found, Point::new(0.0, 0.0), 10.0, tol) && has(&found, Point::new(20.0, 0.0), 10.0, tol), "{found:?}"); + for f in &found { + assert!(touches_circle(f, Point::new(0.0, 0.0), 10.0, tol) && touches_circle(f, Point::new(20.0, 0.0), 10.0, tol), "{f:?}"); + } + // Too small to reach across: none. + let far = circle(100.0, 0.0, 10.0); + assert_eq!(tangent_circles(&[&a, &far], Some(5.0)).unwrap(), vec![]); +} + +#[test] +fn the_numeric_search_agrees_with_the_closed_form() { + // The grid search and Newton on the Bézier outlines find what the closed form finds, within + // the Bézier circle's own error (0.03% of the radius). + let defs = [(0.0, 0.0, 10.0), (35.0, 5.0, 6.0), (12.0, 30.0, 4.0)]; + let shapes = defs.map(|(x, y, r)| circle(x, y, r)); + let refs = [&shapes[0], &shapes[1], &shapes[2]]; + let closed = tangent_circles(&refs, None).unwrap(); + let b = shapes.iter().map(|s| s.control_bounds().unwrap()).reduce(|a, b| a.union(b)).unwrap(); + let (o, s) = (b.center(), b.width().hypot(b.height())); + let local = |p: Point| Point::new((p.x - o.x) / s, (p.y - o.y) / s); + let outlines: Vec<Outline> = refs.iter().map(|p| Outline::new(p, &local)).collect(); + let numeric3 = dedup(numeric(&outlines, None).unwrap(), SAME); + assert_eq!(numeric3.len(), closed.len(), "{numeric3:?} vs {closed:?}"); + for c in &closed { + let tol = 1e-3 * c.radius.max(10.0) / s; + assert!(has(&numeric3, local(c.center), c.radius / s, tol), "{c:?} missing from {numeric3:?}"); + } + let closed2 = tangent_circles(&refs[..2], Some(12.0)).unwrap(); + let numeric2 = dedup(numeric(&outlines[..2], Some(12.0 / s)).unwrap(), SAME); + assert_eq!(numeric2.len(), closed2.len(), "{numeric2:?} vs {closed2:?}"); + for c in &closed2 { + assert!(has(&numeric2, local(c.center), c.radius / s, 1e-2 / s), "{c:?}"); + } +} + +/// An ellipse with semi-axes `a` and `b` about the origin, mapped by `m`: its Bézier path and its +/// exact points by angle. +fn mapped_ellipse(a: f64, b: f64, m: Affine) -> (PathData, impl Fn(f64) -> Point + Copy) { + let path = shapes::ellipse(Rect::new(-a, -b, a, b)).transformed(m); + let exact = move |th: f64| m * Point::new(a * th.cos(), b * th.sin()); + (path, exact) +} + +/// Independently of the code under test: the centers of the circles of radius `r` that touch the +/// exact convex curve `exact` (about `middle`) and the circle about `cc` of radius `rc`, in every +/// combination. A center lies on the curve's normal at `r` (outward or inward) where its distance to +/// `cc` is `rc + r` or `|rc − r|`; it counts when the curve's nearest or farthest point from it is +/// at `r`. +fn independent_centers(exact: impl Fn(f64) -> Point + Copy, middle: Point, cc: Point, rc: f64, r: f64) -> Vec<Point> { + let tau = std::f64::consts::TAU; + let dense: Vec<Point> = (0..100_000).map(|k| exact(k as f64 / 100_000.0 * tau)).collect(); + let n = 200_000; + let mut out: Vec<Point> = vec![]; + for side in [1.0, -1.0] { + let normal = move |th: f64| { + let p = exact(th); + let t = (exact(th + 1e-7) - exact(th - 1e-7)).normalize(); + let mut nrm = Vec2::new(t.y, -t.x); + if nrm.dot(p - middle) < 0.0 { + nrm = -nrm; + } + p + nrm * (side * r) + }; + for target in [rc + r, (rc - r).abs()] { + let g = |th: f64| (normal(th) - cc).hypot() - target; + for k in 0..n { + let (mut a, mut b) = (k as f64 / n as f64 * tau, (k + 1) as f64 / n as f64 * tau); + if g(a) * g(b) < 0.0 { + for _ in 0..60 { + let m = (a + b) / 2.0; + if g(a) * g(m) <= 0.0 { b = m } else { a = m } + } + let q = normal(a); + let (lo, hi) = reach(&dense, q); + let touching = (lo - r).abs() <= 1e-3 || (hi - r).abs() <= 1e-3; + if touching && !out.iter().any(|o| (*o - q).hypot() <= 1e-6) { + out.push(q); + } + } + } + } + } + out +} + +/// `found` and `independent` are the same centers, within `tol`. +fn same_centers(found: &[Circle], independent: &[Point], tol: f64) { + assert_eq!(found.len(), independent.len(), "{found:?} vs {independent:?}"); + for p in independent { + assert!(found.iter().any(|c| (c.center - *p).hypot() <= tol), "{p:?} missing from {found:?}"); + } +} + +#[test] +fn a_rotated_ellipse_and_a_circle_match_an_independent_solve() { + let (ellipse, exact) = mapped_ellipse(40.0, 20.0, Affine::rotate(30f64.to_radians())); + let (cc, rc, r) = (Point::new(70.0, 10.0), 12.0, 15.0); + let disc = circle(cc.x, cc.y, rc); + let found = tangent_circles(&[&ellipse, &disc], Some(r)).unwrap(); + // Every circle touches the analytic ellipse and the circle (Bézier error: 0.03% of 40 pt). + let dense: Vec<Point> = (0..200_000).map(|k| exact(k as f64 / 200_000.0 * std::f64::consts::TAU)).collect(); + for c in &found { + assert!(touches(c, &dense, 0.03), "{c:?}"); + assert!(touches_circle(c, cc, rc, 0.01), "{c:?}"); + } + // Every combination (outside both, holding the circle, holding the ellipse, inside it) solved + // independently: the same circles. + same_centers(&found, &independent_centers(exact, Point::ZERO, cc, rc, r), 0.05); + // A circle overlapping the ellipse, with a radius large enough to hold either. + let (cc, rc, r) = (Point::new(30.0, 5.0), 15.0, 50.0); + let found = tangent_circles(&[&ellipse, &circle(cc.x, cc.y, rc)], Some(r)).unwrap(); + same_centers(&found, &independent_centers(exact, Point::ZERO, cc, rc, r), 0.05); +} + +#[test] +fn a_rotated_and_skewed_ellipse_matches_an_independent_solve() { + let m = Affine::translate((-20.0, 15.0)) * Affine::skew(0.4, 0.0) * Affine::rotate(-0.7); + let (ellipse, exact) = mapped_ellipse(30.0, 12.0, m); + let (cc, rc, r) = (Point::new(15.0, 30.0), 8.0, 20.0); + let found = tangent_circles(&[&ellipse, &circle(cc.x, cc.y, rc)], Some(r)).unwrap(); + let independent = independent_centers(exact, m * Point::ZERO, cc, rc, r); + assert!(!independent.is_empty()); + same_centers(&found, &independent, 0.05); +} + +#[test] +fn two_centers_close_together_are_both_found() { + // An ellipse 20 × 10 about (100, 0) and a circle of radius 10 about the origin: a circle of + // radius 35 fits the 70 pt gap between them on the axis. At 35.000003 two circles touch both + // from outside, about 0.011 pt above and below the axis. + let (ellipse, exact) = mapped_ellipse(20.0, 10.0, Affine::translate((100.0, 0.0))); + let (cc, rc, r) = (Point::ZERO, 10.0, 35.000003); + let found = tangent_circles(&[&ellipse, &circle(cc.x, cc.y, rc)], Some(r)).unwrap(); + let independent = independent_centers(exact, Point::new(100.0, 0.0), cc, rc, r); + assert_eq!(independent.iter().filter(|p| (p.x - 45.0).abs() < 1.0).count(), 2, "{independent:?}"); + same_centers(&found, &independent, 0.005); + // Two tiny circles a million points apart, and a radius just past half the gap: the two + // answers are about 22.36 pt above and below the axis, close together in units of the gap. + let (a, b) = (circle(0.0, 0.0, 0.01), circle(1e6, 0.0, 0.01)); + let found = tangent_circles(&[&a, &b], Some(499999.9905)).unwrap(); + assert_eq!(found.len(), 2, "{found:?}"); + for c in &found { + assert!((c.center.x - 5e5).abs() < 0.1 && (c.center.y.abs() - 500f64.sqrt()).abs() < 0.1, "{found:?}"); + } +} + +#[test] +fn three_circles_give_eight_distinct_circles_in_a_steady_order() { + // Mirror-image pairs about y = 0 have radii equal up to rounding: the upper one comes first. + let defs = [(0.0, -5.0, 1.0), (0.0, 5.0, 1.0), (12.0, 0.0, 2.0)]; + let shapes = defs.map(|(x, y, r)| circle(x, y, r)); + let found = tangent_circles(&[&shapes[0], &shapes[1], &shapes[2]], None).unwrap(); + for (i, a) in found.iter().enumerate() { + for b in &found[i + 1..] { + assert!((a.center - b.center).hypot() + (a.radius - b.radius).abs() > 1e-3, "{a:?} twice in {found:?}"); + } + } + for w in found.windows(2) { + if (w[0].radius - w[1].radius).abs() <= 1e-9 { + assert!(w[0].center.y < w[1].center.y, "{found:?}"); + } + } + // The selection mirrored left to right: the same circles mirrored, in the same order. + let flip = Affine::scale_non_uniform(-1.0, 1.0); + let mirrored = shapes.clone().map(|s| s.transformed(flip)); + let again = tangent_circles(&[&mirrored[0], &mirrored[1], &mirrored[2]], None).unwrap(); + assert_eq!(again.len(), found.len()); + for (a, b) in found.iter().zip(&again) { + assert!((flip * a.center - b.center).hypot() <= 1e-6 && (a.radius - b.radius).abs() <= 1e-6, "{found:?} vs {again:?}"); + } +} + +#[test] +fn radii_equal_up_to_rounding_sort_top_to_bottom() { + let lower = Circle { center: Point::new(0.0, 0.2), radius: 0.1 }; + let upper = Circle { center: Point::new(0.0, -0.2), radius: 0.1 + 1e-13 }; + let wider = Circle { center: Point::new(0.0, -0.5), radius: 0.2 }; + let mut v = [wider, lower, upper]; + sort(&mut v, SAME); + assert_eq!(v, [upper, lower, wider]); +} + +#[test] +fn the_nearest_point_is_looked_for_on_every_segment_it_may_be_on() { + // An arc bulging to y = −0.3 whose one chord lies on y = 0, and a line on y = −0.25. Seen from + // (0, −1), the line's chord is nearer (0.75 against 1.0), but the arc itself is (0.7). + let arc = CubicBez::new((-1.0, 0.0), (-1.0, -0.4), (1.0, -0.4), (1.0, 0.0)); + let line = CubicBez::new((-0.5, -0.25), (-0.2, -0.25), (0.2, -0.25), (0.5, -0.25)); + let outline = Outline { + segments: vec![arc, line], + beside: vec![(None, None), (None, None)], + chords: vec![(arc.p0, arc.p3, 0, 0.0, 1.0), (line.p0, line.p3, 1, 0.0, 1.0)], + slack: 0.3, + }; + let (p, d) = outline.extreme(Point::new(0.0, -1.0), false); + assert!((d - 0.7).abs() <= 1e-9 && (p - Point::new(0.0, -0.3)).hypot() <= 1e-9, "{p:?} {d}"); +} + +#[test] +fn copies_among_three_shapes_are_a_whole_family() { + use TangentCircleError::*; + // A circle turned and turned back differs from itself by rounding only. + let b = circle(3.0, 7.0, 20.0); + let turned = b.transformed(Affine::rotate(0.3)).transformed(Affine::rotate(-0.3)); + assert_ne!(b, turned); + assert_eq!(tangent_circles(&[&b, &turned, &circle(100.0, 0.0, 5.0)], None), Err(TooMany)); + // Two copies of a square. + let sq = square(0.0, 0.0, 10.0); + assert_eq!(tangent_circles(&[&sq, &sq.clone(), &square(60.0, 0.0, 10.0)], None), Err(TooMany)); + // Two circles half a point apart, a million points from the third, are not copies. + let far = [circle(0.0, 0.0, 10.0), circle(0.0, 0.5, 10.0), circle(1e6, 0.0, 10.0)]; + assert_ne!(tangent_circles(&[&far[0], &far[1], &far[2]], None), Err(TooMany)); +} + +#[test] +fn three_squares_are_solved_numerically() { + let shapes = [square(0.0, 0.0, 10.0), square(60.0, 0.0, 10.0), square(30.0, 50.0, 10.0)]; + let found = tangent_circles(&[&shapes[0], &shapes[1], &shapes[2]], None).unwrap(); + assert!(!found.is_empty()); + let dense: Vec<Vec<Point>> = shapes.iter().map(|s| samples(s, 4000)).collect(); + for c in &found { + for pts in &dense { + assert!(touches(c, pts, 0.01), "{c:?}"); + } + } + // By symmetry, the circle in the middle touching all three from outside is centered on x = 30. + let inner = found.iter().find(|c| (c.center.x - 30.0).abs() < 1e-6 && c.center.y > 0.0 && c.center.y < 40.0); + assert!(inner.is_some(), "{found:?}"); +} + +#[test] +fn compound_and_far_off_paths_give_the_same_circles_moved() { + // A ring (two subpaths of one path) and a small square in its hole. + let mut ring = circle(0.0, 0.0, 50.0); + ring.subpaths.extend(circle(0.0, 0.0, 30.0).subpaths); + let dot = square(0.0, 0.0, 5.0); + // Radius 12: in the hole 18 from the center, and 12 from a corner of the square: two by each + // corner. + let found = tangent_circles(&[&ring, &dot], Some(12.0)).unwrap(); + assert_eq!(found.len(), 8, "{found:?}"); + let (ring_pts, dot_pts) = (samples(&ring, 4000), samples(&dot, 4000)); + for c in &found { + assert!(touches(c, &ring_pts, 0.02) && touches(c, &dot_pts, 0.02), "{c:?}"); + } + // Moved far off and scaled: the same circles, moved and scaled. + let m = Affine::translate((1e6, -2e6)) * Affine::scale(3.0); + let (ring2, dot2) = (ring.transformed(m), dot.transformed(m)); + let moved = tangent_circles(&[&ring2, &dot2], Some(36.0)).unwrap(); + assert_eq!(moved.len(), found.len(), "{moved:?} vs {found:?}"); + for c in &found { + assert!(has(&moved, m * c.center, 3.0 * c.radius, 1e-4), "{c:?}"); + } +} + +#[test] +fn open_paths_and_no_answer() { + let line = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0)], false)); + let disc = circle(50.0, 40.0, 10.0); + // Radius 10: a center 10 from the line is at least 30 from the disc's center, never 20. + assert_eq!(tangent_circles(&[&line, &disc], Some(10.0)).unwrap(), vec![]); + // Radius 20: centers on y = 20, 30 from (50, 40): x = 50 ± √500. + let found = tangent_circles(&[&line, &disc], Some(20.0)).unwrap(); + assert_eq!(found.len(), 2, "{found:?}"); + let dx = 500f64.sqrt(); + assert!(has(&found, Point::new(50.0 - dx, 20.0), 20.0, 0.05) && has(&found, Point::new(50.0 + dx, 20.0), 20.0, 0.05), "{found:?}"); + // A given radius far past 64 × the bounds' diagonal: two short segments 10 apart and radius + // 1000 (the limit applies only when three shapes set the radius). + let left = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(1.0, 0.0)], false)); + let right = PathData::single(SubPath::polyline(&[Point::new(10.0, 0.0), Point::new(11.0, 0.0)], false)); + let found = tangent_circles(&[&left, &right], Some(1000.0)).unwrap(); + assert!(!found.is_empty()); + let (lp, rp) = (samples(&left, 4000), samples(&right, 4000)); + for c in &found { + assert!(c.radius == 1000.0 && touches(c, &lp, 1e-3) && touches(c, &rp, 1e-3), "{c:?}"); + } + // Two squares far apart with a small radius: none. + let (a, b) = (square(0.0, 0.0, 10.0), square(500.0, 0.0, 10.0)); + assert_eq!(tangent_circles(&[&a, &b], Some(5.0)).unwrap(), vec![]); +} + +#[test] +fn whole_curves_of_answers_and_bad_input_are_errors() { + use TangentCircleError::*; + let (a, b) = (circle(0.0, 0.0, 50.0), circle(0.0, 0.0, 20.0)); + assert_eq!(tangent_circles(&[&a, &b], Some(15.0)), Err(TooMany)); + let (outer, inner) = (square(0.0, 0.0, 50.0), square(0.0, 0.0, 20.0)); + assert_eq!(tangent_circles(&[&outer, &inner], Some(15.0)), Err(TooMany)); + assert_eq!(tangent_circles(&[&a], Some(1.0)), Err(BadInput)); + assert_eq!(tangent_circles(&[&a, &b], None), Err(BadInput)); + assert_eq!(tangent_circles(&[&a, &b, &a], Some(1.0)), Err(BadInput)); + assert_eq!(tangent_circles(&[&a, &b], Some(0.0)), Err(BadInput)); + assert_eq!(tangent_circles(&[&a, &b], Some(f64::NAN)), Err(BadInput)); + // Two of three circles the same: a whole family touches all three. + let third = circle(100.0, 0.0, 5.0); + assert_eq!(tangent_circles(&[&b, &b.clone(), &third], None), Err(TooMany)); + let mut reversed = b.clone(); + reversed.reverse(); + assert_eq!(tangent_circles(&[&b, &reversed, &third], None), Err(TooMany)); + // Shapes so tiny that the radius overflows in their units. + let (tiny_a, tiny_b) = (circle(0.0, 0.0, 1e-305), circle(1e-304, 0.0, 1e-305)); + assert_eq!(tangent_circles(&[&tiny_a, &tiny_b], Some(1e6)), Err(BadInput)); + let empty = PathData::new(vec![]); + assert_eq!(tangent_circles(&[&a, &empty], Some(1.0)), Err(BadInput)); + let big = PathData::single(SubPath::polyline(&(0..2001).map(|i| Point::new(i as f64, (i % 2) as f64)).collect::<Vec<_>>(), false)); + assert_eq!(tangent_circles(&[&a, &big], Some(1.0)), Err(TooComplex)); + // Lone anchors count as segments. + let dots = PathData::new((0..2001).map(|i| SubPath::polyline(&[Point::new(i as f64, 0.0)], false)).collect()); + assert_eq!(tangent_circle_segments(&dots), 2001); + assert_eq!(tangent_circles(&[&a, &dots], Some(1.0)), Err(TooComplex)); +} + +#[test] +fn answers_about_a_tiny_shape_far_away_stay_apart() { + // Each tiny circle is touched from outside and from inside: answers 0.02 pt apart on each side, + // eight in all. + let (a, b) = (circle(0.0, 0.0, 0.01), circle(1e6, 0.0, 0.01)); + let found = tangent_circles(&[&a, &b], Some(1e6)).unwrap(); + assert_eq!(found.len(), 8, "{found:?}"); + // All of one radius: top to bottom, then left to right. + for w in found.windows(2) { + let (a, b) = (w[0].center, w[1].center); + assert!(a.y < b.y - 1e-3 || ((a.y - b.y).abs() <= 1e-3 && a.x < b.x), "{found:?}"); + } +} diff --git a/crates/pathops/src/addons/pathtools/tangents.rs b/crates/pathops/src/addons/pathtools/tangents.rs new file mode 100644 index 0000000000..a42e628cad --- /dev/null +++ b/crates/pathops/src/addons/pathtools/tangents.rs @@ -0,0 +1,1019 @@ +//! Common Tangents: the straight lines that touch two convex closed outlines (ellipses at any +//! rotation and scale, and convex Bézier paths) without crossing into either. An external tangent +//! has both outlines on the same side of it; an internal one runs between them. +//! +//! A line with unit normal `n` touches an outline from outside where `p · n` reaches the +//! outline's support value `h(n)`, the largest `p · n` over its points. External tangents are the +//! normals where both outlines have the same support value, internal ones where `h₁(n) = -h₂(-n)`. +//! Both are found as roots over the normal's angle: sampled, then refined by bisection, with +//! sampled minima refined too so that a double root (outlines that touch) or two roots between +//! neighboring samples are kept. + +use std::f64::consts::TAU; + +use kurbo::{Affine, CubicBez, ParamCurve, Point, Vec2}; +use vectorcraft_geom::SubPath; + +/// Most segments one outline may have. +pub const MAX_TANGENT_SEGMENTS: usize = 10_000; +/// Normal directions sampled around the circle before refining. +const SAMPLES: usize = 720; +/// Steps of bisection or golden-section search for each root. +const STEPS: usize = 64; +/// Straight pieces each segment is cut into to check that a path is convex and to find its center. +const FLATTEN: usize = 32; + +/// Which side of a tangent the two outlines lie on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TangentKind { + /// Both on the same side. + External, + /// One on each side. + Internal, +} + +/// One common tangent: the stretch of the line from where it touches the first outline to where +/// it touches the second. Where the outlines touch each other at one point, the stretch is +/// centered on that point and as long as the narrower outline is wide along the line, and `from` +/// is the end with the lower position along the line. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Tangent { + pub kind: TangentKind, + pub from: Point, + pub to: Point, +} + +/// Why [`Outline::convex`] or [`Outline::ellipse`] cannot take a shape. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OutlineError { + /// The path is open. + Open, + /// The path bends inward somewhere, or winds around more than once. + NotConvex, + /// No area, or not finite. + Empty, + /// More than [`MAX_TANGENT_SEGMENTS`] segments. + TooComplex, +} + +/// The two outlines are the same, so every line touching one touches the other. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Coincide; + +/// A convex closed outline that [`common_tangents`] takes. +#[derive(Clone, Debug)] +pub enum Outline { + /// The unit circle under an affine map: the center is the map's translation, `m` its linear + /// part (`[a, b, c, d]`, as kurbo orders them). + Ellipse { center: Point, m: [f64; 4] }, + /// A convex closed path's segments, its center of area and the diagonal of its bounds. `ccw` + /// when the segments run counter-clockwise (y up); the segment where `p · n` is largest then + /// comes later in the list as the angle of `n` grows. + Convex { segments: Vec<CubicBez>, center: Point, size: f64, ccw: bool }, +} + +impl Outline { + /// The ellipse that `unit` maps the unit circle onto. + pub fn ellipse(unit: Affine) -> Result<Self, OutlineError> { + let [a, b, c, d, e, f] = unit.as_coeffs(); + let norm = a.abs().max(b.abs()).max(c.abs()).max(d.abs()); + // The determinant is rounded by about `f64::EPSILON * norm²`; one no larger than that may + // belong to a map with no area. An ellipse whose determinant is larger is measured + // exactly. + if !unit.as_coeffs().iter().all(|v| v.is_finite()) || norm <= 0.0 || (a * d - b * c).abs() <= f64::EPSILON * norm * norm { + return Err(OutlineError::Empty); + } + Ok(Outline::Ellipse { center: Point::new(e, f), m: [a, b, c, d] }) + } + + /// A closed subpath that bends one way all around and winds around once. + pub fn convex(sp: &SubPath) -> Result<Self, OutlineError> { + if !sp.closed { + return Err(OutlineError::Open); + } + let n = sp.segment_count(); + if n > MAX_TANGENT_SEGMENTS { + return Err(OutlineError::TooComplex); + } + let segments: Vec<CubicBez> = (0..n).map(|k| sp.segment(k)).collect(); + let finite = |p: Point| p.x.is_finite() && p.y.is_finite(); + if segments.iter().any(|s| ![s.p0, s.p1, s.p2, s.p3].into_iter().all(finite)) { + return Err(OutlineError::Empty); + } + let mut pts: Vec<Point> = Vec::with_capacity(n * FLATTEN); + for s in &segments { + pts.extend((0..FLATTEN).map(|k| s.eval(k as f64 / FLATTEN as f64))); + } + let (lo, hi) = pts.iter().fold((Point::new(f64::MAX, f64::MAX), Point::new(f64::MIN, f64::MIN)), |(lo, hi), p| { + (Point::new(lo.x.min(p.x), lo.y.min(p.y)), Point::new(hi.x.max(p.x), hi.y.max(p.y))) + }); + let size = (hi - lo).hypot(); + if !size.is_finite() || size <= 0.0 { + return Err(OutlineError::Empty); + } + // Points closer than this to the one before are dropped: a retracted handle or a segment + // of no length gives no direction. + pts.dedup_by(|b, a| (*b - *a).hypot() <= 1e-9 * size); + while pts.len() > 1 && pts.first().zip(pts.last()).is_some_and(|(f, l)| (*f - *l).hypot() <= 1e-9 * size) { + pts.pop(); + } + let m = pts.len(); + if m < 3 { + return Err(OutlineError::Empty); + } + // Area, center and turns are worked out on the points taken about the first one and + // divided by the size. + let origin = pts[0].to_vec2(); + let unit: Vec<Vec2> = pts.iter().map(|p| (p.to_vec2() - origin) / size).collect(); + let (mut area2, mut cx, mut cy) = (0.0, 0.0, 0.0); + for i in 0..m { + let (p, q) = (unit[i], unit[(i + 1) % m]); + let cross = p.cross(q); + area2 += cross; + cx += (p.x + q.x) * cross; + cy += (p.y + q.y) * cross; + } + if area2.abs() <= 1e-12 { + return Err(OutlineError::Empty); + } + let sign = area2.signum(); + // Every turn the same way (straight runs allowed), and one turn in all. + let mut turning = 0.0; + for i in 0..m { + let (p, q, r) = (unit[(i + m - 1) % m], unit[i], unit[(i + 1) % m]); + let (u, v) = (q - p, r - q); + let cross = u.cross(v) * sign; + if cross < -1e-12 { + return Err(OutlineError::NotConvex); + } + turning += cross.atan2(u.dot(v)); + } + if (turning - TAU).abs() > 1e-6 { + return Err(OutlineError::NotConvex); + } + // A short bend the other way can lie between two of the points: each segment is checked + // whole. + if segments.iter().any(|s| bends_against(s, sign)) { + return Err(OutlineError::NotConvex); + } + // A corner can also turn inward between two of the points: each join is checked by the + // directions the segments leave and reach it in. Segments of no length are passed over. + let nonzero = |vs: [Vec2; 3]| vs.into_iter().find(|v| v.hypot() > 1e-9 * size).map(|v| v / v.hypot()); + let ends: Vec<(Vec2, Vec2)> = segments + .iter() + .filter_map(|s| nonzero([s.p1 - s.p0, s.p2 - s.p0, s.p3 - s.p0]).zip(nonzero([s.p3 - s.p2, s.p3 - s.p1, s.p3 - s.p0]))) + .collect(); + if ends.iter().enumerate().any(|(i, (_, end))| ends[(i + 1) % ends.len()].0.cross(*end) * sign > 1e-9) { + return Err(OutlineError::NotConvex); + } + let center = (Vec2::new(cx / (3.0 * area2), cy / (3.0 * area2)) * size + origin).to_point(); + if !center.x.is_finite() || !center.y.is_finite() { + return Err(OutlineError::Empty); + } + Ok(Outline::Convex { segments, center, size, ccw: sign > 0.0 }) + } + + /// The outline moved by `d`. + fn shifted(&self, d: Vec2) -> Self { + match self { + Outline::Ellipse { center, m } => Outline::Ellipse { center: *center + d, m: *m }, + Outline::Convex { segments, center, size, ccw } => Outline::Convex { + segments: segments.iter().map(|s| CubicBez::new(s.p0 + d, s.p1 + d, s.p2 + d, s.p3 + d)).collect(), + center: *center + d, + size: *size, + ccw: *ccw, + }, + } + } + + /// Adds to `out` the normal angles where the point of largest `p · n` can pass from one + /// segment to the next: square to each segment's direction at its ends, on both sides. + fn breaks(&self, out: &mut Vec<f64>) { + let Outline::Convex { segments, .. } = self else { return }; + let nonzero = |vs: [Vec2; 3]| vs.into_iter().find(|v| v.hypot2() > 0.0); + for s in segments { + let ends = [nonzero([s.p1 - s.p0, s.p2 - s.p0, s.p3 - s.p0]), nonzero([s.p3 - s.p2, s.p3 - s.p1, s.p3 - s.p0])]; + for d in ends.into_iter().flatten() { + let a = d.y.atan2(d.x); + out.extend([a + TAU / 4.0, a - TAU / 4.0]); + } + } + } + + /// The support value at `n` and the segment it is reached on, from every segment. + fn support_scan(&self, n: Vec2) -> (f64, usize) { + match self { + Outline::Ellipse { .. } => (self.support(n), 0), + Outline::Convex { segments, .. } => { + let mut best = (f64::MIN, 0); + for (i, s) in segments.iter().enumerate() { + each_extreme(s, n, |_, v| { + if v > best.0 { + best = (v, i); + } + }); + } + best + } + } + } + + /// The support value at `n` and the segment it is reached on, walking on from segment `from`, + /// where the support value was reached at a normal angle a little less than `n`'s. + fn support_from(&self, n: Vec2, from: usize) -> (f64, usize) { + match self { + Outline::Ellipse { .. } => (self.support(n), 0), + Outline::Convex { segments, ccw, .. } => { + let len = segments.len(); + if len == 0 { + return (f64::MIN, 0); + } + let step = if *ccw { 1 } else { len - 1 }; + let value = |i: usize| { + let mut best = f64::MIN; + if let Some(s) = segments.get(i) { + each_extreme(s, n, |_, v| best = best.max(v)); + } + best + }; + let mut i = from % len; + let mut v = value(i); + for _ in 0..len { + let j = (i + step) % len; + let w = value(j); + if w < v { + break; + } + (i, v) = (j, w); + } + (v, i) + } + } + } + + /// The center: an ellipse's, or a path's center of area. + pub fn center(&self) -> Point { + match self { + Outline::Ellipse { center, .. } | Outline::Convex { center, .. } => *center, + } + } + + /// The diagonal of the bounds (an ellipse's: of the box its axes span). + pub fn size(&self) -> f64 { + match self { + Outline::Ellipse { m, .. } => { + let [a, b, c, d] = *m; + 2.0 * (a.hypot(c).powi(2) + b.hypot(d).powi(2)).sqrt() + } + Outline::Convex { size, .. } => *size, + } + } + + /// The support value: the largest `p · n` over the outline's points. + fn support(&self, n: Vec2) -> f64 { + match self { + Outline::Ellipse { center, m: [a, b, c, d] } => center.to_vec2().dot(n) + Vec2::new(a * n.x + b * n.y, c * n.x + d * n.y).hypot(), + Outline::Convex { segments, .. } => { + let mut best = f64::MIN; + for s in segments { + each_extreme(s, n, |_, v| best = best.max(v)); + } + best + } + } + } + + /// The points of the outline on the line `p · n = h`, its support value, which is reached on + /// segment `at`: the point where `p · n` is largest, and the ends of any straight side along + /// the line. Another point counts when it lies within `tol` of the line plus `slope` times its + /// distance from that largest point, where `slope` is how far off the normal's angle may be. + /// On a convex outline the points that count form one run around the largest one, so the + /// segments are measured from `at` outward both ways until a segment's end does not count. + fn touching(&self, n: Vec2, h: f64, tol: f64, slope: f64, at: usize) -> Vec<Point> { + match self { + Outline::Ellipse { center, m: [a, b, c, d] } => { + let w = Vec2::new(a * n.x + b * n.y, c * n.x + d * n.y); + let w = w / w.hypot(); + vec![*center + Vec2::new(a * w.x + c * w.y, b * w.x + d * w.y)] + } + Outline::Convex { segments, .. } => { + let len = segments.len(); + let mut all = vec![]; + let Some(first) = segments.get(at % len.max(1)) else { return vec![] }; + each_extreme(first, n, |p, v| all.push((p, v))); + let Some(&(peak, _)) = all.iter().max_by(|x, y| x.1.total_cmp(&y.1)) else { return vec![] }; + let counts = |p: Point| h - p.to_vec2().dot(n) <= tol + slope * (p - peak).hypot(); + let mut ahead = 0; + for j in 1..len { + match segments.get((at + j) % len) { + Some(s) if counts(s.p0) => each_extreme(s, n, |p, v| all.push((p, v))), + _ => break, + } + ahead = j; + } + for j in 1..len - ahead { + match segments.get((at + len - j) % len) { + Some(s) if counts(s.p3) => each_extreme(s, n, |p, v| all.push((p, v))), + _ => break, + } + } + let Some(&(peak, _)) = all.iter().max_by(|x, y| x.1.total_cmp(&y.1)) else { return vec![] }; + all.into_iter().filter(|(p, v)| h - v <= tol + slope * (*p - peak).hypot()).map(|(p, _)| p).collect() + } + } + } +} + +/// Whether cubic `s` bends against `sign` (the way its outline turns) anywhere. The cross product +/// of its first and second derivatives is a quadratic in t; its lowest value on [0, 1] is compared +/// with the segment's control polygon length squared. +fn bends_against(s: &CubicBez, sign: f64) -> bool { + let (a, b, c) = (s.p1 - s.p0, s.p2 - s.p1, s.p3 - s.p2); + let q = |t: f64| { + let u = 1.0 - t; + let d1 = a * (u * u) + b * (2.0 * u * t) + c * (t * t); + let d2 = (b - a) * u + (c - b) * t; + d1.cross(d2) * sign + }; + let (q0, half, q1) = (q(0.0), q(0.5), q(1.0)); + // q(t) = q0 + k1 t + k2 t². + let k2 = 2.0 * (q0 + q1 - 2.0 * half); + let k1 = q1 - q0 - k2; + let mut low = q0.min(q1); + if k2 > 0.0 { + let t = -k1 / (2.0 * k2); + if t > 0.0 && t < 1.0 { + low = low.min(q(t)); + } + } + let scale = (a.hypot() + b.hypot() + c.hypot()).powi(2); + low < -1e-9 * scale +} + +#[cfg(test)] +thread_local! { + /// How many times [`each_extreme`] has measured a segment on this thread, for the tests. + static EXTREMES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; +} + +/// Calls `f` with each point of `s` where `p · n` can be largest (its ends and the places where +/// the curve runs square to `n`) and the value there. +fn each_extreme(s: &CubicBez, n: Vec2, mut f: impl FnMut(Point, f64)) { + #[cfg(test)] + EXTREMES.with(|n| n.set(n.get() + 1)); + let [v0, v1, v2, v3] = [s.p0, s.p1, s.p2, s.p3].map(|p| p.to_vec2().dot(n)); + f(s.p0, v0); + f(s.p3, v3); + // The derivative of p(t) · n, divided by 3: a quadratic in t. + let (d0, d1, d2) = (v1 - v0, v2 - v1, v3 - v2); + let (qa, qb, qc) = (d0 - 2.0 * d1 + d2, 2.0 * (d1 - d0), d0); + let mut root = |t: f64| { + if t > 0.0 && t < 1.0 { + let p = s.eval(t); + f(p, p.to_vec2().dot(n)); + } + }; + let scale = qa.abs().max(qb.abs()).max(qc.abs()); + if !scale.is_finite() || scale <= 0.0 { + return; + } + if qa.abs() <= 1e-12 * scale { + if qb != 0.0 { + root(-qc / qb); + } + return; + } + let disc = qb * qb - 4.0 * qa * qc; + if disc < 0.0 { + return; + } + // The stable form of the two roots; with `qb` zero the sign is taken as positive, so `q` is + // not zero. + let sign = if qb < 0.0 { -1.0 } else { 1.0 }; + let q = -0.5 * (qb + sign * disc.sqrt()); + root(q / qa); + if q != 0.0 { + root(qc / q); + } +} + +/// The unit vector at `angle` radians. +fn dir(angle: f64) -> Vec2 { + Vec2::new(angle.cos(), angle.sin()) +} + +/// The common tangents of `a` and `b`: the external ones, then the internal ones, each in order of +/// the angle of its normal. Separate outlines have two of each; overlapping ones only external +/// ones (two for ellipses, possibly more for paths whose outlines cross more often); one inside the +/// other none; outlines that touch share one tangent where they touch. +pub fn common_tangents(a: &Outline, b: &Outline) -> Result<Vec<Tangent>, Coincide> { + // Worked out about the point between the two centers. + let origin = (a.center().to_vec2() + b.center().to_vec2()) / 2.0; + let (a, b) = (&a.shifted(-origin), &b.shifted(-origin)); + let size = a.size().max(b.size()).max((a.center() - b.center()).hypot()); + let tol = 1e-9 * size; + // The normal angles sampled: evenly spaced ones, and every angle where the support value of + // either outline passes to another segment. Between two neighboring samples each outline is + // then touched on one segment. + let mut at: Vec<f64> = (0..SAMPLES).map(|k| k as f64 * TAU / SAMPLES as f64).collect(); + a.breaks(&mut at); + b.breaks(&mut at); + let mut at: Vec<f64> = at.into_iter().map(|t| t.rem_euclid(TAU)).map(|t| if t < TAU { t } else { 0.0 }).collect(); + at.sort_by(f64::total_cmp); + at.dedup_by(|y, x| *y - *x <= 1e-12); + // The segment each outline is touched on at each sample, found by walking around once. + let hints = |o: &Outline, sign: f64| -> Vec<usize> { + let mut out = Vec::with_capacity(at.len()); + let mut i = at.first().map_or(0, |t| o.support_scan(dir(*t) * sign).1); + for t in &at { + i = o.support_from(dir(*t) * sign, i).1; + out.push(i); + } + out + }; + let (ha, hb, hb_back) = (hints(a, 1.0), hints(b, 1.0), hints(b, -1.0)); + let hint = |h: &[usize], k: usize| h.get(k).copied().unwrap_or(0); + let external = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 - b.support_from(dir(t), hint(&hb, k)).0, tol)?; + let internal = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 + b.support_from(-dir(t), hint(&hb_back, k)).0, tol)?; + let (a, b) = (Hinted { o: a, at: &at, hints: &ha }, Hinted { o: b, at: &at, hints: &hb }); + let mut out = Vec::with_capacity(external.len() + internal.len()); + for (kind, list) in [(TangentKind::External, external), (TangentKind::Internal, internal)] { + for root in list { + let t = tangent_at(&a, &b, kind, root.angle, root.double, size); + out.push(Tangent { from: t.from + origin, to: t.to + origin, ..t }); + } + } + Ok(out) +} + +/// A zero of a support-value difference: the normal's angle, and whether the difference only +/// touches zero there (outlines that touch) rather than crossing it. +#[derive(Clone, Copy, Debug)] +struct Root { + angle: f64, + double: bool, +} + +/// An outline with the segment it is touched on at each sampled normal angle. +struct Hinted<'a> { + o: &'a Outline, + at: &'a [f64], + hints: &'a [usize], +} + +impl Hinted<'_> { + /// The support value at the normal angle `angle` and the segment it is reached on, walking on + /// from the segment of the sample at or before `angle`. + fn support(&self, angle: f64) -> (f64, usize) { + let angle = angle.rem_euclid(TAU); + // Before the first sample, the last one (taken 2π back) comes before `angle`. + let k = self.at.partition_point(|t| *t <= angle).checked_sub(1).unwrap_or(self.at.len().saturating_sub(1)); + self.o.support_from(dir(angle), self.hints.get(k).copied().unwrap_or(0)) + } +} + +/// The tangent of `kind` whose normal is at `angle`: `a` lies where `p · n` is at most the line's +/// value, and `b` on the same side (external) or the other side (internal). `double` when the +/// outlines touch there. +fn tangent_at(a: &Hinted, b: &Hinted, kind: TangentKind, angle: f64, double: bool, size: f64) -> Tangent { + let n = dir(angle); + // The rounding allowed in `p · n` grows with each outline's own size and its distance from the + // origin. + let rounding = |o: &Outline| 1e-12 * o.size() + 1e-14 * (o.center().to_vec2().hypot() + o.size()); + let (tol_a, tol_b) = (rounding(a.o), rounding(b.o)); + // Bisection finds a simple root's angle to about the rounding of the support values; the + // golden-section search finds a double root's to about 1e-8 radians. + let slope = if double { 1e-7 } else { 1e-10 }; + let (ha, sa) = a.support(angle); + let on_a = a.o.touching(n, ha, tol_a, slope, sa); + let on_b = match kind { + TangentKind::External => { + let (hb, sb) = b.support(angle); + b.o.touching(n, hb, tol_b, slope, sb) + } + TangentKind::Internal => { + let (hb, sb) = b.support(angle + TAU / 2.0); + b.o.touching(-n, hb, tol_b, slope, sb) + } + }; + // Positions along the line, which runs square to `n` through `n * ha`. + let t = Vec2::new(-n.y, n.x); + let along = |p: &Point| p.to_vec2().dot(t); + let mean = |v: &[Point]| v.iter().map(along).sum::<f64>() / v.len().max(1) as f64; + let all = on_a.iter().chain(&on_b).map(along); + let (lo, hi) = all.fold((f64::MAX, f64::MIN), |(lo, hi), s| (lo.min(s), hi.max(s))); + let at = |s: f64| (n * ha + t * s).to_point(); + // A double root's angle is found less exactly than a simple one's, so touching points may + // stand a little apart. + let (from, to) = if double && hi - lo <= 1e-6 * size { + // Touching at one point: the narrower outline's width along the line, centered there. + let width = [a, b].map(|o| o.support(angle + TAU / 4.0).0 + o.support(angle - TAU / 4.0).0).into_iter().fold(f64::MAX, f64::min); + let mid = (lo + hi) / 2.0; + (mid - width / 2.0, mid + width / 2.0) + } else if mean(&on_a) <= mean(&on_b) { + (lo, hi) + } else { + (hi, lo) + }; + Tangent { kind, from: at(from), to: at(to) } +} + +/// The angles in `[0, 2π)` where `f` (periodic) is zero, within `tol`. An interval where it stays +/// zero (outlines that meet at a corner or along a shared stretch) gives the angle at its middle, +/// as a double root. +/// +/// `at` holds the sampled angles in increasing order, in `[0, 2π)`; `f(t, k)` is `f` at an angle +/// `t` at or after sample `k` and before the sample two on. +fn roots(at: &[f64], f: &dyn Fn(f64, usize) -> f64, tol: f64) -> Result<Vec<Root>, Coincide> { + let n = at.len(); + if n < 3 { + return Err(Coincide); + } + // The angle of sample `k + j`, counted on from sample `k` past 2π. + let ang = |k: usize, j: usize| at.get((k + j) % n).copied().unwrap_or(0.0) + TAU * ((k + j) / n) as f64; + let v: Vec<f64> = (0..n).map(|k| f(ang(k, 0), k)).collect(); + let val = |k: usize| v.get(k % n).copied().unwrap_or(0.0); + let zero = |x: f64| x.abs() <= tol; + let Some(start) = v.iter().position(|x| !zero(*x)) else { return Err(Coincide) }; + let simple = |angle: f64| Root { angle, double: false }; + let mut out = vec![]; + // Between `lo` (sample `k`) and `hi`, where `s * f` is positive at both ends: the least of + // `s * f`, a double root where it reaches zero, two roots where it goes past it, none where it + // stays above. + let dip = |out: &mut Vec<Root>, s: f64, k: usize, lo: f64, hi: f64| { + let g = |t: f64| f(t, k); + let (t, least) = golden(&|t| s * g(t), lo, hi); + if least < -tol { + out.push(simple(bisect(&g, lo, t))); + out.push(simple(bisect(&g, t, hi))); + } else if least <= tol { + out.push(Root { angle: t, double: true }); + } + }; + for i in 0..n { + let k = (start + i) % n; + let (prev, next) = ((k + n - 1) % n, k + 1); + let theta = ang(k, 0); + if zero(val(k)) { + continue; + } + if zero(val(next)) { + let len = (1..n).take_while(|j| zero(val(k + j))).count(); + if len == 1 { + // One sample on zero: a crossing when the samples beside it differ in sign, else a + // dip between them. + let (lo, hi) = (theta, ang(k, 2)); + let s = val(k).signum(); + if val(k + 2).signum() == s { + dip(&mut out, s, k, lo, hi); + } else { + out.push(simple(bisect(&|t| f(t, k), lo, hi))); + } + } else { + out.push(Root { angle: (ang(k, 1) + ang(k, len)) / 2.0, double: true }); + } + continue; + } + if val(k).signum() != val(next).signum() { + out.push(simple(bisect(&|t| f(t, k), theta, ang(k, 1)))); + continue; + } + // A sampled minimum of |f|: the curve may dip to zero (a double root), or across it and + // back (two roots), between the neighboring samples. + let (vp, vk, vn) = (val(prev), val(k), val(next)); + if !zero(vp) && vp.signum() == vk.signum() && vk.abs() < vp.abs() && vk.abs() <= vn.abs() { + let lo = if k == 0 { ang(prev, 0) - TAU } else { ang(prev, 0) }; + dip(&mut out, vk.signum(), prev, lo, ang(k, 1)); + } + } + let mut out: Vec<Root> = out.into_iter().map(|r| Root { angle: r.angle.rem_euclid(TAU), ..r }).collect(); + out.sort_by(|a, b| a.angle.total_cmp(&b.angle)); + out.dedup_by(|b, a| { + let same = (b.angle - a.angle).abs() < 1e-7; + a.double |= same && b.double; + same + }); + if out.len() > 1 + && out.first().zip(out.last()).is_some_and(|(f, l)| f.angle + TAU - l.angle < 1e-7) + && let Some(last) = out.pop() + && let Some(first) = out.first_mut() + { + first.double |= last.double; + } + Ok(out) +} + +/// A root of `f` between `lo` and `hi`, where it has opposite signs. +fn bisect(f: &dyn Fn(f64) -> f64, mut lo: f64, mut hi: f64) -> f64 { + let s = f(lo).signum(); + for _ in 0..STEPS { + let mid = (lo + hi) / 2.0; + if f(mid).signum() == s { + lo = mid; + } else { + hi = mid; + } + } + (lo + hi) / 2.0 +} + +/// Where `g` is least between `lo` and `hi` (taken as having one minimum there), and its value. +fn golden(g: &dyn Fn(f64) -> f64, mut lo: f64, mut hi: f64) -> (f64, f64) { + let r = (5f64.sqrt() - 1.0) / 2.0; + let (mut x1, mut x2) = (hi - r * (hi - lo), lo + r * (hi - lo)); + let (mut g1, mut g2) = (g(x1), g(x2)); + for _ in 0..STEPS { + if g1 < g2 { + hi = x2; + (x2, g2) = (x1, g1); + x1 = hi - r * (hi - lo); + g1 = g(x1); + } else { + lo = x1; + (x1, g1) = (x2, g2); + x2 = lo + r * (hi - lo); + g2 = g(x2); + } + } + let t = (lo + hi) / 2.0; + (t, g(t)) +} + +#[cfg(test)] +mod tests { + use std::cell::Cell; + + use kurbo::Rect; + use vectorcraft_geom::shapes; + + use super::*; + + fn circle(cx: f64, cy: f64, r: f64) -> Outline { + Outline::ellipse(Affine::new([r, 0.0, 0.0, r, cx, cy])).unwrap() + } + + /// An ellipse with semi-axes `rx`, `ry`, turned `deg` degrees, centered at (`cx`, `cy`). + fn ellipse_map(cx: f64, cy: f64, rx: f64, ry: f64, deg: f64) -> Affine { + Affine::translate((cx, cy)) * Affine::rotate(deg.to_radians()) * Affine::scale_non_uniform(rx, ry) + } + + /// Whether `t` has its two ends at `p` and `q`, in either order. + fn ends_at(t: &Tangent, p: Point, q: Point) -> bool { + ends_within(t, p, q, 1e-7) + } + + /// [`ends_at`] within `eps`: the angle of a tangent where outlines touch (a double root) is + /// found to about 1e-8 radians. + fn ends_within(t: &Tangent, p: Point, q: Point, eps: f64) -> bool { + let near = |a: Point, b: Point| (a - b).hypot() < eps; + (near(t.from, p) && near(t.to, q)) || (near(t.from, q) && near(t.to, p)) + } + + /// Checks `t` against dense samples of the two outlines, without support values: each lies on + /// one side of the line (the same side for an external tangent, opposite ones for an internal + /// one) and comes within `eps` of it. + fn check_against_samples(t: &Tangent, a: &[Point], b: &[Point], eps: f64) { + let d = t.to - t.from; + let n = Vec2::new(-d.y, d.x) / d.hypot(); + let side = |pts: &[Point]| { + let dist: Vec<f64> = pts.iter().map(|p| (*p - t.from).dot(n)).collect(); + let (lo, hi) = dist.iter().fold((f64::MAX, f64::MIN), |(lo, hi), s| (lo.min(*s), hi.max(*s))); + assert!(lo > -eps || hi < eps, "the line crosses the outline: {lo} .. {hi} ({t:?})"); + assert!(lo.abs() < eps || hi.abs() < eps, "the line misses the outline: {lo} .. {hi} ({t:?})"); + if hi < eps { -1.0 } else { 1.0 } + }; + let (sa, sb) = (side(a), side(b)); + match t.kind { + TangentKind::External => assert_eq!(sa, sb, "{t:?}"), + TangentKind::Internal => assert_ne!(sa, sb, "{t:?}"), + } + } + + fn sample_ellipse(m: Affine, count: usize) -> Vec<Point> { + (0..count).map(|k| m * Point::new((TAU * k as f64 / count as f64).cos(), (TAU * k as f64 / count as f64).sin())).collect() + } + + fn sample_path(sp: &SubPath, per_segment: usize) -> Vec<Point> { + (0..sp.segment_count()).flat_map(|k| (0..per_segment).map(move |j| sp.segment(k).eval(j as f64 / per_segment as f64))).collect() + } + + #[test] + fn two_circles_have_four_tangents_at_the_closed_form_points() { + let (c1, r1, c2, r2) = (Point::new(0.0, 0.0), 10.0, Point::new(100.0, 0.0), 20.0); + let all = common_tangents(&circle(c1.x, c1.y, r1), &circle(c2.x, c2.y, r2)).unwrap(); + assert_eq!(all.len(), 4, "{all:?}"); + // External: (c1 - c2) · n = r2 - r1, so n.x = -0.1; the points are c + r n on each. + // Internal: (c1 - c2) · n = -(r1 + r2), so n.x = 0.3; c1 + r1 n and c2 - r2 n. + for (kind, nx) in [(TangentKind::External, -0.1f64), (TangentKind::Internal, 0.3)] { + for sy in [1.0, -1.0] { + let n = Vec2::new(nx, sy * (1.0 - nx * nx).sqrt()); + let far = if kind == TangentKind::External { c2 + n * r2 } else { c2 - n * r2 }; + let found = all.iter().filter(|t| t.kind == kind && ends_at(t, c1 + n * r1, far)).count(); + assert_eq!(found, 1, "{kind:?} {n:?} in {all:?}"); + } + } + // Each runs from the first outline to the second. + assert!(all.iter().all(|t| (t.from - c1).hypot() < (t.to - c1).hypot())); + } + + #[test] + fn turned_ellipses_match_an_independent_numeric_solution() { + let (ma, mb) = (ellipse_map(0.0, 0.0, 40.0, 15.0, 30.0), ellipse_map(150.0, 60.0, 25.0, 60.0, -70.0)); + let all = common_tangents(&Outline::ellipse(ma).unwrap(), &Outline::ellipse(mb).unwrap()).unwrap(); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{all:?}"); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{all:?}"); + let (sa, sb) = (sample_ellipse(ma, 5_000), sample_ellipse(mb, 5_000)); + for t in &all { + check_against_samples(t, &sa, &sb, 1e-3); + } + // A brute-force scan of the normal's angle with support values read off the samples finds + // the same normals. + let support = |pts: &[Point], n: Vec2| pts.iter().map(|p| p.to_vec2().dot(n)).fold(f64::MIN, f64::max); + let scan = |f: &dyn Fn(Vec2) -> f64| { + let steps = 7_200; + let g = |k: usize| f(dir(TAU * k as f64 / steps as f64)); + (0..steps).filter(|&k| g(k).signum() != g((k + 1) % steps).signum()).map(|k| TAU * (k as f64 + 0.5) / steps as f64).collect::<Vec<_>>() + }; + let ext = scan(&|n| support(&sa, n) - support(&sb, n)); + let int = scan(&|n| support(&sa, n) + support(&sb, -n)); + for (kind, expected) in [(TangentKind::External, ext), (TangentKind::Internal, int)] { + assert_eq!(expected.len(), 2); + for angle in expected { + let n = dir(angle); + let hit = all.iter().filter(|t| t.kind == kind).any(|t| { + let d = t.to - t.from; + let m = Vec2::new(d.y, -d.x) / d.hypot(); + m.dot(n).abs() > 1.0 - 1e-6 + }); + assert!(hit, "{kind:?} normal at {angle} in {all:?}"); + } + } + } + + #[test] + fn nested_overlapping_and_touching_circles() { + // One inside the other: none. + assert!(common_tangents(&circle(0.0, 0.0, 50.0), &circle(5.0, 0.0, 10.0)).unwrap().is_empty()); + // Overlapping: the two external ones only. + let over = common_tangents(&circle(0.0, 0.0, 30.0), &circle(40.0, 0.0, 30.0)).unwrap(); + assert_eq!(over.len(), 2); + assert!(over.iter().all(|t| t.kind == TangentKind::External)); + assert!(over.iter().any(|t| ends_at(t, Point::new(0.0, 30.0), Point::new(40.0, 30.0)))); + // Touching from outside at (10, 0): two external ones and one shared internal one, square to + // the line of centers, as long as the smaller circle is wide. + let touch = common_tangents(&circle(0.0, 0.0, 10.0), &circle(30.0, 0.0, 20.0)).unwrap(); + assert_eq!(touch.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{touch:?}"); + let shared: Vec<_> = touch.iter().filter(|t| t.kind == TangentKind::Internal).collect(); + assert_eq!(shared.len(), 1, "{touch:?}"); + assert!(ends_within(shared[0], Point::new(10.0, -10.0), Point::new(10.0, 10.0), 1e-5), "{shared:?}"); + // Touching along a direction between two sampled normals: the sampled minimum is refined + // down to the double root. + let along = dir(0.1234); + let off = common_tangents(&circle(0.0, 0.0, 10.0), &circle(30.0 * along.x, 30.0 * along.y, 20.0)).unwrap(); + assert_eq!(off.iter().filter(|t| t.kind == TangentKind::Internal).count(), 1, "{off:?}"); + // A hair apart: two internal tangents less than a sample apart, both kept. + let d = 30.000_01; + let near_miss = common_tangents(&circle(0.0, 0.0, 10.0), &circle(d * along.x, d * along.y, 20.0)).unwrap(); + assert_eq!(near_miss.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{near_miss:?}"); + // Inside with a clearance of 1e-6: no tangent. + assert!(common_tangents(&circle(0.0, 0.0, 50.0), &circle(40.0 - 1e-6, 0.0, 10.0)).unwrap().is_empty()); + // Equal circles a hair apart: the two external tangents run between their real contact + // points, that hair apart, not as a touching tangent. + let hair = common_tangents(&circle(0.0, 0.0, 30.0), &circle(1e-5, 0.0, 30.0)).unwrap(); + assert_eq!(hair.len(), 2, "{hair:?}"); + assert!(hair.iter().all(|t| ((t.to - t.from).hypot() - 1e-5).abs() < 1e-9), "{hair:?}"); + // Touching from inside at (50, 0): the one shared external tangent. + let inside = common_tangents(&circle(0.0, 0.0, 50.0), &circle(40.0, 0.0, 10.0)).unwrap(); + assert_eq!(inside.len(), 1, "{inside:?}"); + assert!(ends_within(&inside[0], Point::new(50.0, -10.0), Point::new(50.0, 10.0), 1e-5), "{inside:?}"); + } + + #[test] + fn a_convex_bezier_blob_and_an_ellipse_path() { + // A lopsided convex blob of four curves. + let a = |x: f64, y: f64, ix: f64, iy: f64, ox: f64, oy: f64| { + vectorcraft_geom::Anchor::with_handles(Point::new(x, y), Point::new(ix, iy), Point::new(ox, oy)) + }; + let blob = SubPath::new( + vec![ + a(0.0, 40.0, 0.0, 70.0, 0.0, 10.0), + a(50.0, 0.0, 20.0, 0.0, 90.0, 0.0), + a(110.0, 50.0, 110.0, 20.0, 110.0, 90.0), + a(40.0, 100.0, 80.0, 100.0, 10.0, 100.0), + ], + true, + ); + let round = shapes::ellipse(Rect::new(200.0, 150.0, 260.0, 230.0)).subpaths[0].clone(); + let (oa, ob) = (Outline::convex(&blob).unwrap(), Outline::convex(&round).unwrap()); + let all = common_tangents(&oa, &ob).unwrap(); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{all:?}"); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{all:?}"); + let (sa, sb) = (sample_path(&blob, 4000), sample_path(&round, 4000)); + for t in &all { + check_against_samples(t, &sa, &sb, 1e-3); + } + // The path's center is its center of area: the ellipse path's is its box's center. + assert!((ob.center() - Point::new(230.0, 190.0)).hypot() < 1e-6, "{:?}", ob.center()); + } + + #[test] + fn flat_sides_give_the_whole_stretch_they_touch() { + let square = + |x: f64| SubPath::polyline(&[Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)], true); + let all = common_tangents(&Outline::convex(&square(0.0)).unwrap(), &Outline::convex(&square(30.0)).unwrap()).unwrap(); + let ext: Vec<_> = all.iter().filter(|t| t.kind == TangentKind::External).collect(); + assert_eq!(ext.len(), 2, "{all:?}"); + assert!(ext.iter().any(|t| ends_at(t, Point::new(0.0, 0.0), Point::new(40.0, 0.0))), "{ext:?}"); + assert!(ext.iter().any(|t| ends_at(t, Point::new(0.0, 10.0), Point::new(40.0, 10.0))), "{ext:?}"); + // Far apart, each diamond is still touched only at its top corner. + let diamond = + |x: f64| SubPath::polyline(&[Point::new(x - 5.0, 0.0), Point::new(x, -5.0), Point::new(x + 5.0, 0.0), Point::new(x, 5.0)], true); + let far = common_tangents(&Outline::convex(&diamond(0.0)).unwrap(), &Outline::convex(&diamond(1e9)).unwrap()).unwrap(); + let top = far.iter().find(|t| t.kind == TangentKind::External && t.from.y > 0.0).unwrap(); + assert!(ends_within(top, Point::new(0.0, 5.0), Point::new(1e9, 5.0), 1e-3), "{far:?}"); + // Far from the origin the center of area and the tangents come out as near it. + let o = 1e9; + let away = |x: f64| SubPath::polyline(&[(x, o), (x + 10.0, o), (x + 10.0, o + 10.0), (x, o + 10.0)].map(Point::from), true); + let (sa, sb) = (Outline::convex(&away(o)).unwrap(), Outline::convex(&away(o + 30.0)).unwrap()); + assert!((sa.center() - Point::new(o + 5.0, o + 5.0)).hypot() < 1e-6, "{:?}", sa.center()); + let shifted = common_tangents(&sa, &sb).unwrap(); + assert!(shifted.iter().any(|t| ends_within(t, Point::new(o, o), Point::new(o + 40.0, o), 1e-6)), "{shifted:?}"); + // The internal ones are the diagonals between the near corners. + let int: Vec<_> = all.iter().filter(|t| t.kind == TangentKind::Internal).collect(); + assert_eq!(int.len(), 2, "{all:?}"); + assert!(int.iter().any(|t| ends_at(t, Point::new(10.0, 0.0), Point::new(30.0, 10.0))), "{int:?}"); + assert!(int.iter().any(|t| ends_at(t, Point::new(10.0, 10.0), Point::new(30.0, 0.0))), "{int:?}"); + // Squares meeting at the corner (10, 10): every line through the corner between their + // sides touches both, and the one internal line drawn is the one at the middle of those + // directions, as long as a square is wide along it. + let box_at = |x: f64, y: f64| { + SubPath::polyline(&[Point::new(x, y), Point::new(x + 10.0, y), Point::new(x + 10.0, y + 10.0), Point::new(x, y + 10.0)], true) + }; + let corner = common_tangents(&Outline::convex(&box_at(0.0, 0.0)).unwrap(), &Outline::convex(&box_at(10.0, 10.0)).unwrap()).unwrap(); + let shared: Vec<_> = corner.iter().filter(|t| t.kind == TangentKind::Internal).collect(); + assert_eq!(shared.len(), 1, "{corner:?}"); + assert!(ends_within(shared[0], Point::new(5.0, 15.0), Point::new(15.0, 5.0), 1e-6), "{shared:?}"); + // Sides 1e-6 off parallel: each line ends at the corners it touches, not at the corners + // of the sides it nearly lies along. + let tilted = common_tangents(&Outline::convex(&box_at(0.0, 0.0)).unwrap(), &Outline::convex(&box_at(30.0, -1e-6)).unwrap()).unwrap(); + let ext: Vec<_> = tilted.iter().filter(|t| t.kind == TangentKind::External).collect(); + assert_eq!(ext.len(), 2, "{tilted:?}"); + assert!(ext.iter().any(|t| ends_within(t, Point::new(10.0, 10.0), Point::new(40.0, 10.0 - 1e-6), 1e-6)), "{ext:?}"); + assert!(ext.iter().any(|t| ends_within(t, Point::new(0.0, 0.0), Point::new(30.0, -1e-6), 1e-6)), "{ext:?}"); + } + + /// A circle path of four curves, radius 100 about the origin, with an anchor at (100, 0). + fn circle_path() -> SubPath { + shapes::ellipse(Rect::new(-100.0, -100.0, 100.0, 100.0)).subpaths[0].clone() + } + + /// The point of `sp` where `p · n` is largest. + fn peak(sp: &SubPath, n: Vec2) -> Point { + let mut best = (Point::ORIGIN, f64::MIN); + for k in 0..sp.segment_count() { + each_extreme(&sp.segment(k), n, |p, v| { + if v > best.1 { + best = (p, v); + } + }); + } + best.0 + } + + #[test] + fn a_curve_is_touched_only_at_its_peak_beside_an_anchor() { + // The line touches the circle path 5e-4 radians from its anchor at (100, 0), where the + // anchor lies about 1.25e-5 inside the line: the line still ends at the peak, not at the + // anchor 0.05 along it. + let path = circle_path(); + let n = dir(5e-4); + let away = Vec2::new(n.y, -n.x) * 300.0; + let a = Outline::convex(&path).unwrap(); + let all = common_tangents(&a, &a.shifted(away)).unwrap(); + let top = all.iter().find(|t| t.kind == TangentKind::External && (t.from.to_vec2().dot(n) - 100.0).abs() < 1e-3).unwrap(); + let p = peak(&path, n); + assert!(ends_within(top, p, p + away, 1e-6), "{top:?} {p:?}"); + // An exact circle touching the path there from outside: one shared internal line, as long + // as that circle is wide, not a stub running to the anchor. + let b = circle(p.x + 20.0 * n.x, p.y + 20.0 * n.y, 20.0); + let touch = common_tangents(&a, &b).unwrap(); + let shared: Vec<_> = touch.iter().filter(|t| t.kind == TangentKind::Internal).collect(); + assert_eq!(shared.len(), 1, "{touch:?}"); + assert!(((shared[0].to - shared[0].from).hypot() - 40.0).abs() < 1e-3, "{shared:?}"); + assert!(((shared[0].from.midpoint(shared[0].to)) - p).hypot() < 1e-3, "{shared:?}"); + } + + #[test] + fn outlines_crossing_more_often_than_the_even_samples_keep_every_tangent() { + // Two regular 400-gons about one center, one turned half a step: their outlines cross 800 + // times, and an external tangent runs across each crossing. + let gon = |turn: f64| { + let pts: Vec<Point> = (0..400).map(|k| (dir(turn + TAU * k as f64 / 400.0) * 100.0).to_point()).collect(); + SubPath::polyline(&pts, true) + }; + let all = common_tangents(&Outline::convex(&gon(0.0)).unwrap(), &Outline::convex(&gon(TAU / 800.0)).unwrap()).unwrap(); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 800); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 0); + // Each runs between a corner of one and the next corner of the other, about 0.785 apart. + assert!(all.iter().all(|t| ((t.to - t.from).hypot() - 200.0 * (TAU / 1600.0).sin()).abs() < 1e-6), "{:?}", all.first()); + } + + #[test] + fn each_tangent_measures_only_the_segments_near_where_it_touches() { + // Two regular 2,000-gons about one center, one turned half a step: 4,000 external + // tangents. Measuring every segment of both outlines for every tangent takes about 8,000 + // measurements per tangent. + let sides = 2_000; + let gon = |turn: f64| { + let pts: Vec<Point> = (0..sides).map(|k| (dir(turn + TAU * k as f64 / sides as f64) * 100.0).to_point()).collect(); + SubPath::polyline(&pts, true) + }; + let (a, b) = (Outline::convex(&gon(0.0)).unwrap(), Outline::convex(&gon(TAU / (2 * sides) as f64)).unwrap()); + EXTREMES.with(|c| c.set(0)); + let all = common_tangents(&a, &b).unwrap(); + let calls = EXTREMES.with(Cell::get); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2 * sides); + assert!(calls < 1_000 * all.len(), "{calls} measurements for {} tangents", all.len()); + let r = 100.0 * (TAU / (4 * sides) as f64).sin(); + assert!(all.iter().all(|t| ((t.to - t.from).hypot() - 2.0 * r).abs() < 1e-6), "{:?}", all.first()); + } + + #[test] + fn a_very_thin_ellipse_is_measured_exactly() { + // Semi-axes 1e6 and 1e-7, a ratio of 1e13, beside a circle, then the whole figure turned + // 30 degrees: the tangents run from the ellipse's tips to the circle. + for deg in [0.0, 30.0] { + let turn = Affine::rotate(f64::to_radians(deg)); + let thin = turn * Affine::scale_non_uniform(1e6, 1e-7); + let round = turn * Affine::new([10.0, 0.0, 0.0, 10.0, 0.0, 100.0]); + let all = common_tangents(&Outline::ellipse(thin).unwrap(), &Outline::ellipse(round).unwrap()).unwrap(); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{all:?}"); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{all:?}"); + let (sa, sb) = (sample_ellipse(thin, 20_000), sample_ellipse(round, 5_000)); + for t in &all { + check_against_samples(t, &sa, &sb, 1e-3); + // The end on the ellipse, taken back to the unturned figure. + let (from, to) = (turn.inverse() * t.from, turn.inverse() * t.to); + let tip = if (from.x.abs() - 1e6).abs() < 1e-3 { from } else { to }; + assert!((tip.x.abs() - 1e6).abs() < 1e-3 && tip.y.abs() < 1e-6, "{deg} {t:?}"); + } + } + // A determinant a few times its rounding is taken; one lost in the rounding of the map's + // entries is still refused. + assert!(Outline::ellipse(Affine::new([1.0, 0.0, 0.0, 4.0 * f64::EPSILON, 0.0, 0.0])).is_ok()); + assert_eq!(Outline::ellipse(Affine::new([1.0, 0.0, 0.0, f64::EPSILON, 0.0, 0.0])).err(), Some(OutlineError::Empty)); + assert_eq!(Outline::ellipse(Affine::new([1.0, 1.0, 1.0, 1.0 + f64::EPSILON, 0.0, 0.0])).err(), Some(OutlineError::Empty)); + } + + #[test] + fn a_curve_peaking_inside_a_segment_is_measured_at_its_peak() { + // p(t) · n has the control values 0, 0.25, 0.5, -0.25: its derivative's linear term is + // zero, and the peak, 0.25 at t = 0.5, lies inside the segment. + let s = CubicBez::new((0.0, 0.0), (1.0, 0.25), (2.0, 0.5), (3.0, -0.25)); + let mut best = f64::MIN; + each_extreme(&s, Vec2::new(0.0, 1.0), |_, v| best = best.max(v)); + assert!((best - 0.25).abs() < 1e-12, "{best}"); + } + + #[test] + fn open_concave_empty_and_identical_outlines_are_refused() { + let open = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0)], false); + assert_eq!(Outline::convex(&open).err(), Some(OutlineError::Open)); + let star = shapes::star(Point::new(0.0, 0.0), 50.0, 20.0, 5, 0.0).subpaths[0].clone(); + assert_eq!(Outline::convex(&star).err(), Some(OutlineError::NotConvex)); + // A half disk whose straight side is a cubic with crossed handles: it bends the other way + // for a short stretch between two of the points the outline is checked at. + let mut bp = vectorcraft_geom::BezPath::new(); + let k = 0.5523 * 50.0; + bp.move_to((0.0, 0.0)); + bp.curve_to((62.4, 43.4), (60.3, 44.2), (100.0, 0.0)); + bp.curve_to((100.0, -k), (50.0 + k, -50.0), (50.0, -50.0)); + bp.curve_to((50.0 - k, -50.0), (0.0, -k), (0.0, 0.0)); + bp.close_path(); + let bend = vectorcraft_geom::PathData::from_bezpath(&bp).subpaths[0].clone(); + assert_eq!(Outline::convex(&bend).err(), Some(OutlineError::NotConvex)); + // A triangle whose first side is a cubic that leaves its start a little the wrong way: the + // corner there turns inward, though the checked points and the curve itself turn one way. + let mut bp = vectorcraft_geom::BezPath::new(); + bp.move_to((0.0, 0.0)); + bp.curve_to((-1.0, -1.0), (66.0, -2.0), (100.0, 0.0)); + bp.line_to((50.0, 100.0)); + bp.close_path(); + let notch = vectorcraft_geom::PathData::from_bezpath(&bp).subpaths[0].clone(); + assert_eq!(Outline::convex(¬ch).err(), Some(OutlineError::NotConvex)); + // A square traced twice around winds around twice. + let twice: Vec<Point> = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].repeat(2).into_iter().map(Point::from).collect(); + assert_eq!(Outline::convex(&SubPath::polyline(&twice, true)).err(), Some(OutlineError::NotConvex)); + let flat = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(20.0, 0.0)], true); + assert_eq!(Outline::convex(&flat).err(), Some(OutlineError::Empty)); + assert_eq!(Outline::ellipse(Affine::scale_non_uniform(10.0, 0.0)).err(), Some(OutlineError::Empty)); + assert_eq!(Outline::ellipse(Affine::new([f64::NAN, 0.0, 0.0, 1.0, 0.0, 0.0])).err(), Some(OutlineError::Empty)); + let many: Vec<Point> = (0..=MAX_TANGENT_SEGMENTS).map(|k| dir(TAU * k as f64 / (MAX_TANGENT_SEGMENTS + 1) as f64).to_point()).collect(); + assert_eq!(Outline::convex(&SubPath::polyline(&many, true)).err(), Some(OutlineError::TooComplex)); + // A square 1e110 wide has a finite center. + let huge = SubPath::polyline(&[(0.0, 0.0), (1e110, 0.0), (1e110, 1e110), (0.0, 1e110)].map(Point::from), true); + let center = Outline::convex(&huge).unwrap().center(); + assert!((center - Point::new(5e109, 5e109)).hypot() < 1e98, "{center:?}"); + assert_eq!(common_tangents(&circle(1.0, 2.0, 3.0), &circle(1.0, 2.0, 3.0)), Err(Coincide)); + } +} diff --git a/crates/pathops/src/addons/pathtools/tests.rs b/crates/pathops/src/addons/pathtools/tests.rs index 301da1a57c..3c6c592d71 100644 --- a/crates/pathops/src/addons/pathtools/tests.rs +++ b/crates/pathops/src/addons/pathtools/tests.rs @@ -515,6 +515,29 @@ fn one_work_budget_bounds_several_calls_together() { assert!(crossings_on(&path, &[]).is_some(), "a call of its own has its own budget"); } +#[test] +fn work_done_once_can_be_drawn_again_from_another_budget() { + let row: Vec<(f64, f64)> = (0..=1000).map(|i| (i as f64, 0.0)).collect(); + let path = PathData::single(line(&row, false)); + let start = Work::default(); + let mut work = start; + crossings_on_within(&path, &[], &mut work).unwrap(); + let cost = work.spent_since(start); + // Drawing a call's cost leaves what the call itself leaves, 120 times and no more. + let mut again = Work::default(); + assert_eq!(again.draw(cost), Some(())); + assert_eq!(again, work); + let draws = (1..200).take_while(|_| again.draw(cost).is_some()).count(); + assert_eq!(draws, 119); + let left = again; + assert_eq!(again.draw(cost), None); + assert_eq!(again, left, "a draw that fails takes nothing"); + // A twentieth of the budget pays for the call 6 times. + assert_eq!((Work::share(0), Work::share(1)), (Work::default(), Work::default())); + let mut part = Work::share(20); + assert_eq!((0..200).take_while(|_| part.draw(cost).is_some()).count(), 6); +} + #[test] fn a_segment_that_loops_over_itself_crosses_itself() { // One cubic that meets itself at t = 0.25 and t = 0.75. diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index 49b7c051f1..d35050f70c 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -30,8 +30,8 @@ pub use fit::{fit_cubics, fit_cubics_through}; pub use offset::{Cap, Join, MAX_OFFSET_SEGMENT_PAIRS, offset_path, outline_stroke, stroke_region, try_offset_path}; pub use pathfinder::{FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, pathfinder_with, region_at, regions, regions_within}; pub use planar::{ - BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, cut_out, encloses_area, find_gaps, has_open_path, interior_point, - live_paint, live_paint_with_gaps, run_around, shape_builder, shape_builder_with_gap, + Adjacency, BuilderArrangement, MapEdge, MapFace, MapOutline, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, adjacency, cut_out, + encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around, shape_builder, shape_builder_with_gap, }; pub use trap::{TRAP_HEIGHT_WIDTH_RANGE, TRAP_MAX_WIDTH, TRAP_MIN_WIDTH, trap_band}; diff --git a/crates/pathops/src/planar.rs b/crates/pathops/src/planar.rs index 75234b3943..f702f993ed 100644 --- a/crates/pathops/src/planar.rs +++ b/crates/pathops/src/planar.rs @@ -26,12 +26,14 @@ use vectorcraft_geom::{FillRule, PathData, SubPath}; use crate::boolean::{DEFAULT_PRECISION, Seg, Tidy, eps_for, is_sliver, segs_to_subpath, snap_horizontals, tidy_segments, to_seg}; use crate::pathfinder::{Region, Shape}; +mod adjacency; mod graph; mod index; mod live_paint; mod map; mod shape_builder; +pub use adjacency::{Adjacency, MapEdge, MapFace, MapOutline, adjacency}; pub(crate) use graph::pin_ends; #[cfg(test)] use index::{Crossings, RectIndex, reference_budget, segment_footprint, work_done}; diff --git a/crates/pathops/src/planar/adjacency.rs b/crates/pathops/src/planar/adjacency.rs new file mode 100644 index 0000000000..52357a0d67 --- /dev/null +++ b/crates/pathops/src/planar/adjacency.rs @@ -0,0 +1,169 @@ +//! Which faces of a planar map each edge separates, and every input each edge lies on. +//! +//! [`live_paint`](super::live_paint) gives each edge under its front-most input only, and says +//! nothing about the faces on its sides. [`adjacency`] reads both from the same planar map, so a +//! caller can tell which faces a line divides and which lines lie on top of each other. + +use super::graph::{find, half_segs, twin, unshear}; +use super::index::RectIndex; +use super::map::{Map, map_with}; +use super::*; + +/// A planar map of some paths with each edge's sides and inputs ([`adjacency`]). +#[derive(Clone, Debug, Default)] +pub struct Adjacency { + pub faces: Vec<MapFace>, + pub edges: Vec<MapEdge>, + /// Bounded areas left out as slivers: narrower than the precision on average, such as a thin + /// gap between two lines. + pub slivers: Vec<PathData>, + /// The outer boundary of each connected piece of the paths. + pub outlines: Vec<MapOutline>, +} + +/// A bounded face: its outline, then the outer boundaries of the pieces inside it (as holes), and +/// its area without them. +#[derive(Clone, Debug)] +pub struct MapFace { + pub path: PathData, + pub area: f64, + /// The connected piece of the paths whose edges bound it. + pub piece: usize, +} + +/// An edge: a piece of one or more inputs between two places where paths meet. +#[derive(Clone, Debug)] +pub struct MapEdge { + pub path: PathData, + /// Every input it lies on (indices into the inputs, ascending). + pub sources: Vec<usize>, + /// The faces on each side of it as it runs along `path`, seen on the page (document + /// coordinates, y down): `left` on the left. `None` outside every bounded face, or in a sliver. + /// A piece of line that ends loose inside a face has that face on both sides. + pub left: Option<usize>, + pub right: Option<usize>, + pub piece: usize, +} + +/// The outer boundary of a connected piece of the paths. +#[derive(Clone, Debug)] +pub struct MapOutline { + pub path: PathData, + pub piece: usize, +} + +/// The planar map of `shapes`, every path an edge as in [`live_paint`](super::live_paint), with +/// faces refit to `precision` and slivers narrower than it left out. `None` when the paths can't be +/// swept (non-finite, too degenerate, or more than [`SHAPE_BUILDER_MAX_SEGMENTS`] segments), when +/// `precision` is not a positive number, and when no path has two anchors. +pub fn adjacency(shapes: &[Shape], precision: f64) -> Option<Adjacency> { + if !(precision.is_finite() && precision > 0.0) { + return None; + } + let segments: usize = shapes.iter().flat_map(|s| &s.path.subpaths).map(SubPath::segment_count).sum(); + if segments > SHAPE_BUILDER_MAX_SEGMENTS { + return None; + } + let m = map_with(shapes, false, precision)?; + Some(read(&m)) +} + +fn read(m: &Map) -> Adjacency { + let path = |cycle: &[usize], closed: bool| { + let segs: Vec<Seg> = cycle.iter().flat_map(|&h| half_segs(&m.edges, h)).collect(); + segs_to_subpath(&tidy_segments(segs, closed, &m.tidy), closed) + }; + let unsheared = |subpaths: Vec<SubPath>| unshear(PathData::new(subpaths), &m.anchors, m.snap); + + // Connected pieces, by the vertices the edges join, numbered in the order they are first met. + let vertices = m.edges.iter().flat_map(|e| e.ends).max().map_or(0, |v| v + 1); + let mut parent: Vec<usize> = (0..vertices).collect(); + for e in &m.edges { + let (a, b) = (find(&mut parent, e.ends[0]), find(&mut parent, e.ends[1])); + if let Some(p) = parent.get_mut(a) { + *p = b; + } + } + let mut number: Vec<Option<usize>> = vec![None; vertices]; + let mut pieces = 0; + let mut piece_of_vertex = |v: usize| { + let root = find(&mut parent, v); + match number.get_mut(root) { + Some(Some(n)) => *n, + Some(slot) => { + *slot = Some(pieces); + pieces += 1; + pieces - 1 + } + None => 0, + } + }; + let edge_pieces: Vec<usize> = m.edges.iter().map(|e| piece_of_vertex(e.ends[0])).collect(); + let piece_of = |cycle: &[usize]| cycle.first().and_then(|&h| edge_pieces.get(h / 2)).copied().unwrap_or(0); + + // The face on each half-edge's side: a face's own cycle, and the outer boundaries of the + // pieces inside it, bound it. + let mut face_of: Vec<Option<usize>> = vec![None; 2 * m.edges.len()]; + let mut faces = Vec::with_capacity(m.faces.len()); + for (i, (cycle, _, area)) in m.faces.iter().enumerate() { + let holes: Vec<&(Vec<usize>, BezPath)> = m.face_holes.get(i).into_iter().flatten().filter_map(|&k| m.holes.get(k)).collect(); + for &h in cycle.iter().chain(holes.iter().flat_map(|(c, _)| c)) { + if let Some(f) = face_of.get_mut(h) { + *f = Some(i); + } + } + let mut subpaths: Vec<SubPath> = path(cycle, true).into_iter().collect(); + subpaths.extend(holes.iter().filter_map(|(c, _)| path(c, true))); + // A hole's outer boundary winds the other way: its area is negative. + let area = area + holes.iter().map(|(_, bp)| bp.area()).sum::<f64>(); + faces.push(MapFace { path: unsheared(subpaths), area, piece: piece_of(cycle) }); + } + + // A face walk leaves out the edges that end loose (spurs): such an edge lies inside the face + // around its middle, on both sides. + let mut on_cycle = vec![false; 2 * m.edges.len()]; + let cycles = m.faces.iter().map(|f| &f.0).chain(m.holes.iter().map(|h| &h.0)).chain(m.slivers.iter().map(|s| &s.0)); + for &h in cycles.flatten() { + if let Some(c) = on_cycle.get_mut(h) { + *c = true; + } + } + let spur = |e: usize| !on_cycle.get(2 * e).copied().unwrap_or(true) && !on_cycle.get(twin(2 * e)).copied().unwrap_or(true); + // The faces by their bounds, so that each spur tests only the faces whose bounds hold it; + // built only when there is a spur. + let bezpaths: Vec<BezPath> = if (0..m.edges.len()).any(spur) { faces.iter().map(|f| f.path.to_bezpath()).collect() } else { vec![] }; + let face_index = RectIndex::new(bezpaths.iter().enumerate().map(|(i, bp)| (bp.bounding_box(), i)).collect()); + let face_around = |p: Point| { + face_index + .at(p, 0.0) + .copied() + .filter(|&i| bezpaths.get(i).is_some_and(|bp| bp.winding(p) != 0)) + .min_by(|&a, &b| faces.get(a).map_or(f64::INFINITY, |f| f.area).total_cmp(&faces.get(b).map_or(f64::INFINITY, |f| f.area))) + }; + + // A face cycle winds so its face is on the side where the cross product of the half-edge's + // direction and the way to the face is positive: on the page, with y down, that is the right. + let edges = m + .edges + .iter() + .enumerate() + .filter_map(|(e, edge)| { + let sp = path(&[2 * e], false)?; + let path = unsheared(vec![sp]); + let (left, right) = if spur(e) { + let around = path.to_bezpath().segments().next().map(|s| s.eval(0.5)).and_then(face_around); + (around, around) + } else { + (face_of.get(twin(2 * e)).copied().flatten(), face_of.get(2 * e).copied().flatten()) + }; + Some(MapEdge { path, sources: edge.sources.clone(), left, right, piece: edge_pieces.get(e).copied().unwrap_or(0) }) + }) + .collect(); + let slivers = m.slivers.iter().filter_map(|(cycle, _)| path(cycle, true)).map(|sp| unsheared(vec![sp])).collect(); + let outlines = + m.holes.iter().filter_map(|(cycle, _)| Some(MapOutline { path: unsheared(vec![path(cycle, true)?]), piece: piece_of(cycle) })).collect(); + Adjacency { faces, edges, slivers, outlines } +} + +#[cfg(test)] +mod tests; diff --git a/crates/pathops/src/planar/adjacency/tests.rs b/crates/pathops/src/planar/adjacency/tests.rs new file mode 100644 index 0000000000..8677a7e11a --- /dev/null +++ b/crates/pathops/src/planar/adjacency/tests.rs @@ -0,0 +1,200 @@ +use super::*; +use kurbo::{ParamCurveNearest, Vec2}; +use proptest::prelude::*; +use vectorcraft_geom::{FillRule, Rect, shapes}; + +fn line(a: (f64, f64), b: (f64, f64)) -> Shape { + Shape::new(PathData::single(SubPath::polyline(&[Point::new(a.0, a.1), Point::new(b.0, b.1)], false)), FillRule::NonZero, 0) +} + +fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> Shape { + Shape::new(shapes::rectangle(Rect::new(x0, y0, x1, y1)), FillRule::NonZero, 0) +} + +fn inside(f: &MapFace, p: Point) -> bool { + f.path.to_bezpath().winding(p) != 0 +} + +/// The edges whose middle lies within 0.01 of `p`. +fn edges_at(a: &Adjacency, p: Point) -> Vec<&MapEdge> { + a.edges + .iter() + .filter(|e| { + let bp = e.path.to_bezpath(); + bp.segments().any(|s| { + let n = s.nearest(p, 1e-6); + n.distance_sq < 1e-4 + }) + }) + .collect() +} + +#[test] +fn a_line_across_a_rectangle_divides_two_faces_it_lies_between() { + let a = adjacency(&[rect(0.0, 0.0, 100.0, 50.0), line((40.0, -10.0), (40.0, 60.0))], DEFAULT_PRECISION).unwrap(); + assert_eq!(a.faces.len(), 2, "{:?}", a.faces); + let left_face = a.faces.iter().position(|f| inside(f, Point::new(20.0, 25.0))).unwrap(); + let right_face = a.faces.iter().position(|f| inside(f, Point::new(70.0, 25.0))).unwrap(); + assert_ne!(left_face, right_face); + assert!((a.faces[left_face].area - 2000.0).abs() < 1e-6 && (a.faces[right_face].area - 3000.0).abs() < 1e-6); + let shared = edges_at(&a, Point::new(40.0, 25.0)); + assert_eq!(shared.len(), 1, "{shared:?}"); + let e = shared[0]; + assert_eq!(e.sources, vec![1]); + let mut sides = [e.left.unwrap(), e.right.unwrap()]; + sides.sort_unstable(); + let mut want = [left_face, right_face]; + want.sort_unstable(); + assert_eq!(sides, want); + // The rectangle's own sides have a face on one side only; the line's ends stick out into no face. + let side = edges_at(&a, Point::new(70.0, 0.0)); + assert_eq!(side.len(), 1); + assert_eq!([side[0].left, side[0].right].iter().flatten().count(), 1); + let stub = edges_at(&a, Point::new(40.0, -5.0)); + assert_eq!((stub[0].left, stub[0].right), (None, None)); + assert!(a.faces.iter().all(|f| f.piece == 0) && a.edges.iter().all(|e| e.piece == 0)); +} + +#[test] +fn a_line_that_ends_inside_a_face_has_that_face_on_both_sides() { + let a = adjacency(&[rect(0.0, 0.0, 100.0, 50.0), line((50.0, 0.0), (50.0, 30.0)), line((20.0, 10.0), (30.0, 20.0))], DEFAULT_PRECISION).unwrap(); + assert_eq!(a.faces.len(), 1); + for at in [Point::new(50.0, 15.0), Point::new(25.0, 15.0)] { + let e = edges_at(&a, at); + assert_eq!(e.len(), 1, "{at:?}"); + assert_eq!((e[0].left, e[0].right), (Some(0), Some(0)), "{at:?}"); + } +} + +#[test] +fn loose_lines_in_many_faces_look_only_at_the_faces_near_them() { + // A 40 × 40 grid of separate squares, then the same with a loose line in each. + let squares: Vec<Shape> = + (0..1600).map(|k| (f64::from(k % 40) * 20.0, f64::from(k / 40) * 20.0)).map(|(x, y)| rect(x, y, x + 10.0, y + 10.0)).collect(); + let started = super::super::index::work_done(); + assert_eq!(adjacency(&squares, DEFAULT_PRECISION).unwrap().faces.len(), 1600); + let plain = super::super::index::work_done() - started; + let mut all = squares.clone(); + all.extend((0..1600).map(|k| (f64::from(k % 40) * 20.0, f64::from(k / 40) * 20.0)).map(|(x, y)| line((x + 5.0, y), (x + 5.0, y + 5.0)))); + let started = super::super::index::work_done(); + let a = adjacency(&all, DEFAULT_PRECISION).unwrap(); + let work = super::super::index::work_done() - started - plain; + let loose: Vec<&MapEdge> = a.edges.iter().filter(|e| e.sources.len() == 1 && e.sources[0] >= 1600).collect(); + assert_eq!(loose.len(), 1600); + for e in loose { + let mid = e.path.to_bezpath().segments().next().unwrap().eval(0.5); + let face = a.faces.iter().position(|f| inside(f, mid)); + assert_eq!((e.left, e.right), (face, face)); + assert!(face.is_some()); + } + // Testing every face for each loose line would read 1,600 faces per line. + assert!(work <= 64 * 1600, "{work} reads"); +} + +#[test] +fn a_line_on_a_rectangle_side_keeps_both_inputs_in_either_order() { + for flip in [false, true] { + let (r, l) = (rect(0.0, 0.0, 100.0, 50.0), line((-10.0, 50.0), (110.0, 50.0))); + let shapes = if flip { vec![l, r] } else { vec![r, l] }; + let a = adjacency(&shapes, DEFAULT_PRECISION).unwrap(); + let on = edges_at(&a, Point::new(30.0, 50.0)); + assert_eq!(on.len(), 1, "flip {flip}: {on:?}"); + assert_eq!(on[0].sources, vec![0, 1], "flip {flip}"); + } +} + +#[test] +fn each_side_names_the_face_seen_on_that_side_of_the_edge() { + // A tray-like outline with a crease grid, edges drawn in every direction. + let a = adjacency( + &[ + rect(0.0, 0.0, 90.0, 60.0), + line((30.0, 0.0), (30.0, 60.0)), + line((60.0, 60.0), (60.0, 0.0)), + line((90.0, 20.0), (0.0, 20.0)), + line((0.0, 40.0), (90.0, 40.0)), + ], + DEFAULT_PRECISION, + ) + .unwrap(); + assert_eq!(a.faces.len(), 9); + let mut checked = 0; + for e in &a.edges { + let bp = e.path.to_bezpath(); + let Some(seg) = bp.segments().next() else { continue }; + let (p, d) = (seg.eval(0.5), seg.end() - seg.start()); + let n = d.normalize(); + // On the page (y down), the left of a direction (dx, dy) is (dy, -dx). + let (left_at, right_at) = (p + Vec2::new(n.y, -n.x) * 0.5, p + Vec2::new(-n.y, n.x) * 0.5); + for (side, at) in [(e.left, left_at), (e.right, right_at)] { + match side { + Some(f) => assert!(inside(&a.faces[f], at), "{e:?}"), + None => assert!(a.faces.iter().all(|f| !inside(f, at)), "{e:?}"), + } + checked += 1; + } + } + assert!(checked >= 24, "{checked}"); +} + +#[test] +fn a_slot_narrower_than_the_precision_is_a_sliver() { + let a = adjacency(&[rect(0.0, 0.0, 100.0, 50.0), rect(50.0, 10.0, 50.004, 40.0)], DEFAULT_PRECISION).unwrap(); + assert_eq!(a.slivers.len(), 1, "{:?}", a.slivers); + assert_eq!(a.faces.len(), 1); + let b = adjacency(&[rect(0.0, 0.0, 100.0, 50.0), rect(50.0, 10.0, 51.0, 40.0)], DEFAULT_PRECISION).unwrap(); + assert!(b.slivers.is_empty()); + assert_eq!(b.faces.len(), 2, "the slot is a face of its own"); +} + +#[test] +fn a_ring_is_a_face_with_a_hole_and_two_pieces() { + let a = adjacency(&[rect(0.0, 0.0, 100.0, 100.0), rect(30.0, 30.0, 70.0, 70.0)], DEFAULT_PRECISION).unwrap(); + assert_eq!(a.faces.len(), 2); + let ring = a.faces.iter().find(|f| inside(f, Point::new(10.0, 10.0))).unwrap(); + assert!(!inside(ring, Point::new(50.0, 50.0)), "the inner square is a hole in the ring"); + assert!((ring.area - 8400.0).abs() < 1e-6, "{}", ring.area); + assert_eq!(a.outlines.len(), 2); + assert_ne!(a.outlines[0].piece, a.outlines[1].piece); + let inner = a.faces.iter().find(|f| inside(f, Point::new(50.0, 50.0))).unwrap(); + assert_ne!(inner.piece, ring.piece); + let inner_side = edges_at(&a, Point::new(50.0, 30.0)); + let mut sides = [inner_side[0].left, inner_side[0].right]; + sides.sort_unstable(); + assert!(sides.iter().all(Option::is_some), "a ring face on one side, the inner square on the other: {sides:?}"); +} + +#[test] +fn bad_input_gives_no_map() { + assert!(adjacency(&[], DEFAULT_PRECISION).is_none()); + assert!(adjacency(&[line((0.0, 0.0), (f64::NAN, 1.0))], DEFAULT_PRECISION).is_none()); + assert!(adjacency(&[rect(0.0, 0.0, 10.0, 10.0)], 0.0).is_none()); + assert!(adjacency(&[rect(0.0, 0.0, 10.0, 10.0)], f64::INFINITY).is_none()); + let mut points: Vec<Point> = (0..=SHAPE_BUILDER_MAX_SEGMENTS + 1).map(|i| Point::new(i as f64, (i % 2) as f64)).collect(); + let open = Shape::new(PathData::single(SubPath::polyline(&points, false)), FillRule::NonZero, 0); + assert!(adjacency(&[open], DEFAULT_PRECISION).is_none(), "over the segment limit"); + points.truncate(64); + let open = Shape::new(PathData::single(SubPath::polyline(&points, false)), FillRule::NonZero, 0); + assert!(adjacency(&[open], DEFAULT_PRECISION).is_some()); +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(64))] + /// Random lines and boxes never panic, and every side an edge names is a face. + #[test] + fn random_lines_give_a_consistent_map( + segs in proptest::collection::vec((-50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0), 1..12), + boxed in any::<bool>(), + ) { + let mut shapes: Vec<Shape> = segs.iter().map(|&(a, b, c, d)| line((a, b), (c, d))).collect(); + if boxed { + shapes.push(rect(-40.0, -40.0, 40.0, 40.0)); + } + if let Some(a) = adjacency(&shapes, DEFAULT_PRECISION) { + for e in &a.edges { + prop_assert!(e.left.is_none_or(|f| f < a.faces.len()) && e.right.is_none_or(|f| f < a.faces.len())); + prop_assert!(e.sources.iter().all(|&s| s < shapes.len())); + } + } + } +} diff --git a/crates/pathops/src/planar/map.rs b/crates/pathops/src/planar/map.rs index aa853b2469..a9b25d24b5 100644 --- a/crates/pathops/src/planar/map.rs +++ b/crates/pathops/src/planar/map.rs @@ -15,23 +15,23 @@ pub(crate) struct Rest { /// The planar graph of `shapes` (in the sweep's frame) with its faces walked: what [`build`] makes /// Live Paint faces and edges from, and what [`Map::merge`] merges faces in. pub(crate) struct Map { - edges: Vec<Edge>, + pub(super) edges: Vec<Edge>, around: Vec<Vec<usize>>, slot_of: Vec<usize>, /// Bounded faces: their cycle of half-edges, path and area; and, by their bounds, which can /// hold a point, so finding the face around one tests only those. - faces: Vec<(Vec<usize>, BezPath, f64)>, + pub(super) faces: Vec<(Vec<usize>, BezPath, f64)>, face_index: RectIndex<usize>, /// Bounded faces left out as slivers ([`is_sliver`]): their cycle of half-edges and the inputs /// whose fill covers them (none for a gap, such as a thin cutout). pub(super) slivers: Vec<(Vec<usize>, Vec<usize>)>, /// Outer boundaries of connected pieces, and the face each one is a hole in. - holes: Vec<(Vec<usize>, BezPath)>, - face_holes: Vec<Vec<usize>>, - tidy: Tidy, + pub(super) holes: Vec<(Vec<usize>, BezPath)>, + pub(super) face_holes: Vec<Vec<usize>>, + pub(super) tidy: Tidy, /// The inputs' anchors (sorted by x) and how close results snap back onto them. - anchors: Vec<Point>, - snap: f64, + pub(super) anchors: Vec<Point>, + pub(super) snap: f64, } /// With `cover`, also finds which inputs cover each sliver, which only [`Map::merge`] reads; @@ -41,7 +41,7 @@ pub(crate) fn map(shapes: &[Shape], cover: bool) -> Option<Map> { } /// [`map`] whose faces and pieces are refit to `precision`, and whose slivers thinner than it are dropped. -fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option<Map> { +pub(super) fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option<Map> { let mut inputs: Vec<(BezPath, usize)> = Vec::new(); for (i, s) in shapes.iter().enumerate() { let mut bp = BezPath::new(); diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index d4394dfefa..817d334fb8 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -24,17 +24,18 @@ 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); the version usvg already uses. -roxmltree = "0.21" +# The XMP packet that File Info is read from (file_info.rs). +craft-xml = { workspace = true } # PDF security (encrypt.rs): pure Rust, MIT OR Apache-2.0, builds for wasm. aes = "0.8" md-5 = { version = "0.10", default-features = false } 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<u16> = (0..2).flat_map(|y| (0..4).map(move |x| x as u16 * 20000 + y as u16)).collect(); + let raw_u16: Vec<u8> = 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<u8> = 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/export/entry.rs b/crates/pdf/src/export/entry.rs index 00ac16a3fe..fcdcd01f63 100644 --- a/crates/pdf/src/export/entry.rs +++ b/crates/pdf/src/export/entry.rs @@ -57,6 +57,7 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha let layers = vectorcraft_effects::WrittenLayers { hidden: set.writes_layers() && !doc.page_knockout, non_printing: set.include_non_printing || set.create_layers, + hidden_objects: false, }; let baked = vectorcraft_effects::bake_document_placing_symbols(doc, true, layers); // Baking stops early when cancelled, leaving a half-baked copy that must not be written. diff --git a/crates/pdf/src/export/exporter.rs b/crates/pdf/src/export/exporter.rs index f102e0a0ab..a116f8bc2a 100644 --- a/crates/pdf/src/export/exporter.rs +++ b/crates/pdf/src/export/exporter.rs @@ -18,6 +18,10 @@ pub(super) const MAX_PATTERN_DEPTH: u32 = 4; /// (`vectorcraft-engine`'s `rasterfx::undecoded_warning`). pub(super) const UNDECODED: &str = "an image couldn't be decoded and is missing from the picture"; +/// The warning for an image left out because its colors can't be converted as the Output +/// settings ask, although it could be written in its own colors. +pub(super) const UNCONVERTED: &str = "an image couldn't be converted to the Output destination and is missing from the picture"; + /// The warning for an image whose placement cannot be written. pub(super) const UNWRITABLE_IMAGE: &str = "an image couldn't be written and is missing from the picture"; diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 04a3a811f3..3da2079b9b 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -1,8 +1,10 @@ -use super::exporter::{UNDECODED, UNWRITABLE_IMAGE, q, writable, xf}; +use super::exporter::{UNCONVERTED, UNDECODED, UNWRITABLE_IMAGE, q, writable, xf}; use super::{Arc, BlendMode, Color, Exporter, Image, Node, NodeKind, Paint, Rect, Size, Surface, cmyk, krilla}; use krilla::color::device_n::{Colorant, DeviceNSpace, Process}; use krilla::image::{BitsPerComponent, CustomImage, ImageColorspace}; +use crate::images::SourceProfiles; + /// The byte count of a repeated color channel, within [`vectorcraft_doc::MAX_RASTER_ALLOC`]. fn tinted_color_len(samples: usize, pixels: usize) -> Option<usize> { let bytes = samples.checked_mul(pixels)?; @@ -124,7 +126,9 @@ impl Exporter<'_> { /// settings say ([`crate::images::recode`], [`crate::images::recode_cmyk`] for CMYK images); /// cached by key (and size when images are resampled). With `interpolate` (and the export's /// own setting), viewers may smooth it. `None`, with [`UNDECODED`] among the warnings, for an - /// image that is missing, can't be decoded or is in [`Self::left_out`]. + /// image that is missing, can't be decoded or is in [`Self::left_out`]; `None`, with + /// [`UNCONVERTED`], for one whose colors the Output settings convert but that can only be + /// written in its own ([`crate::images::Recoded::unconverted`]). fn load_image(&mut self, im: &vectorcraft_doc::ImageObject, size: (f64, f64), interpolate: bool) -> Option<Image> { let key = im.key.as_str(); let c = self.compression; @@ -138,8 +142,11 @@ impl Exporter<'_> { } let doc = self.doc; let out = self.out.clone(); - let profiles = !out.standard.cmyk_only(); - let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: self.sixteen_bit }); + let profiles = out.source_profiles(); + let then = out.converts_tagged_pixels().then_some(&*out); + let grey = out.converts_grey_images(); + let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: self.sixteen_bit, then, grey }); + let mut unconverted = false; let img = doc.image_blob(im).filter(|_| !self.left_out.contains(key)).and_then(|blob| { let cmyk_image = blob.is_cmyk(); if !cmyk_image && self.convert && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk { @@ -147,10 +154,16 @@ impl Exporter<'_> { } let r = if cmyk_image { let icc = out.cmyk_image_icc(blob); - crate::images::recode_cmyk(blob, size, c, interpolate, out.cmyk_pixels(), None, icc.as_deref()) + crate::images::recode_cmyk(blob, size, c, interpolate, out.cmyk_pixels(), None, out.cmyk_tag(icc.as_deref())) } else { crate::images::recode(&blob.bytes, size, c, interpolate, out.pixels(), profiles, to_srgb) }; + if r.unconverted { + // The source image would be written in its own colors: it is left out, with a + // warning that names the conversion when it could have been written. + unconverted = embed(blob, interpolate, self.sixteen_bit, profiles).is_some(); + return None; + } let img = r.image.or_else(|| embed(blob, interpolate, self.sixteen_bit, profiles)); // An image left out gets the warning below instead. for w in [r.warning, r.note].into_iter().flatten().filter(|_| img.is_some()) { @@ -158,7 +171,9 @@ impl Exporter<'_> { } img }); - if img.is_none() { + if unconverted { + self.warn(UNCONVERTED); + } else if img.is_none() { self.warn(UNDECODED); } self.images.insert(cache, img.clone()); @@ -197,7 +212,8 @@ impl Exporter<'_> { let img = doc.image_blob(im).filter(|b| b.is_cmyk()).and_then(|blob| { let alpha = crate::images::mask_alpha(doc.image_blob(mi)?, im.width, im.height, m.clip)?; let icc = self.out.cmyk_image_icc(blob); - let r = crate::images::recode_cmyk(blob, size, self.compression, interpolate, self.out.cmyk_pixels(), Some(alpha), icc.as_deref()); + let tag = self.out.cmyk_tag(icc.as_deref()); + let r = crate::images::recode_cmyk(blob, size, self.compression, interpolate, self.out.cmyk_pixels(), Some(alpha), tag); if let (Some(w), Some(_)) = (r.warning, &r.image) { self.warn(w); } @@ -320,13 +336,15 @@ pub(super) fn png_8_bit(bytes: &[u8]) -> Option<Vec<u8>> { } /// Image `blob` as it is: PNG, JPEG, GIF and WebP through the PDF writer (JPEG data unchanged), -/// other formats (a TIFF) decoded with their 16-bit samples and, when `profiles` allows it (not in -/// PDF/X-1a), the ICC profile they carry ([`crate::images::decoded_image`]). Without `profiles`, an -/// image that carries a gray or RGB profile is written without it, and so is one whose gray or RGB -/// profile is malformed ([`crate::images::valid_icc`]): a JPEG with its data unchanged, an image of -/// another format decoded. Without `sixteen_bit` (a file before PDF 1.5), a PNG or another image of -/// 16 bits a sample is written at 8 bits ([`png_8_bit`]). -pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixteen_bit: bool, profiles: bool) -> Option<Image> { +/// other formats (a TIFF) decoded with their 16-bit samples and, when `profiles` keeps it (not in +/// PDF/X-1a), the ICC profile they carry ([`crate::images::decoded_image`]). When `profiles` +/// doesn't keep it, an image that carries a gray or RGB profile is written without it, and so is +/// one whose gray or RGB profile is malformed ([`crate::images::valid_icc`]): a JPEG with its data +/// unchanged, an image of another format decoded. With [`SourceProfiles::Remove`], an image that +/// carries any profile is written without it, a JPEG without its `ICC_PROFILE` segments (decoded +/// when those can't be taken out). Without `sixteen_bit` (a file before PDF 1.5), a PNG or another +/// image of 16 bits a sample is written at 8 bits ([`png_8_bit`]). +pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixteen_bit: bool, profiles: SourceProfiles) -> Option<Image> { // The header's size first: the writer's decoders allocate what it declares, and the encoded // bytes of an image that is far larger than any the app reads may be a few kilobytes. let size = image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice())).with_guessed_format().ok()?.into_dimensions(); @@ -334,16 +352,25 @@ pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixtee return None; } let bytes = blob.bytes.as_ref().clone(); - // The PDF writer keeps a gray or RGB image's ICC profile: without `profiles`, or when the - // profile is malformed, such a JPEG is written without its profile, and an image of another + // The PDF writer keeps a gray or RGB image's ICC profile: unless `profiles` keeps it, or when + // the profile is malformed, such a JPEG is written without its profile, and an image of another // format is decoded and written without it. The color space is read from the header's bytes - // 16..20 even in a profile cut short, as the PDF writer reads it. - let strip = crate::images::source_icc(&bytes).is_some_and(|icc| match icc.get(16..20) { - Some(space @ (b"GRAY" | b"RGB ")) => !profiles || <[u8; 4]>::try_from(space).is_ok_and(|s| !crate::images::valid_icc(&icc, s)), + // 16..20 even in a profile cut short, as the PDF writer reads it. With `Remove`, a JPEG's + // `ICC_PROFILE` segments are taken out also when they don't make up a profile the decoder reads. + let remove = profiles == SourceProfiles::Remove; + let jpeg = matches!(blob.mime.as_str(), "image/jpeg" | "image/jpg"); + let unkept = crate::images::source_icc(&bytes).is_some_and(|icc| match icc.get(16..20) { + _ if remove => true, + Some(space @ (b"GRAY" | b"RGB ")) => { + profiles != SourceProfiles::Keep || <[u8; 4]>::try_from(space).is_ok_and(|s| !crate::images::valid_icc(&icc, s)) + } _ => false, }); + let strip = (remove && jpeg) || unkept; let direct = match blob.mime.as_str() { - "image/jpeg" | "image/jpg" if strip => Image::from_jpeg_with_icc(bytes.clone().into(), None, interpolate).ok(), + "image/jpeg" | "image/jpg" if strip => { + crate::images::jpeg_data(&bytes, remove).and_then(|data| Image::from_jpeg_with_icc(data.into(), None, interpolate).ok()) + } _ if strip => None, "image/png" if !sixteen_bit && png_16_bit(&bytes) => png_8_bit(&bytes).and_then(|png| Image::from_png(png.into(), interpolate).ok()), "image/png" => Image::from_png(bytes.clone().into(), interpolate).ok(), @@ -371,7 +398,7 @@ mod tests { let crc = !png[12..29].iter().fold(!0u32, |c, b| (0..8).fold(c ^ u32::from(*b), |c, _| if c & 1 == 1 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 })); png[29..33].copy_from_slice(&crc.to_be_bytes()); - assert!(super::embed(&ImageBlob::png(png), false, true, true).is_none()); + assert!(super::embed(&ImageBlob::png(png), false, true, super::SourceProfiles::Keep).is_none()); } #[test] diff --git a/crates/pdf/src/export/text.rs b/crates/pdf/src/export/text.rs index c6946f5416..ea29167f1b 100644 --- a/crates/pdf/src/export/text.rs +++ b/crates/pdf/src/export/text.rs @@ -326,7 +326,7 @@ impl Exporter<'_> { let img = match self.images.get(&cache) { Some(img) => img.clone(), None => { - let img = embed(&image.blob, self.interpolate, self.sixteen_bit, !self.out.standard.cmyk_only()); + let img = embed(&image.blob, self.interpolate, self.sixteen_bit, self.out.source_profiles()); self.images.insert(cache, img.clone()); img } diff --git a/crates/pdf/src/file_info.rs b/crates/pdf/src/file_info.rs index 1cb0a45273..36a4f0ed8e 100644 --- a/crates/pdf/src/file_info.rs +++ b/crates/pdf/src/file_info.rs @@ -2,10 +2,13 @@ //! dictionary (ISO 32000-1 §14.3.3) and the XMP packet of the catalog's metadata stream (§14.3.2, //! ISO 16684-1). Where both give a field, the XMP packet's value is taken; a packet that can't be //! read leaves the information dictionary's values. +//! +//! File › File Info's metadata templates are XMP packets of the same properties: [`metadata_template`] +//! writes one and [`read_template`] reads one back. use craft_pdf::syntax::Pdf; use craft_pdf::syntax::object::{DateTime, Dict, Stream}; -use roxmltree::Node; +use craft_xml::{Canonical, Doctype, El, Limits, Names, Options}; use crate::import_scan::text_string; @@ -15,11 +18,18 @@ const MAX_XMP: usize = 8 << 20; const MAX_NESTING: usize = 256; const RDF: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; -const XML: &str = "http://www.w3.org/XML/1998/namespace"; pub(crate) const DC: &str = "http://purl.org/dc/elements/1.1/"; const XMP: &str = "http://ns.adobe.com/xap/1.0/"; // brand-ok: the XMP namespace the files use pub(crate) const XMP_RIGHTS: &str = "http://ns.adobe.com/xap/1.0/rights/"; // brand-ok: the XMP namespace the files use const PDF: &str = "http://ns.adobe.com/pdf/1.3/"; // brand-ok: the XMP namespace the files use +const PHOTOSHOP: &str = "http://ns.adobe.com/photoshop/1.0/"; // brand-ok: the XMP namespace the files use +const X: &str = "adobe:ns:meta/"; // brand-ok: the XMP namespace the files use + +/// The longest metadata template [`read_template`] reads, in bytes. +pub const MAX_TEMPLATE_BYTES: usize = MAX_XMP; + +const XMP_NAMESPACES: Canonical<'static> = + Canonical::new(&[("rdf", RDF), ("dc", DC), ("xmp", XMP), ("xmpRights", XMP_RIGHTS), ("pdf", PDF), ("photoshop", PHOTOSHOP)]); // brand-ok: the XMP namespace prefix the files use /// The File Info fields a PDF gives, each `None` when the file gives none (or only blank text). #[derive(Clone, Debug, Default, PartialEq, Eq)] @@ -28,10 +38,15 @@ pub struct FileInfo { pub title: Option<String>, /// XMP `dc:creator` (its names joined with ", "), else Info `Author`. pub author: Option<String>, + /// XMP `photoshop:AuthorsPosition`. + pub author_title: Option<String>, /// XMP `dc:description` (its `x-default` item, else its first), else Info `Subject`. pub description: Option<String>, /// XMP `dc:subject`, else XMP `pdf:Keywords` or Info `Keywords` split at commas and semicolons. pub keywords: Option<Vec<String>>, + /// XMP `xmp:Rating`, a whole number from 0 to 5 (a rejected file's -1 and other values are + /// left out). + pub rating: Option<u8>, /// XMP `dc:rights` (its `x-default` item, else its first). pub copyright_notice: Option<String>, /// XMP `xmpRights:WebStatement`. @@ -73,42 +88,115 @@ fn packet(pdf: &Pdf) -> Option<Vec<u8>> { } /// The File Info fields of an XMP packet; `None` when it isn't XML in UTF-8 or UTF-16, or when its -/// elements nest more than [`MAX_NESTING`] deep. +/// [`xmp`] of `packet`; `None` when it isn't XML in UTF-8 or UTF-16, or when its elements nest +/// more than [`MAX_NESTING`] deep. fn xmp(packet: &[u8]) -> Option<FileInfo> { + read_xmp(packet, false) +} + +/// The File Info fields of the metadata template `bytes`, an XMP packet as [`metadata_template`] +/// writes one (or any XMP file); `None` when it is longer than [`MAX_TEMPLATE_BYTES`], isn't XML in +/// UTF-8 or UTF-16, has no `rdf:RDF` element, or nests more than [`MAX_NESTING`] deep. +pub fn read_template(bytes: &[u8]) -> Option<FileInfo> { + if bytes.len() > MAX_TEMPLATE_BYTES { + return None; + } + read_xmp(bytes, true) +} + +/// [`xmp`]; with `need_rdf`, `None` for XML that has no `rdf:RDF` element. +fn read_xmp(packet: &[u8], need_rdf: bool) -> Option<FileInfo> { let text = xml_text(packet)?; - // roxmltree parses nested elements recursively. - if nesting(&text) > MAX_NESTING { + let opts = Options { + names: Names::Canonical(&XMP_NAMESPACES), + doctype: Doctype::Reject, + limits: Limits { max_depth: MAX_NESTING, ..Limits::DEFAULT }, + ..Options::default() + } + .strict(); + let root = opts.parse(text.as_bytes()).ok()?; + let rdfs: Vec<&El> = std::iter::once(&root).chain(root.descendants()).filter(|n| n.is("rdf:RDF")).collect(); + if need_rdf && rdfs.is_empty() { return None; } - let xml = roxmltree::Document::parse(&text).ok()?; // The resource's own descriptions: those right under `rdf:RDF`, not the ones inside a value. - let descriptions: Vec<Node<'_, '_>> = xml - .descendants() - .filter(|n| n.has_tag_name((RDF, "RDF"))) - .flat_map(|rdf| rdf.children()) - .filter(|n| n.has_tag_name((RDF, "Description"))) - .collect(); - let get = |ns: &str, name: &str| property(&descriptions, ns, name); - let first = |ns: &str, name: &str| get(ns, name).into_iter().next(); - let creators = get(DC, "creator"); - let subjects = get(DC, "subject"); + let descriptions: Vec<&El> = rdfs.iter().flat_map(|rdf| rdf.children("rdf:Description")).collect(); + let get = |name: &str| property(&descriptions, name); + let first = |name: &str| get(name).into_iter().next(); + let creators = get("dc:creator"); + let subjects = get("dc:subject"); Some(FileInfo { - title: first(DC, "title"), + title: first("dc:title"), author: (!creators.is_empty()).then(|| creators.join(", ")), - description: first(DC, "description"), - keywords: if subjects.is_empty() { first(PDF, "Keywords").map(|k| split(&k)).filter(|k| !k.is_empty()) } else { Some(subjects) }, - copyright_notice: first(DC, "rights"), - copyright_url: first(XMP_RIGHTS, "WebStatement"), - copyrighted: first(XMP_RIGHTS, "Marked").and_then(|m| match m.to_ascii_lowercase().as_str() { + author_title: first("photoshop:AuthorsPosition"), // brand-ok: the XMP property name the files use + description: first("dc:description"), + keywords: if subjects.is_empty() { first("pdf:Keywords").map(|k| split(&k)).filter(|k| !k.is_empty()) } else { Some(subjects) }, + rating: first("xmp:Rating").and_then(|r| rating(&r)), + copyright_notice: first("dc:rights"), + copyright_url: first("xmpRights:WebStatement"), + copyrighted: first("xmpRights:Marked").and_then(|m| match m.to_ascii_lowercase().as_str() { "true" => Some(true), "false" => Some(false), _ => None, }), - created: first(XMP, "CreateDate").and_then(|d| xmp_date(&d)), - modified: first(XMP, "ModifyDate").and_then(|d| xmp_date(&d)), + created: first("xmp:CreateDate").and_then(|d| xmp_date(&d)), + modified: first("xmp:ModifyDate").and_then(|d| xmp_date(&d)), }) } +/// An `xmp:Rating` value as File Info takes one: a whole number from 0 to 5, written as an integer +/// or as a real with no fraction (`3`, `3.0`). The rejected rating -1, fractions and other values +/// give `None`. +fn rating(s: &str) -> Option<u8> { + let r: f64 = s.trim().parse().ok()?; + (r.fract() == 0.0 && (0.0..=5.0).contains(&r)).then_some(r as u8) +} + +/// The metadata template of `f`: an XMP packet (ISO 16684-1) holding its title (`dc:title`), author +/// (`dc:creator`), author title (`photoshop:AuthorsPosition`), description (`dc:description`), +/// keywords (`dc:subject`), rating (`xmp:Rating`), copyright status (`xmpRights:Marked`), notice +/// (`dc:rights`) and URL (`xmpRights:WebStatement`), each where `f` gives it, which +/// [`read_template`] reads back. The dates are left out. +pub fn metadata_template(f: &FileInfo) -> String { + use crate::post::xml_text as esc; + let alt = |name: &str, v: &str| format!(" <{name}><rdf:Alt><rdf:li xml:lang=\"x-default\">{}</rdf:li></rdf:Alt></{name}>\n", esc(v)); + let simple = |name: &str, v: &str| format!(" <{name}>{}</{name}>\n", esc(v)); + let blank = |v: &Option<String>| v.as_deref().map(str::trim).filter(|v| !v.is_empty()).map(str::to_string); + let mut props = String::new(); + if let Some(v) = blank(&f.title) { + props.push_str(&alt("dc:title", &v)); + } + if let Some(v) = blank(&f.author) { + props.push_str(&format!(" <dc:creator><rdf:Seq><rdf:li>{}</rdf:li></rdf:Seq></dc:creator>\n", esc(&v))); + } + if let Some(v) = blank(&f.author_title) { + props.push_str(&simple("photoshop:AuthorsPosition", &v)); // brand-ok: the XMP property name the files use + } + if let Some(v) = blank(&f.description) { + props.push_str(&alt("dc:description", &v)); + } + let keywords: Vec<&str> = f.keywords.iter().flatten().map(|k| k.trim()).filter(|k| !k.is_empty()).collect(); + if !keywords.is_empty() { + let items: String = keywords.iter().map(|k| format!("<rdf:li>{}</rdf:li>", esc(k))).collect(); + props.push_str(&format!(" <dc:subject><rdf:Bag>{items}</rdf:Bag></dc:subject>\n")); + } + if let Some(r) = f.rating { + props.push_str(&simple("xmp:Rating", &r.to_string())); + } + if let Some(c) = f.copyrighted { + props.push_str(&simple("xmpRights:Marked", if c { "True" } else { "False" })); + } + if let Some(v) = blank(&f.copyright_notice) { + props.push_str(&alt("dc:rights", &v)); + } + if let Some(v) = blank(&f.copyright_url) { + props.push_str(&simple("xmpRights:WebStatement", &v)); + } + format!( + "<?xpacket begin=\"\u{FEFF}\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n<x:xmpmeta xmlns:x=\"{X}\">\n <rdf:RDF xmlns:rdf=\"{RDF}\">\n <rdf:Description rdf:about=\"\" xmlns:dc=\"{DC}\" xmlns:xmp=\"{XMP}\" xmlns:xmpRights=\"{XMP_RIGHTS}\" xmlns:photoshop=\"{PHOTOSHOP}\">\n{props} </rdf:Description>\n </rdf:RDF>\n</x:xmpmeta>\n<?xpacket end=\"w\"?>\n" // brand-ok: the XMP namespace prefix the files use + ) +} + /// A packet's text: UTF-8 (with or without a byte order mark), or UTF-16 told by its byte order /// mark or by a zero byte beside the `<` it starts with. fn xml_text(b: &[u8]) -> Option<String> { @@ -123,58 +211,14 @@ fn xml_text(b: &[u8]) -> Option<String> { } } -/// How deep the elements of `xml` nest: start tags less end tags, at most, outside comments, -/// CDATA sections, processing instructions, declarations and quoted attribute values. -fn nesting(xml: &str) -> usize { - let b = xml.as_bytes(); - let (mut depth, mut most, mut i) = (0usize, 0usize, 0usize); - // The index just past the first `end` at or after `from` (the end of the text if none). - let past = |from: usize, end: &[u8]| { - b.get(from..).and_then(|rest| rest.windows(end.len()).position(|w| w == end)).map_or(b.len(), |at| from + at + end.len()) - }; - while let Some(at) = b.get(i..).and_then(|rest| rest.iter().position(|&c| c == b'<')) { - let start = i + at; - let rest = b.get(start..).unwrap_or_default(); - if rest.starts_with(b"<!--") { - i = past(start + 4, b"-->"); - } else if rest.starts_with(b"<![CDATA[") { - i = past(start + 9, b"]]>"); - } else if rest.starts_with(b"<?") { - i = past(start + 2, b"?>"); - } else if rest.starts_with(b"<!") || rest.starts_with(b"</") { - depth = depth.saturating_sub(usize::from(rest.starts_with(b"</"))); - i = past(start + 2, b">"); - } else { - // A start tag: up to its `>` outside quotes; `/>` closes it at once. - let mut j = start + 1; - let mut quote = None; - while let Some(&c) = b.get(j) { - match (quote, c) { - (None, b'"' | b'\'') => quote = Some(c), - (Some(q), _) if c == q => quote = None, - (None, b'>') => break, - _ => {} - } - j += 1; - } - if b.get(j.saturating_sub(1)) != Some(&b'/') { - depth += 1; - most = most.max(depth); - } - i = j + 1; - } - } - most -} - -/// The values of property `ns` `name` on the first of `descriptions` that gives it: an attribute +/// The values of property `name` on the first of `descriptions` that gives it: an attribute /// of the `rdf:Description`, or a property element's items ([`items`]), blank ones left out. -fn property(descriptions: &[Node<'_, '_>], ns: &str, name: &str) -> Vec<String> { +fn property(descriptions: &[&El], name: &str) -> Vec<String> { for d in descriptions { - if let Some(v) = d.attribute((ns, name)).map(str::trim).filter(|v| !v.is_empty()) { + if let Some(v) = d.attr(name).map(str::trim).filter(|v| !v.is_empty()) { return vec![v.to_string()]; } - let found = d.children().filter(|c| c.has_tag_name((ns, name))).map(items).find(|v| !v.is_empty()); + let found = d.children(name).map(items).find(|v| !v.is_empty()); if let Some(v) = found { return v; } @@ -185,14 +229,10 @@ fn property(descriptions: &[Node<'_, '_>], ns: &str, name: &str) -> Vec<String> /// The items of property element `p`: the `rdf:li` of its `rdf:Seq`, `rdf:Bag` or `rdf:Alt` (the /// `x-default` language item first), else its own value ([`value_of`]); trimmed, blank ones left /// out. -fn items(p: Node<'_, '_>) -> Vec<String> { - let array = p.children().find(|c| ["Seq", "Bag", "Alt"].into_iter().any(|t| c.has_tag_name((RDF, t)))); +fn items(p: &El) -> Vec<String> { + let array = p.elements().find(|c| matches!(c.name.as_str(), "rdf:Seq" | "rdf:Bag" | "rdf:Alt")); let mut values: Vec<(bool, String)> = match array { - Some(a) => a - .children() - .filter(|c| c.has_tag_name((RDF, "li"))) - .map(|li| (li.attribute((XML, "lang")).is_some_and(|l| l.eq_ignore_ascii_case("x-default")), value_of(li))) - .collect(), + Some(a) => a.children("rdf:li").map(|li| (li.attr("xml:lang").is_some_and(|l| l.eq_ignore_ascii_case("x-default")), value_of(li))).collect(), None => vec![(false, value_of(p))], }; // A stable sort: the `x-default` item first, the others in their order. @@ -203,19 +243,19 @@ fn items(p: Node<'_, '_>) -> Vec<String> { /// The value of element `n`: the URI of its `rdf:resource` attribute (how RDF writes a URI value); /// for a qualified value, its `rdf:value` (an attribute or an element, on `n` or on an /// `rdf:Description` inside it), without the qualifiers; else the text inside it. -fn value_of(mut n: Node<'_, '_>) -> String { +fn value_of(mut n: &El) -> String { // Each step goes to an element inside `n`, so the loop ends. loop { - if let Some(uri) = n.attribute((RDF, "resource")) { + if let Some(uri) = n.attr("rdf:resource") { return uri.to_string(); } - let holder = n.children().find(|c| c.has_tag_name((RDF, "Description"))).unwrap_or(n); - if let Some(v) = holder.attribute((RDF, "value")) { + let holder = n.child("rdf:Description").unwrap_or(n); + if let Some(v) = holder.attr("rdf:value") { return v.to_string(); } - match holder.children().find(|c| c.has_tag_name((RDF, "value"))) { + match holder.child("rdf:value") { Some(v) => n = v, - None => return n.descendants().filter(|d| d.is_text()).filter_map(|d| d.text()).collect(), + None => return n.deep_text(), } } } diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index ac1d77f372..eaff6c781f 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -12,7 +12,9 @@ //! conversion leaves unchanged (an sRGB profile) keeps its JPEG data. A black-and-white image whose //! converted levels are grey is compressed as greyscale. A colour image the Output settings also //! convert to their destination ([`Pixels`]) goes from its profile to sRGB, then to the -//! destination; a grey one keeps its profile there, as grey pixels are not converted. +//! destination, and so does one converted from its profile to an RGB destination whose untagged +//! images keep their numbers (Preserve Numbers); a grey one keeps its profile there, as grey +//! pixels are not converted. //! //! CMYK images ([`ImageBlob::cmyk`]) stay CMYK: a CMYK JPEG already as asked is embedded as it is //! when its numbers are kept; the others' ink amounts are resampled, converted when the Output @@ -20,6 +22,9 @@ //! inverted samples, which the PDF writer's Decode array undoes. A CMYK image whose numbers are //! kept carries the CMYK profile it is given ([`cmyk_icc`]), whether it is embedded as it is or //! written again; without one it is untagged, a JPEG's own `ICC_PROFILE` segments included. +//! With Don't Include Profiles set ([`SourceProfiles::Remove`], [`CmykTag::Removed`]), a JPEG +//! embedded as it is loses its `ICC_PROFILE` segments, its other segments and compressed samples +//! unchanged. use std::io::Cursor; use std::sync::Arc; @@ -152,10 +157,10 @@ pub(crate) fn from_decoded(img: DynamicImage, icc: Option<Vec<u8>>, interpolate: } /// Image `bytes` decoded within [`limits`], with the ICC profile it carries ([`source_icc`]) when -/// `profiles` allows it (not in PDF/X-1a, which allows no ICC-based color spaces), as -/// [`from_decoded`] writes it. `None` when it can't be decoded. -pub(crate) fn decoded_image(bytes: &[u8], interpolate: bool, sixteen_bit: bool, profiles: bool) -> Option<Image> { - from_decoded(decoded(bytes)?, profiles.then(|| source_icc(bytes)).flatten(), interpolate, sixteen_bit) +/// `profiles` keeps it ([`SourceProfiles::Keep`]), as [`from_decoded`] writes it. `None` when it +/// can't be decoded. +pub(crate) fn decoded_image(bytes: &[u8], interpolate: bool, sixteen_bit: bool, profiles: SourceProfiles) -> Option<Image> { + from_decoded(decoded(bytes)?, (profiles == SourceProfiles::Keep).then(|| source_icc(bytes)).flatten(), interpolate, sixteen_bit) } /// Are all of the RGBA pixels `rgba` grey? @@ -317,17 +322,69 @@ pub(crate) struct Recoded { /// Set when the image's colors are converted to the destination without its ICC profile, /// which can't be read. pub note: Option<&'static str>, + /// Set when the colors were to be converted but the image couldn't be decoded within the + /// allowance or written with them: the source image, kept as it is, would be in its own colors. + pub unconverted: bool, } -/// How [`recode`] converts a gray or RGB image that carries an ICC profile to sRGB (Convert to -/// Destination, [`crate::output::ColorOut::image_srgb_intent`]): the destination when it is sRGB, -/// else the step before the image's [`Pixels`] conversion. -#[derive(Clone, Copy, Debug)] -pub(crate) struct ToSrgb { +/// How [`recode`] converts a gray or RGB image that carries an ICC profile to sRGB +/// ([`crate::output::ColorOut::image_srgb_intent`]): the destination when it is sRGB, else the +/// step before the image's [`Pixels`] conversion. +#[derive(Clone, Copy)] +pub(crate) struct ToSrgb<'a> { /// The rendering intent of the conversion. pub intent: Intent, /// 16-bit samples may be written (PDF 1.5 and later). pub sixteen_bit: bool, + /// The colour output whose [`crate::output::ColorOut::tagged_pixels`] then convert a colour + /// image converted from its profile, when other colour images are not converted (`recode`'s + /// `convert`): to an RGB destination whose untagged images keep their numbers (Preserve + /// Numbers). Its table is built when the first such image needs it. + pub then: Option<&'a crate::output::ColorOut>, + /// Gray images are converted too: with an sRGB destination + /// ([`crate::output::ColorOut::converts_grey_images`]). In the others they keep their profile. + pub grey: bool, +} + +/// What happens to the ICC profile a gray or RGB image carries +/// ([`crate::output::ColorOut::source_profiles`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum SourceProfiles { + /// The image keeps a well-formed gray or RGB profile ([`valid_icc`]). + Keep, + /// The image is untagged; a JPEG embedded as it is keeps its data unchanged (PDF/X-1a). + Untag, + /// The image is untagged and a JPEG embedded as it is loses its `ICC_PROFILE` segments, its + /// other segments and compressed samples unchanged (Don't Include Profiles). + Remove, +} + +/// The CMYK profile [`recode_cmyk`] tags a CMYK image that keeps its numbers with. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum CmykTag<'a> { + /// This profile ([`cmyk_icc`]). + Profile(&'a [u8]), + /// None; a JPEG embedded as it is keeps its data unchanged. + Untagged, + /// None, and a JPEG embedded as it is loses its `ICC_PROFILE` segments, its other segments + /// and compressed samples unchanged (Don't Include Profiles). + Removed, +} + +impl<'a> CmykTag<'a> { + /// The profile the image is tagged with. + fn icc(self) -> Option<&'a [u8]> { + match self { + Self::Profile(icc) => Some(icc), + Self::Untagged | Self::Removed => None, + } + } +} + +/// JPEG `bytes` as they are embedded: without their `ICC_PROFILE` segments with `remove` +/// ([`vectorcraft_doc::cmyk::jpeg_without_icc`]). `None` when those can't be taken out. +pub(crate) fn jpeg_data(bytes: &[u8], remove: bool) -> Option<Vec<u8>> { + if remove { vectorcraft_doc::cmyk::jpeg_without_icc(bytes) } else { Some(bytes.to_vec()) } } /// The ICC profile image `bytes` carries ([`source_icc`]), when it is a well-formed profile of @@ -474,21 +531,25 @@ fn resample_channels(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> Dynamic /// Encoded image `bytes` placed `size` points wide and high, as the Compression settings `c` ask: /// resampled when its resolution is above the threshold, compressed with ZIP or JPEG, its colours /// converted by `convert` (colour images). Pixels that keep their colours keep the ICC profile -/// they carry when `profiles` allows it (not in PDF/X-1a, which allows no ICC-based color spaces); -/// with `to_srgb`, pixels in a gray or RGB profile other than sRGB are converted from it to sRGB -/// instead ([`ToSrgb`]), and colour ones then by `convert`; grey ones that `convert` leaves as -/// they are keep their profile. `interpolate` lets viewers smooth it. An image that can't be -/// decoded is kept as it is, with a warning when its pixels were to be converted to sRGB. +/// they carry when `profiles` keeps it ([`SourceProfiles::Keep`]); with `to_srgb`, pixels in a +/// gray or RGB profile other than sRGB are converted from it to sRGB instead ([`ToSrgb`]), and +/// colour ones then by `convert`, or without it by the conversion `to_srgb` gives +/// ([`ToSrgb::then`]); grey ones keep their profile unless the destination is sRGB +/// ([`ToSrgb::grey`]). `interpolate` lets viewers smooth it. An image that can't be decoded is +/// kept as it is, with a warning when its pixels were to be converted to sRGB. When `convert` +/// was to convert its colors, it is [`Recoded::unconverted`] if its header can't be read (it may +/// be in color) or its pixels are beyond the decode allowance; a color image whose pixel data +/// can't be read is not. pub(crate) fn recode( bytes: &[u8], size: (f64, f64), c: &CompressionSettings, interpolate: bool, convert: Option<&Pixels>, - profiles: bool, + profiles: SourceProfiles, to_srgb: Option<ToSrgb>, ) -> Recoded { - let keep = Recoded { image: None, warning: None, note: None }; + let keep = Recoded { image: None, warning: None, note: None, unconverted: convert.is_some() }; let Ok(reader) = ImageReader::new(Cursor::new(bytes)).with_guessed_format() else { return keep }; let jpeg = reader.format() == Some(ImageFormat::Jpeg); let Ok(mut decoder) = reader.into_decoder() else { return keep }; @@ -496,8 +557,9 @@ pub(crate) fn recode( use ExtendedColorType as T; let grey = matches!(decoder.original_color_type(), T::L1 | T::La1 | T::L2 | T::La2 | T::L4 | T::La4 | T::L8 | T::La8 | T::L16 | T::La16); // Pixels in a profile they are converted from are decoded, whatever the Compression settings. - // Grey pixels, which `convert` leaves as they are, keep their profile when it converts. - let to_srgb = to_srgb.filter(|_| !(grey && convert.is_some())); + // Grey pixels keep their profile unless the destination is sRGB ([`ToSrgb::grey`]). + let then = to_srgb.and_then(|t| t.then); + let to_srgb = to_srgb.filter(|t| !grey || t.grey); // Converted to the destination as sRGB, as before, when the profile can't be read. let mut note = None; let source = match to_srgb.and_then(|t| Some((source_profile(bytes, if grey { *b"GRAY" } else { *b"RGB " })?, t))) { @@ -506,23 +568,25 @@ pub(crate) fn recode( note = Some(CONVERTED_AS_SRGB); None } - Some((None, _)) => return Recoded { image: None, warning: Some(UNCONVERTED), note: None }, + Some((None, _)) => return Recoded { image: None, warning: Some(UNCONVERTED), note: None, unconverted: false }, None => None, }; // Pixels that can't be decoded are kept as they are, with a warning when they were to be // converted. - let keep = if source.is_some() { Recoded { image: None, warning: Some(UNDECODED), note: None } } else { keep }; + let keep = if source.is_some() { Recoded { warning: Some(UNDECODED), ..keep } } else { keep }; // What the header declares is decoded within the image allowance, not whatever it asks for. + // Grey pixels aren't converted. if decoder.set_limits(limits()).is_err() { - return keep; + return Recoded { unconverted: convert.is_some() && !grey, ..keep }; } let (mut kind, pixels) = if grey { // Only the pixels tell monochrome images from greyscale ones: decoded unless both keep it. let (g, m) = (rule(c, Kind::Gray), rule(c, Kind::Mono)); if source.is_none() && kept(&g, dims, size, jpeg) && kept(&m, dims, size, jpeg) && g.instead == m.instead { - return Recoded { image: None, warning: g.instead, note: None }; + return Recoded { image: None, warning: g.instead, note: None, unconverted: false }; } - let Ok(img) = DynamicImage::from_decoder(decoder) else { return keep }; + // Grey pixels aren't converted. + let Ok(img) = DynamicImage::from_decoder(decoder) else { return Recoded { unconverted: false, ..keep } }; (if bilevel(&img) { Kind::Mono } else { Kind::Gray }, Some(img)) } else { (Kind::Color, None) @@ -530,9 +594,16 @@ pub(crate) fn recode( let mut rule = rule(c, kind); let convert = convert.filter(|_| kind == Kind::Color); if kept(&rule, dims, size, jpeg) && convert.is_none() && source.is_none() { - return Recoded { image: None, warning: rule.instead, note: None }; + return Recoded { image: None, warning: rule.instead, note: None, unconverted: false }; } - let Some(mut img) = pixels.or_else(|| decoded(bytes)) else { return keep }; + // Pixels that can't be read can't be written in their own colors either; ones beyond the + // allowance can. + let mut img = match pixels.map_or_else(|| decoded_within(bytes), Ok) { + Ok(img) => img, + Err(limited) => return Recoded { unconverted: limited && convert.is_some(), ..keep }, + }; + // Converted from its profile: then by `convert`, else by the conversion `to_srgb` gives. + let mut from_profile = false; if let Some((p, t)) = &source { let srgb = match into_srgb(img, p, t.intent) { Some(s) => Some(s), @@ -542,7 +613,7 @@ pub(crate) fn recode( note = Some(CONVERTED_AS_SRGB); None } - None => return Recoded { image: None, warning: Some(UNCONVERTED), note: None }, + None => return Recoded { image: None, warning: Some(UNCONVERTED), note: None, unconverted: false }, }; img = match srgb { Some((srgb, changed)) => { @@ -550,30 +621,39 @@ pub(crate) fn recode( if kind == Kind::Mono && !bilevel(&srgb) { (kind, rule) = (Kind::Gray, self::rule(c, Kind::Gray)); } + from_profile = true; // Written as it is only when nothing converts it further. - let as_is = kept(&rule, dims, size, jpeg) && convert.is_none(); + let as_is = kept(&rule, dims, size, jpeg) && convert.is_none() && then.is_none(); // A JPEG kept as JPEG whose samples the conversion leaves unchanged (an sRGB - // profile): its JPEG data, without the profile. - if !changed && as_is && jpeg { - let image = Image::from_jpeg_with_icc(bytes.to_vec().into(), None, interpolate).ok(); - return Recoded { image, warning: rule.instead, note: None }; + // profile): its JPEG data, without the profile (and, with `Remove`, without its + // segments: encoded again when those can't be taken out). + if !changed + && as_is + && jpeg + && let Some(data) = jpeg_data(bytes, profiles == SourceProfiles::Remove) + { + let image = Image::from_jpeg_with_icc(data.into(), None, interpolate).ok(); + return Recoded { image, warning: rule.instead, note: None, unconverted: false }; } // Not resampled and lossless: written at its own depth. if as_is && jpeg_quality(&rule, jpeg).is_none() { - return Recoded { image: from_decoded(srgb, None, interpolate, t.sixteen_bit), warning: rule.instead, note: None }; + let image = from_decoded(srgb, None, interpolate, t.sixteen_bit); + return Recoded { image, warning: rule.instead, note: None, unconverted: false }; } srgb } - None => { - let Some(img) = decoded(bytes) else { return keep }; - img - } + None => match decoded_within(bytes) { + Ok(img) => img, + Err(limited) => return Recoded { unconverted: limited && convert.is_some(), ..keep }, + }, }; } + let convert = if from_profile { convert.or_else(|| then.and_then(crate::output::ColorOut::tagged_pixels)) } else { convert }; // Pixels that keep their colours keep the profile they are in; converted ones are in the // destination's. let want = if kind == Kind::Color { *b"RGB " } else { *b"GRAY" }; - let icc = (profiles && convert.is_none() && source.is_none()).then(|| source_icc(bytes)).flatten().filter(|icc| valid_icc(icc, want)); + let keeps = profiles == SourceProfiles::Keep && convert.is_none() && source.is_none(); + let icc = keeps.then(|| source_icc(bytes)).flatten().filter(|icc| valid_icc(icc, want)); let rgb_icc = icc.is_some() && kind == Kind::Color; let mut rgba = resample(img, &rule, sized(&rule, dims, size)).into_rgba8(); if kind == Kind::Mono { @@ -601,7 +681,8 @@ pub(crate) fn recode( to_jpeg(&samples, space, width, height, q, interpolate, icc.as_deref().map(Vec::as_slice)) }); let image = jpeg.or_else(|| from_rgba(rgba.as_raw(), width, height, interpolate, convert, icc)); - Recoded { image, warning: rule.instead, note } + let unconverted = image.is_none() && convert.is_some(); + Recoded { image, warning: rule.instead, note, unconverted } } /// A colorized image's coverage (one sample a pixel, `w` × `h`, see @@ -630,8 +711,9 @@ pub(crate) fn coverage_sized(w: u32, h: u32, cover: Vec<u8>, size: (f64, f64), c /// is when its numbers are (`convert` is `None`); otherwise its ink amounts are resampled, /// converted by `convert` and compressed again. With `alpha` (one sample a pixel, see /// [`mask_alpha`]) the image is lossless and carries it as its soft mask; `None` then when its -/// inks can't be read. When its numbers are kept, the image is tagged with CMYK profile `icc` -/// (see [`cmyk_icc`]), and is untagged without one; converted pixels are never tagged with it. +/// inks can't be read. When its numbers are kept, the image is tagged as `tag` says, and is +/// untagged without a profile; converted pixels are never tagged with it. +/// With `convert`, an image whose inks can't be read or written is [`Recoded::unconverted`]. pub(crate) fn recode_cmyk( blob: &ImageBlob, size: (f64, f64), @@ -639,29 +721,38 @@ pub(crate) fn recode_cmyk( interpolate: bool, convert: Option<&CmykPixels>, alpha: Option<Vec<u8>>, - icc: Option<&[u8]>, + tag: CmykTag<'_>, ) -> Recoded { let rule = rule(c, Kind::Color); let jpeg = jpeg_components(&blob.bytes).is_some(); - let icc = icc.filter(|_| convert.is_none()); + let icc = tag.icc().filter(|_| convert.is_none()); if jpeg && convert.is_none() && alpha.is_none() { let dims = ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().ok().and_then(|r| r.into_dimensions().ok()); - if let Some((w, h)) = dims.filter(|d| kept(&rule, *d, size, true)) { - // The JPEG data as it is, tagged with `icc` rather than with its own segments; one - // larger than [`MAX_EMBED_PIXELS`] is not written. + // The JPEG data as it is (without its `ICC_PROFILE` segments with `CmykTag::Removed`: its + // inks are encoded again when those can't be taken out), tagged with `icc` rather than + // with its own segments; one larger than [`MAX_EMBED_PIXELS`] is not written. + if let Some((w, h)) = dims.filter(|d| kept(&rule, *d, size, true)) + && let Some(data) = jpeg_data(&blob.bytes, tag == CmykTag::Removed) + { let image = (u64::from(w) * u64::from(h) <= MAX_EMBED_PIXELS) - .then(|| Image::from_jpeg_with_icc(blob.bytes.as_ref().clone().into(), icc.map(|i| i.to_vec().into()), interpolate).ok()) + .then(|| Image::from_jpeg_with_icc(data.into(), icc.map(|i| i.to_vec().into()), interpolate).ok()) .flatten(); - return Recoded { image, warning: rule.instead, note: None }; + return Recoded { image, warning: rule.instead, note: None, unconverted: false }; } } + // Inks that can't be read can't be converted: the image is not to be kept as it is. + let unconverted = Recoded { image: None, warning: None, note: None, unconverted: true }; let Some(inks) = blob.cmyk() else { - return Recoded { image: None, warning: Some(if jpeg { CMYK_KEPT } else { CMYK_RGB }), note: None }; + if convert.is_some() { + return unconverted; + } + return Recoded { image: None, warning: Some(if jpeg { CMYK_KEPT } else { CMYK_RGB }), note: None, unconverted: false }; }; let (width, height) = sized(&rule, (inks.width, inks.height), size); let (inks, alpha) = match resampled_inks(inks, alpha, &rule, (width, height)) { Ok(r) => r, - Err(warning) => return Recoded { image: None, warning, note: None }, + Err(_) if convert.is_some() => return unconverted, + Err(warning) => return Recoded { image: None, warning, note: None, unconverted: false }, }; let (samples, space) = match convert { Some(p) => p.convert(&inks), @@ -670,7 +761,8 @@ pub(crate) fn recode_cmyk( // JPEG needs opaque pixels. let image = jpeg_quality(&rule, jpeg).filter(|_| alpha.is_none()).and_then(|q| to_jpeg(&samples, space, width, height, q, interpolate, icc)); let image = image.or_else(|| lossless(samples, alpha, space, width, height, interpolate, icc)); - Recoded { image, warning: rule.instead, note: None } + let unconverted = image.is_none() && convert.is_some(); + Recoded { image, warning: rule.instead, note: None, unconverted } } /// Ink amounts (four bytes a pixel) and their alpha (one byte a pixel), if any. @@ -715,9 +807,15 @@ fn limits() -> image::Limits { /// `bytes` decoded within [`limits`]: an image whose header asks for more is not decoded. fn decoded(bytes: &[u8]) -> Option<DynamicImage> { - let mut r = ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?; + decoded_within(bytes).ok() +} + +/// `bytes` decoded like [`decoded`]; on failure, whether the decoder stopped at [`limits`] +/// (`true`) rather than at data it can't read (`false`). +fn decoded_within(bytes: &[u8]) -> Result<DynamicImage, bool> { + let mut r = ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|_| false)?; r.limits(limits()); - r.decode().ok() + r.decode().map_err(|e| matches!(e, image::ImageError::Limits(_))) } /// The alpha an opacity mask whose art is greyscale image `blob` alone gives the image of diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index 0d50c58f31..e6e34ae429 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -361,8 +361,9 @@ impl<'p> Builder<'p> { Some(MaskSpec::Mask(m)) => (opacity, Some(m.clone())), None => (opacity, None), }; - // Isolation only shows with blending inside; knockout with several objects. - let isolate = isolate && Node::children_blend(&children, &mut |c| c.blends_through()); + // Isolation only shows with blending or overprinting inside; knockout with several + // objects. + let isolate = isolate && (Node::children_blend(&children, &mut |c| c.blends_through()) || children_overprint(&children)); let knockout = knockout && children.len() > 1; let plain = opacity >= 0.999 && blend == BlendMode::Normal && mask.is_none() && !isolate && !knockout; if children.is_empty() { @@ -747,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); @@ -1183,3 +1191,16 @@ fn visual_glyph_text(text: String) -> String { let chars: Vec<char> = text.chars().collect(); order.iter().filter_map(|&i| chars.get(i)).collect() } + +/// Whether a visible fill or stroke among `children` overprints, characters' too, directly or +/// through children that don't isolate. In an isolated group an overprinting object is drawn on +/// the group's empty backdrop, so it covers the inks of the art below the group that it does not +/// paint; without isolation it leaves them. +fn children_overprint(children: &[Arc<Node>]) -> bool { + children.iter().any(|c| { + c.visible + && (c.appearance.items.iter().any(|i| i.visible() && i.overprint()) + || matches!(&c.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke)) + || (!c.isolate && c.children().is_some_and(|ch| children_overprint(ch)))) + }) +} diff --git a/crates/pdf/src/import/entry.rs b/crates/pdf/src/import/entry.rs index 8503b4fb20..8f84b9a332 100644 --- a/crates/pdf/src/import/entry.rs +++ b/crates/pdf/src/import/entry.rs @@ -239,6 +239,14 @@ pub fn imports_of(bytes: &[u8]) -> usize { IMPORTS.lock().ok().and_then(|i| i.get(&(bytes.as_ptr() as usize)).copied()).unwrap_or(0) } +/// The widest bleed of `pages` on each side (`[top, bottom, left, right]`, see [`crate::pages::bleed`]). +fn widest_bleed<'p, 'd: 'p>(pages: impl Iterator<Item = &'p craft_pdf::syntax::page::Page<'d>>) -> [f64; 4] { + pages.fold([0.0; 4], |widest, page| { + let bleed = crate::pages::bleed(page); + std::array::from_fn(|i| widest[i].max(bleed[i])) + }) +} + /// [`read_with_reader_options`] of `original`, the PDF `bytes` read with `reader`. fn read_opened( bytes: &[u8], @@ -286,15 +294,17 @@ fn read_opened( let mut nesting = Nesting::new(); // The top-level groups in the order the pages mark them, bottom first. let (mut order, mut known) = (vec![], HashSet::new()); + // Artboards on the trim boxes have the bleed boxes round them as the document's bleed, so the + // art there shows and prints as bleed. + if opts.crop == CropTo::Trim { + doc.setup.bleed = widest_bleed(picked.iter().filter_map(|&n| pages.get(n))); + } + // The artboards are the gap apart plus the document's bleed on both sides, which export adds + // round every artboard, so no page's bleed reaches into the next artboard. + let [_, _, bleed_left, bleed_right] = doc.setup.bleed; + let spacing = opts.artboard_gap + bleed_left + bleed_right; for (i, &number) in picked.iter().enumerate() { let Some(page) = pages.get(number) else { continue }; - // Artboards on the trim boxes have the bleed boxes round them as the document's bleed - // (the widest of the pages' on each side), so the art there shows and prints as bleed. - if opts.crop == CropTo::Trim { - for (side, b) in doc.setup.bleed.iter_mut().zip(crate::pages::bleed(page)) { - *side = side.max(b); - } - } // The chosen box sits at (x, 0); the page draws round it. let (init, frame) = crate::pages::frame(page, opts.crop); let mut ab = Rect::new(x, 0.0, x + frame.width(), frame.height()); @@ -371,7 +381,7 @@ fn read_opened( right = right.max(art.x1); ab = art; } - x = right + opts.artboard_gap; + x = right + spacing; clear = right.max(art_right) + opts.artboard_gap; doc.artboards.push(Artboard { id: i as u32 + 1, 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<Node>]) -> Option<Rect> { } pub(super) fn rgba_png(rgba: Vec<u8>, w: u32, h: u32) -> Option<Vec<u8>> { - 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<u8>, w: u32, h: u32) -> Option<Vec<u8>> { - 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<u8> { diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 8f9959c77f..9cef615783 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -76,7 +76,7 @@ mod syntax; pub use editing::{EDITING_FILE, Editing, LEGACY_EDITING_FILE, editing, editing_with}; pub use encrypt::Encryption; pub use export::{check_page_sizes, export, export_with_report, page_areas}; -pub use file_info::{FileInfo, file_info}; +pub use file_info::{FileInfo, MAX_TEMPLATE_BYTES, file_info, metadata_template, read_template}; #[cfg(any(test, feature = "read-count"))] pub use import::imports_of; pub use import::{ @@ -134,7 +134,8 @@ impl PdfOptions { pub struct ImportOptions { /// Import at most this many pages (of those picked); `None` = all of them. pub max_pages: Option<usize>, - /// Horizontal gap in points between the artboards created for consecutive pages. + /// Horizontal gap in points between the artboards created for consecutive pages (on trim + /// boxes, plus the document's bleed on both sides). pub artboard_gap: f64, /// 0-based pages to import, in this order; `None` = every page. pub pages: Option<Vec<usize>>, diff --git a/crates/pdf/src/output.rs b/crates/pdf/src/output.rs index 92381e1628..f5e4bb6e36 100644 --- a/crates/pdf/src/output.rs +++ b/crates/pdf/src/output.rs @@ -14,7 +14,10 @@ //! that carries an ICC profile is converted from it to sRGB with the same intent and written //! without it ([`ColorOut::image_srgb_intent`]); with `destination` and a destination its //! pixels are converted to (CMYK, another RGB space), a colour image is converted from its -//! profile to sRGB and then to the destination. Without conversion it keeps its profile. The +//! profile to sRGB and then to the destination. With `preserveNumbers` (and PDF/X-1a), which +//! keeps the numbers of untagged colours only, such an image is converted from its profile +//! whatever the destination: to sRGB, and then to a CMYK or other RGB destination +//! ([`ColorOut::tagged_pixels`]). Without conversion it keeps its profile. The //! destination is a profile name; empty, the document's profile for its colour mode. //! - Profiles ([`ProfileInclusion`]): with `all`, with `destination`, and with `taggedSource` on a //! document that was assigned profiles, colours are written in ICC-based colour spaces: CMYK @@ -24,7 +27,11 @@ //! always tag them, whatever `profiles` says; PDF/X-1a never does, and always converts to a //! CMYK destination (see [`crate::pdfx`]). A CMYK image that keeps its numbers is tagged with //! the CMYK profile it carries, if any, with `all` and `taggedSource`, and in PDF/A, PDF/X-3 -//! and PDF/X-4 unless `profiles` is `destination` ([`ColorOut::cmyk_image_icc`]). +//! and PDF/X-4 unless `profiles` is `destination` ([`ColorOut::cmyk_image_icc`]). When +//! `profiles` isn't set, colors are written as with `none` and gray and RGB images keep the +//! profiles they carry (but in PDF/X-1a); when it is set to `none`, no image keeps its own +//! profile, a JPEG's `ICC_PROFILE` segments included, except in PDF/A, PDF/X-3 and PDF/X-4 +//! ([`ColorOut::source_profiles`]). //! - Output intent: the profile `outputIntent` names, embedded as the `/GTS_PDFX` output intent //! of the catalog with the condition, identifier and registry; Trapped goes in the document //! information (`/False` when an output intent is written untrapped). PDF/A files carry their @@ -70,6 +77,9 @@ pub(crate) struct ColorOut { /// CMYK images that keep their numbers are tagged with the CMYK profile they carry /// ([`Self::cmyk_image_icc`]). image_icc: bool, + /// Don't Include Profiles was set, in a file that doesn't tag every color: no image keeps its + /// own ICC profile, a JPEG's `ICC_PROFILE` segments included ([`Self::source_profiles`]). + no_profiles: bool, /// The CMYK profile that tags CMYK colours. cmyk_profile: String, /// Tagged RGB colours are written as their sRGB equivalents: why (a warning), when their RGB @@ -77,6 +87,9 @@ pub(crate) struct ColorOut { pub srgb_note: Option<String>, /// The image transform, built when the first image needs it. pixels: OnceLock<Option<Pixels>>, + /// The transform of images converted from their profile, when it isn't `pixels` + /// ([`Self::tagged_pixels`]). + tagged_pixels: OnceLock<Option<Pixels>>, /// The CMYK image transform, built when the first CMYK image needs it. cmyk_pixels: OnceLock<Option<CmykPixels>>, intent: Intent, @@ -117,9 +130,11 @@ impl Default for ColorOut { dest: None, tagged: false, image_icc: false, + no_profiles: false, cmyk_profile, srgb_note: None, pixels: OnceLock::new(), + tagged_pixels: OnceLock::new(), cmyk_pixels: OnceLock::new(), intent, catalog: None, @@ -246,9 +261,11 @@ impl ColorOut { } out.dest = Some(Dest { srgb: name == cms::SRGB, cms, model, keep, destination }); } - out.tagged = matches!(set.standard, Standard::PdfA2b | Standard::PdfX3 | Standard::PdfX4) + let profiles = set.output.profiles.unwrap_or_default(); + let tags_all = matches!(set.standard, Standard::PdfA2b | Standard::PdfX3 | Standard::PdfX4); + out.tagged = tags_all || (!set.standard.cmyk_only() - && match set.output.profiles { + && match profiles { ProfileInclusion::None => false, ProfileInclusion::All | ProfileInclusion::Destination => true, ProfileInclusion::TaggedSource => !doc.color_profiles.is_empty(), @@ -256,11 +273,14 @@ impl ColorOut { // Source profiles: with `all` and `taggedSource`, and in the files that tag every colour // unless only the destination profile is asked for; never in PDF/X-1a. out.image_icc = !set.standard.cmyk_only() - && match set.output.profiles { + && match profiles { ProfileInclusion::All | ProfileInclusion::TaggedSource => true, - ProfileInclusion::None => matches!(set.standard, Standard::PdfA2b | Standard::PdfX3 | Standard::PdfX4), + ProfileInclusion::None => tags_all, ProfileInclusion::Destination => false, }; + // A set Don't Include Profiles leaves out every image's own profile, outside the files + // that tag every color. + out.no_profiles = set.output.profiles == Some(ProfileInclusion::None) && !tags_all; let rgb = match &out.dest { Some(d) if d.model == Model::Rgb => (d.srgb, d.cms.settings().rgb.clone()), _ => (source.rgb_is_srgb(), st.rgb.clone()), @@ -348,13 +368,49 @@ impl ColorOut { /// The intent a gray or RGB image that carries an ICC profile is converted from it to sRGB /// with ([`crate::images::recode`]): the colour settings' intent, with Convert to Destination /// and an sRGB destination, also when the document's RGB space is sRGB, or a destination - /// colour images' pixels are then converted to ([`Self::pixels`]: CMYK, another RGB space). - /// `None` otherwise, Preserve Numbers and an RGB destination that is the document's own RGB - /// profile (which leaves RGB colours and RGB images as they are) included: such an image - /// keeps its profile, or its numbers are converted as sRGB ones. + /// colour images' pixels are then converted to ([`Self::pixels`]: CMYK, another RGB space); + /// and with Preserve Numbers (and PDF/X-1a's own conversion), whatever the destination, as + /// only untagged colours of the destination's model keep their numbers. The pixels are then + /// converted by [`Self::tagged_pixels`]. `None` otherwise, an RGB destination that is the + /// document's own RGB profile with Convert to Destination (which leaves RGB colours and RGB + /// images as they are) included: such an image keeps its profile. pub(crate) fn image_srgb_intent(&self) -> Option<Intent> { - let d = self.dest.as_ref().filter(|d| d.destination)?; - ((d.model == Model::Rgb && d.srgb) || self.pixels().is_some()).then_some(self.intent) + let d = self.dest.as_ref()?; + let rgb = d.model == Model::Rgb && (d.srgb || !d.destination); + (rgb || self.pixels().is_some()).then_some(self.intent) + } + + /// Are gray images that carry an ICC profile converted from it to sRGB grays too + /// ([`Self::image_srgb_intent`])? Only with an sRGB destination; in the others, RGB tagged as + /// sRGB included, grey pixels are not converted and keep their profile. + pub(crate) fn converts_grey_images(&self) -> bool { + self.dest.as_ref().is_some_and(|d| d.model == Model::Rgb && d.srgb) + } + + /// The destination a colour image converted from its ICC profile to sRGB + /// ([`Self::image_srgb_intent`]) is then converted to when other colour images are not + /// ([`Self::pixels`]): with Preserve Numbers, an RGB destination other than sRGB, whose + /// untagged RGB images keep their numbers (unless RGB is tagged as sRGB). + fn tagged_rgb_dest(&self) -> Option<&Dest> { + self.dest.as_ref().filter(|d| !d.destination && d.model == Model::Rgb && !d.srgb && !self.tagged) + } + + /// Are colour images converted from their ICC profile then converted by + /// [`Self::tagged_pixels`]? + pub(crate) fn converts_tagged_pixels(&self) -> bool { + self.tagged_rgb_dest().is_some() + } + + /// How a colour image converted from its ICC profile to sRGB is then converted into that + /// destination's RGB space ([`Self::converts_tagged_pixels`]), built when the first such image + /// needs it; `None` when there is no such destination. + pub(crate) fn tagged_pixels(&self) -> Option<&Pixels> { + self.tagged_pixels + .get_or_init(|| { + let d = self.tagged_rgb_dest()?; + Some(Pixels::Rgb(Box::new(ProofLut::build(|rgb| d.cms.srgb_to_rgb(rgb))))) + }) + .as_ref() } /// The CMYK profile CMYK image `blob` is tagged with ([`crate::images::cmyk_icc`]): the one it @@ -367,6 +423,33 @@ impl ColorOut { crate::images::cmyk_icc(blob) } + /// How CMYK image `blob` is tagged ([`crate::images::recode_cmyk`]): with the profile + /// [`Self::cmyk_image_icc`] gives (`icc`), else untagged, without a JPEG's own `ICC_PROFILE` + /// segments when Don't Include Profiles was set. + pub(crate) fn cmyk_tag<'a>(&self, icc: Option<&'a [u8]>) -> crate::images::CmykTag<'a> { + use crate::images::CmykTag; + match icc { + Some(icc) => CmykTag::Profile(icc), + None if self.no_profiles => CmykTag::Removed, + None => CmykTag::Untagged, + } + } + + /// What happens to the ICC profile a gray or RGB image carries ([`crate::images::recode`]): + /// left out with its JPEG segments when Don't Include Profiles was set (not in PDF/A, PDF/X-3 + /// and PDF/X-4), left out of the color space in PDF/X-1a, which allows no ICC-based color + /// spaces, and kept otherwise, also when the Profiles setting isn't set. + pub(crate) fn source_profiles(&self) -> crate::images::SourceProfiles { + use crate::images::SourceProfiles; + if self.no_profiles { + SourceProfiles::Remove + } else if self.standard.cmyk_only() { + SourceProfiles::Untag + } else { + SourceProfiles::Keep + } + } + /// How CMYK images' ink amounts are converted; `None` when they keep their numbers (no /// conversion, or to a CMYK destination that keeps them). pub(crate) fn cmyk_pixels(&self) -> Option<&CmykPixels> { diff --git a/crates/pdf/src/post.rs b/crates/pdf/src/post.rs index c6fdd8048d..79e872e59b 100644 --- a/crates/pdf/src/post.rs +++ b/crates/pdf/src/post.rs @@ -180,7 +180,7 @@ fn rights_properties(info: &DocMetadata) -> String { /// `s` as XML character data: `&`, `<`, `>` and `"` escaped, a carriage return written as the /// character reference ` `, and the characters XML 1.0 doesn't allow left out. -fn xml_text(s: &str) -> String { +pub(crate) fn xml_text(s: &str) -> String { let mut out = String::with_capacity(s.len()); for c in s.chars() { match c { diff --git a/crates/pdf/src/print.rs b/crates/pdf/src/print.rs index 2a3cbf98af..54e85f44b4 100644 --- a/crates/pdf/src/print.rs +++ b/crates/pdf/src/print.rs @@ -187,7 +187,7 @@ pub fn printed_document<'a>(doc: &'a Document, set: &PrintSettings) -> Cow<'a, D // the art that prints; the layers kept are shown. let mut kept = doc.clone(); keep_layers(&mut kept.layers, set.print_layers); - let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true }; + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; let mut d = vectorcraft_effects::bake_document_placing_symbols(&kept, true, layers).unwrap_or(kept); composite_overprints(&mut d, set); Cow::Owned(d) diff --git a/crates/pdf/src/settings.rs b/crates/pdf/src/settings.rs index adaaa30c9c..c2f5487cbb 100644 --- a/crates/pdf/src/settings.rs +++ b/crates/pdf/src/settings.rs @@ -387,7 +387,12 @@ pub struct OutputSettings { /// Destination profile name (empty: the document's profile; [`DOCUMENT_CMYK`]: the CMYK /// profile in effect, whatever the document's colour mode). pub destination: String, - pub profiles: ProfileInclusion, + /// The Profile Inclusion setting; `None` (left out, `null` or `"default"`) when it isn't set: + /// colors are then written as with [`ProfileInclusion::None`], while gray and RGB images keep + /// the ICC profiles they carry. A set [`ProfileInclusion::None`] also leaves those out (see + /// [`crate::output`]). + #[serde(deserialize_with = "unset_or_choice")] + pub profiles: Option<ProfileInclusion>, /// PDF/X output intent profile name. pub output_intent: String, pub output_condition: String, @@ -397,6 +402,19 @@ pub struct OutputSettings { pub trapped: bool, } +/// The JSON id of a setting that isn't set ([`OutputSettings::profiles`]), as `null` is. +pub const UNSET_CHOICE: &str = "default"; + +/// A choice that may be left unset: `null` and [`UNSET_CHOICE`] are `None`, a choice's id is that +/// choice. +fn unset_or_choice<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Option<T>, D::Error> { + match Option::<String>::deserialize(d)? { + None => Ok(None), + Some(id) if id == UNSET_CHOICE => Ok(None), + Some(id) => T::deserialize(serde::de::value::StringDeserializer::<D::Error>::new(id)).map(Some), + } +} + /// The Advanced section. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] 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<Vec<u8>> { 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<Vec<u8>> { - 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<u8> { *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<u8> { +fn cut_image(format: craft_image_codecs::Format, tag: &[u8], keep: usize) -> Vec<u8> { 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/blend.rs b/crates/pdf/src/tests/blend.rs index 1cd5c949e0..25948763d8 100644 --- a/crates/pdf/src/tests/blend.rs +++ b/crates/pdf/src/tests/blend.rs @@ -195,7 +195,8 @@ fn a_knockout_group_without_blending_inside_is_isolated_only_when_it_isolates() /// An overprinting element of a knockout group that does not isolate is drawn in a `/K` group /// without `/I true`, so it overprints the art below the group, and its graphics state still -/// overprints (`/OP`, `/op`, `/OPM 1`). An isolated group keeps `/I true`. +/// overprints (`/OP`, `/op`, `/OPM 1`). An isolated group keeps `/I true`, reads back isolated +/// and is written with `/I true` again. #[test] fn an_overprinting_element_of_a_knockout_group_that_does_not_isolate_overprints_the_art_below() { for isolate in [false, true] { @@ -219,6 +220,42 @@ fn an_overprinting_element_of_a_knockout_group_that_does_not_isolate_overprints_ }); assert_eq!(overprints, [false, false, false, true], "isolate {isolate}"); assert_eq!(knockout_groups(&back), [3], "isolate {isolate}"); + let mut found = vec![]; + back.walk(|n| { + if n.knockout == vectorcraft_doc::Knockout::On { + found.push(n.isolate); + } + }); + assert_eq!(found, [isolate], "isolate {isolate}"); + assert_eq!(text(&back).matches("/Itrue").count(), usize::from(isolate), "isolate {isolate}"); + } +} + +/// An isolated group with nothing blending inside but an overprinting fill reads back as an +/// isolated group and is written with `/I true` again; a group that does not isolate reads back +/// as its objects. +#[test] +fn an_isolated_group_with_an_overprinting_object_reads_back_isolated() { + for isolate in [false, true] { + let mut d = Document::new(200.0, 200.0); + add(&mut d, rect(Rect::new(0.0, 0.0, 200.0, 200.0), (0.9, 0.8, 0.2))); + let mut top = rect(Rect::new(60.0, 60.0, 160.0, 160.0), (0.0, 0.0, 1.0)); + top.appearance.fill_mut().unwrap().overprint = true; + let mut below = rect(Rect::new(20.0, 20.0, 120.0, 120.0), (1.0, 0.0, 0.0)); + (below.id, top.id) = (d.alloc_id(), d.alloc_id()); + let mut g = Node::group(NodeId(0), vec![std::sync::Arc::new(below), std::sync::Arc::new(top)]); + g.isolate = isolate; + add(&mut d, g); + assert_eq!(text(&d).matches("/Itrue").count(), usize::from(isolate), "isolate {isolate}"); + let back = import(&export(&d, &PdfOptions::default()).unwrap()).unwrap_or_else(|e| panic!("isolate {isolate}: {e}")); + let mut groups = vec![]; + back.walk(|n| { + if matches!(n.kind, vectorcraft_doc::NodeKind::Group { .. }) { + groups.push(n.isolate); + } + }); + assert_eq!(groups, if isolate { vec![true] } else { vec![] }, "isolate {isolate}"); + assert_eq!(text(&back).matches("/Itrue").count(), usize::from(isolate), "isolate {isolate}"); } } diff --git a/crates/pdf/src/tests/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index 590afa3df9..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<u8> { - 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<u8> { @@ -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<u8>)) -> Vec<u8> { /// `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<u8> { - 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 @@ -573,6 +608,35 @@ fn a_cmyk_image_that_keeps_its_numbers_carries_its_cmyk_profile() { assert!(!String::from_utf8_lossy(&bytes).contains("/S/Luminosity"), "no luminosity soft mask"); } +/// With Don't Include Profiles set, a CMYK JPEG kept as it is is DeviceCMYK without its own +/// `ICC_PROFILE` segments, its compressed inks unchanged; one resampled and compressed again is +/// written without a profile too. Left unset, the JPEG data stays as it is. +#[test] +fn a_set_dont_include_profiles_takes_a_cmyk_jpegs_profile_out() { + let ink = [0u8, 102, 255, 0]; + let icc = cmyk_profile(|_| {}); + let jpg = cmyk_jpeg_with(&flat(ink, 64 * 64), 64, 64, &icc); + let d = image_doc(ImageBlob::new("image/jpeg", jpg.clone()), 64, 64); + let export = |s: serde_json::Value| { + let out = export_with_report(&d, &opts(s.clone())).unwrap_or_else(|e| panic!("{s}: {e}")); + let w: Vec<Written> = written(&out.bytes).into_iter().filter(|w| w.space != "DeviceGray").collect(); + assert_eq!(w.len(), 1, "{s}: {w:?}"); + (w.into_iter().next().unwrap(), out.bytes) + }; + let segment = |data: &[u8]| data.windows(12).any(|w| w == b"ICC_PROFILE\0"); + let (w, _) = export(json!({})); + assert!(w.data == jpg && segment(&w.data), "unset: the JPEG data unchanged"); + let s = json!({"output": {"profiles": "none"}}); + let (w, bytes) = export(s.clone()); + assert_eq!((w.space.as_str(), w.filter.as_deref()), ("DeviceCMYK", Some("DCTDecode")), "{s}"); + assert!(!segment(&w.data) && w.data.len() < jpg.len(), "{s}: no ICC_PROFILE segment is left"); + assert!(w.data == vectorcraft_doc::cmyk::jpeg_without_icc(&jpg).unwrap(), "{s}: the other segments and the scan unchanged"); + assert_eq!(blobs(&import(&bytes).unwrap())[0].cmyk().unwrap().data, ImageBlob::new("image/jpeg", jpg.clone()).cmyk().unwrap().data); + let s = json!({"output": {"profiles": "none"}, "compression": {"color": {"downsample": "bicubic", "ppi": 72.0, "abovePpi": 100.0}}}); + let (w, _) = export(s.clone()); + assert!(w.icc.is_none() && !segment(&w.data), "{s}: {w:?}"); +} + /// A CMYK JPEG kept as it is whose header declares far more pixels than the app reads is left out /// with a warning, as other images that large are. #[test] @@ -593,6 +657,38 @@ fn a_kept_cmyk_jpeg_declaring_too_many_pixels_is_left_out() { } } +/// A CMYK JPEG whose inks can't be read (it declares more pixels than CMYK images are decoded +/// with, though fewer than the writer embeds) is written with its own numbers only when they are +/// kept: when the Output settings convert its colors it is left out with a warning, in every +/// standard. +#[test] +fn a_cmyk_jpeg_whose_inks_cant_be_read_is_left_out_when_its_colors_are_converted() { + let mut jpg = cmyk_jpeg(&flat([0, 102, 255, 0], 4), 2, 2); + // Height and width of the SOF0 segment (after its marker, length and precision): 8200 × 8200. + let sof = jpg.windows(2).position(|w| w == [0xFF, 0xC0]).unwrap(); + jpg[sof + 5..sof + 9].copy_from_slice(&[0x20, 0x08, 0x20, 0x08]); + let blob = ImageBlob::new("image/jpeg", jpg); + assert!(blob.is_cmyk() && blob.cmyk().is_none()); + let d = image_doc(blob, 2, 2); + let out = export_with_report(&d, &opts(json!({}))).unwrap(); + let kept = written(&out.bytes); + assert!(kept.len() == 1 && kept[0].space == "DeviceCMYK", "kept as it is: {kept:?}"); + let unconverted = "an image couldn't be converted to the Output destination and is missing from the picture"; + for s in [ + json!({"output": {"conversion": "destination", "destination": DEVICE_CMYK}}), + json!({"output": {"conversion": "destination", "destination": SRGB}}), + json!({"standard": "pdfX1a", "output": {"conversion": "destination", "destination": DEVICE_CMYK}}), + json!({"standard": "pdfX4", "output": {"conversion": "destination", "destination": DEVICE_CMYK}}), + json!({"standard": "pdfA2b", "output": {"conversion": "destination", "destination": DEVICE_CMYK}}), + ] { + let out = export_with_report(&d, &opts(s.clone())).unwrap_or_else(|e| panic!("{s}: {e}")); + assert!(written(&out.bytes).is_empty(), "{s}"); + assert!(out.warnings.iter().any(|w| w == unconverted), "{s}: {:?}", out.warnings); + let other = out.warnings.iter().any(|w| w.contains("couldn't be decoded") || w.contains("written as it is")); + assert!(!other, "{s}: {:?}", out.warnings); + } +} + /// The profile each transparency group of written PDF `bytes` blends in: its ICC-based space's /// profile, or `None` for DeviceCMYK. fn group_profiles(bytes: &[u8]) -> Vec<Option<Vec<u8>>> { @@ -847,7 +943,41 @@ fn export_smasks(d: &Document) -> (Vec<u8>, Vec<Option<Vec<u8>>>) { fn png(img: impl Into<image::DynamicImage>) -> Vec<u8> { 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 } @@ -1124,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<Paint>) -> 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<Paint>, Vec<u8>)> { 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/compression.rs b/crates/pdf/src/tests/compression.rs index f36cb88e4b..9f7c8560cf 100644 --- a/crates/pdf/src/tests/compression.rs +++ b/crates/pdf/src/tests/compression.rs @@ -266,10 +266,60 @@ fn images_declaring_more_than_the_allowance_are_not_decoded() { assert_eq!(crate::images::mask_alpha(&blob, 60_000, 60_000, false), None); assert_eq!(crate::images::mask_alpha(&blob, 2, 2, false), None, "another size is not decoded at all"); let c: CompressionSettings = serde_json::from_value(json!({"gray": {"downsample": "bicubic", "ppi": 72, "abovePpi": 100}})).unwrap(); - let r = crate::images::recode(&png, (10.0, 10.0), &c, false, None, true, None); + let r = crate::images::recode(&png, (10.0, 10.0), &c, false, None, crate::images::SourceProfiles::Keep, None); assert!(r.image.is_none(), "kept as it is"); } +/// When the Output settings convert colors, a color image beyond the decode allowance can't be +/// kept as it is: it is unconverted, and so is one whose header can't be read. A color image +/// whose pixel data can't be read (tagged with an ICC profile it is converted from or not) can't +/// be written in its own colors either, and is kept as it is, as is a grey one, whose pixels +/// aren't converted, and any image without a conversion. +#[test] +fn a_color_image_beyond_the_allowance_for_a_conversion_is_unconverted() { + use vectorcraft_color::cms::{DISPLAY_P3, GENERIC_CMYK, icc_bytes}; + let d = doc(encoded(colour(), ImageFormat::Png), "image/png"); + let settings: PdfSettings = serde_json::from_value(json!({"output": {"conversion": "destination", "destination": GENERIC_CMYK}})).unwrap(); + let out = crate::output::ColorOut::new(&d, &settings).unwrap(); + assert!(out.pixels().is_some()); + let then = out.converts_tagged_pixels().then_some(&out); + let grey = out.converts_grey_images(); + let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: false, then, grey }); + assert!(to_srgb.is_some()); + let c: CompressionSettings = serde_json::from_value(json!({})).unwrap(); + let half = |mut bytes: Vec<u8>| { + bytes.truncate(bytes.len() / 2); + bytes + }; + let cut = |img: DynamicImage| half(encoded(img, ImageFormat::Png)); + let mut p3 = icc_bytes(DISPLAY_P3).unwrap().to_vec(); + p3[8..12].copy_from_slice(&[4, 0x20, 0, 0]); + // `declared_png`'s header declaring RGB pixels (color type 2), with the IHDR chunk's CRC + // written again. + let mut rgb_declared = declared_png(60_000, 60_000); + rgb_declared[25] = 2; + let mut crc = flate2::Crc::new(); + crc.update(&rgb_declared[12..29]); + rgb_declared[29..33].copy_from_slice(&crc.sum().to_be_bytes()); + let cases = [ + ("RGB declaring more than the allowance", rgb_declared, true), + ("RGB", cut(colour()), false), + ("tagged RGB", half(tagged(&colour(), &p3, ImageFormat::Png)), false), + ("unreadable", vec![1, 2, 3], true), + ("grey", cut(colour().grayscale()), false), + ("grey declaring more than the allowance", declared_png(60_000, 60_000), false), + ]; + for (what, bytes, unconverted) in cases { + let r = crate::images::recode(&bytes, (72.0, 72.0), &c, false, out.pixels(), crate::images::SourceProfiles::Keep, to_srgb); + assert!(r.image.is_none(), "{what}"); + assert_eq!(r.unconverted, unconverted, "{what}"); + assert!( + !crate::images::recode(&bytes, (72.0, 72.0), &c, false, None, crate::images::SourceProfiles::Keep, None).unconverted, + "{what}, no conversion" + ); + } +} + /// A version 2.1 display ICC profile for colour space `space` (`RGB ` or `GRAY`), `len` bytes in /// all, with an empty tag table, every byte after the tag count different from its neighbors. fn icc_profile(space: &[u8; 4], len: usize) -> Vec<u8> { @@ -425,6 +475,80 @@ fn pdf_x1a_keeps_a_tagged_gray_jpeg_as_jpeg() { } } +/// With Don't Include Profiles set, a gray or RGB image is written without the ICC profile it +/// carries: a PNG, JPEG or TIFF embedded as it is, resampled or compressed with JPEG, with alpha and +/// at 16 bits. A JPEG kept as it is loses its `ICC_PROFILE` segments, its compressed samples +/// unchanged. Left unset, or `null`, the setting keeps the profiles. PDF/X-4 files keep them +/// whatever the setting says. +#[test] +fn a_set_dont_include_profiles_removes_image_profiles() { + let (rgb, gray) = (icc_profile(b"RGB ", 600), icc_profile(b"GRAY", 300)); + let mut clear = colour().to_rgba8(); + clear.put_pixel(0, 0, image::Rgba([10, 20, 30, 0])); + let deep = DynamicImage::ImageRgb16(colour().to_rgb16()); + let export = |d: &Document, settings: Value| { + let mut settings: PdfSettings = serde_json::from_value(settings).unwrap(); + settings.compression.compress_text = false; + export_with_report(d, &PdfOptions { settings, ..Default::default() }).unwrap() + }; + let resampled = + json!({"color": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}, "gray": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}}); + let jpeg = json!({"color": {"compression": "jpeg"}, "gray": {"compression": "jpeg"}}); + let cases = [ + ("RGB PNG", tagged(&colour(), &rgb, ImageFormat::Png), "image/png", json!({}), "DeviceRGB"), + ("gray PNG", tagged(&colour().grayscale(), &gray, ImageFormat::Png), "image/png", json!({}), "DeviceGray"), + ("RGB JPEG", tagged(&colour(), &rgb, ImageFormat::Jpeg), "image/jpeg", json!({}), "DeviceRGB"), + ("gray JPEG", tagged(&colour().grayscale(), &gray, ImageFormat::Jpeg), "image/jpeg", json!({}), "DeviceGray"), + ("RGB TIFF", tagged(&colour(), &rgb, ImageFormat::Tiff), "image/tiff", json!({}), "DeviceRGB"), + ("gray TIFF", tagged(&colour().grayscale(), &gray, ImageFormat::Tiff), "image/tiff", json!({}), "DeviceGray"), + ("RGBA TIFF", tagged(&clear.into(), &rgb, ImageFormat::Tiff), "image/tiff", json!({}), "DeviceRGB"), + ("16-bit TIFF", tagged(&deep, &rgb, ImageFormat::Tiff), "image/tiff", json!({}), "DeviceRGB"), + ("RGB PNG, resampled", tagged(&colour(), &rgb, ImageFormat::Png), "image/png", resampled.clone(), "DeviceRGB"), + ("gray JPEG, resampled", tagged(&colour().grayscale(), &gray, ImageFormat::Jpeg), "image/jpeg", resampled, "DeviceGray"), + ("RGB TIFF as JPEG", tagged(&colour(), &rgb, ImageFormat::Tiff), "image/tiff", jpeg.clone(), "DeviceRGB"), + ("gray TIFF as JPEG", tagged(&colour().grayscale(), &gray, ImageFormat::Tiff), "image/tiff", jpeg, "DeviceGray"), + ]; + for (what, bytes, mime, compression, device) in cases { + let d = doc(bytes.clone(), mime); + // Left unset, or null, the image keeps its profile. + for profiles in [json!({}), json!({"profiles": null})] { + let r = export(&d, json!({"compression": compression.clone(), "output": profiles})); + let spaces = image_spaces(&r.bytes); + assert!(spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.is_some(), "{what}, {profiles}: {spaces:?}"); + } + let none = export(&d, json!({"compression": compression.clone(), "output": {"profiles": "none"}})); + assert!(none.warnings.is_empty(), "{what}: {:?}", none.warnings); + let spaces = image_spaces(&none.bytes); + assert!(spaces.len() == 1 && spaces[0].space == device && spaces[0].icc.is_none(), "{what}: {spaces:?}"); + let data = image_data(&none.bytes); + assert!(data.iter().all(|d| !d.windows(12).any(|w| w == b"ICC_PROFILE\0")), "{what}: no ICC_PROFILE segment is left"); + if mime == "image/jpeg" && compression == json!({}) { + // The JPEG data without its profile segments: the image decoder reads the same pixels + // from it, and no profile. + assert!(data.len() == 1 && data[0].len() < bytes.len(), "{what}: the JPEG data kept"); + let decode = |b: &[u8]| image::load_from_memory_with_format(b, ImageFormat::Jpeg).unwrap(); + assert!(decode(&data[0]) == decode(&bytes), "{what}: the same pixels"); + assert!(crate::images::source_icc(&data[0]).is_none() && crate::images::source_icc(&bytes).is_some(), "{what}"); + } + // PDF/X-4 tags every colour: the image keeps its profile. + let x4 = export(&d, json!({"standard": "pdfX4", "compatibility": "1.6", "compression": compression, "output": {"profiles": "none"}})); + let spaces = image_spaces(&x4.bytes); + assert!(spaces.len() == 1 && spaces[0].space == "ICCBased", "{what}, PDF/X-4: {spaces:?}"); + } + // A JPEG whose `ICC_PROFILE` segments don't make up a profile (the first of two, the second + // missing) loses them too. + let plain = encoded(colour(), ImageFormat::Jpeg); + let mut part = vec![0xFF, 0xD8, 0xFF, 0xE2, 0, 30]; + part.extend_from_slice(b"ICC_PROFILE\0"); + part.extend_from_slice(&[1, 2]); + part.extend_from_slice(&rgb[..14]); + part.extend_from_slice(&plain[2..]); + assert!(crate::images::source_icc(&part).is_none(), "the decoder reads no profile"); + let none = export(&doc(part, "image/jpeg"), json!({"output": {"profiles": "none"}})); + let data = image_data(&none.bytes); + assert!(data == [plain], "an unreadable profile: the JPEG data without its segments"); +} + /// A gray or RGB TIFF that carries an ICC profile of its colour space is written in an ICC-based /// colour space holding the same profile, at 16 bits a sample from PDF 1.5 on, with its alpha as /// a soft mask; and so is a tagged TIFF or PNG that is resampled or compressed with JPEG. Pixels @@ -776,11 +900,12 @@ fn convert_to_srgb_converts_tagged_images_from_their_profile() { png }; let c: CompressionSettings = serde_json::from_value(json!({})).unwrap(); - let srgb_out = Some(crate::images::ToSrgb { intent: Intent::RelativeColorimetric, sixteen_bit: true }); + let srgb_out = Some(crate::images::ToSrgb { intent: Intent::RelativeColorimetric, sixteen_bit: true, then: None, grey: true }); for (what, png) in [("RGB", declared(&colour(), &p3)), ("gray", declared(&colour().grayscale(), &gray))] { - let r = crate::images::recode(&png, (100.0, 100.0), &c, false, None, true, srgb_out); + let keep = crate::images::SourceProfiles::Keep; + let r = crate::images::recode(&png, (100.0, 100.0), &c, false, None, keep, srgb_out); assert!(r.image.is_none() && r.warning.is_some_and(|w| w.contains("not converted to sRGB")), "{what}: {:?}", r.warning); - let r = crate::images::recode(&png, (100.0, 100.0), &c, false, None, true, None); + let r = crate::images::recode(&png, (100.0, 100.0), &c, false, None, keep, None); assert!(r.image.is_none() && r.warning.is_none(), "{what}, no conversion: {:?}", r.warning); // Too large to embed as it is too: the export leaves it out, and says only that. let mut settings: PdfSettings = serde_json::from_value(to_srgb(json!({}))).unwrap(); @@ -980,3 +1105,127 @@ fn convert_to_destination_converts_tagged_images_from_their_profile() { let as_srgb = converted_samples(&img, to_cmyk); assert!(image_samples(&r.bytes).first().is_some_and(|s| samples_close(s, &as_srgb, false, 1)), "unread profile: converted as sRGB"); } + +/// With Preserve Numbers, an RGB image that carries an ICC profile is converted from that profile +/// whatever the destination, while an untagged one keeps its numbers in an RGB destination (and +/// converts from sRGB to a CMYK one, as before): to Generic CMYK, sRGB, Wide Gamut RGB, and Wide +/// Gamut RGB that is also the document's RGB profile, and in PDF/X-1a, which converts the same way. +/// A gray image keeps its profile, except in an sRGB destination, where it is converted to sRGB +/// grays. An RGB profile the CMS can't read leaves the image as it is in an RGB destination, and +/// its numbers converted as sRGB ones to a CMYK destination, with a warning. +#[test] +fn preserve_numbers_converts_tagged_images_from_their_profile() { + use vectorcraft_color::cms::{self, ColorSettings, DISPLAY_P3, GENERIC_CMYK, Intent, SRGB, WIDE_GAMUT_RGB, icc_bytes}; + let intent = Intent::RelativeColorimetric; + let settings_with = + |rgb: &str| std::sync::Arc::new(cms::Cms::new(&ColorSettings { intent, rgb: rgb.into(), ..ColorSettings::default() }).unwrap()); + let (active, own) = (settings_with(SRGB), settings_with(WIDE_GAMUT_RGB)); + let mut p3 = icc_bytes(DISPLAY_P3).unwrap().to_vec(); + p3[8..12].copy_from_slice(&[4, 0x20, 0, 0]); + let p3_profile = cms::IccProfile::from_bytes(None, &p3).unwrap(); + let from_p3 = |rgb: [u8; 3]| p3_profile.to_srgb(&rgb.map(|v| f32::from(v) / 255.0), intent).unwrap().map(|v| (v * 255.0).round() as u8); + let img = colour_blocks(); + let tagged_png = doc(tagged(&img, &p3, ImageFormat::Png), "image/png"); + let untagged_png = doc(encoded(img.clone(), ImageFormat::Png), "image/png"); + let device = |space: &str| vec![Written { space: space.into(), icc: None, bits: 8, filter: "FlateDecode".into(), smask: false }]; + let cmyk = cms::Cms::new(&ColorSettings { intent, cmyk: GENERIC_CMYK.into(), ..ColorSettings::default() }).unwrap(); + let cmy = cms::ProofLut::build(|rgb| { + let v = cmyk.srgb_to_cmyk(rgb, intent); + [v[0], v[1], v[2]] + }); + let black = cms::ProofLut::build(|rgb| [cmyk.srgb_to_cmyk(rgb, intent)[3], 0.0, 0.0]); + let wide_lut = cms::ProofLut::build(|rgb| own.srgb_to_rgb(rgb)); + let to_cmyk = |rgb: [u8; 3]| [cmy.apply8(rgb).as_slice(), &black.apply8(rgb)[..1]].concat(); + let to_wide = |rgb: [u8; 3]| wide_lut.apply8(rgb).to_vec(); + let to_srgb = |rgb: [u8; 3]| rgb.to_vec(); + type ToDest<'a> = &'a dyn Fn([u8; 3]) -> Vec<u8>; + // Each case: what, the color settings, the export settings, the space images are written in, + // how an sRGB pixel converts to the destination, and whether untagged images keep their numbers. + type Case<'a> = (&'a str, &'a std::sync::Arc<cms::Cms>, Value, &'a str, ToDest<'a>, bool); + let cases: [Case<'_>; 5] = [ + ("CMYK", &active, json!({"output": {"conversion": "preserveNumbers", "destination": GENERIC_CMYK}}), "DeviceCMYK", &to_cmyk, false), + ("sRGB", &active, json!({"output": {"conversion": "preserveNumbers", "destination": SRGB}}), "DeviceRGB", &to_srgb, true), + ("Wide Gamut", &active, json!({"output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB}}), "DeviceRGB", &to_wide, true), + ("own RGB", &own, json!({"output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB}}), "DeviceRGB", &to_wide, true), + ( + "PDF/X-1a", + &active, + json!({"standard": "pdfX1a", "compatibility": "1.3", "output": {"destination": GENERIC_CMYK}}), + "DeviceCMYK", + &to_cmyk, + false, + ), + ]; + for (what, color, settings, space, to_dest, keeps) in cases { + let export = |d: &Document| { + let mut s: PdfSettings = serde_json::from_value(settings.clone()).unwrap(); + s.compression.compress_text = false; + let r = cms::with_active((*color).clone(), || export_with_report(d, &PdfOptions { settings: s, ..Default::default() })).unwrap(); + assert!(r.warnings.is_empty(), "{what}: {:?}", r.warnings); + if what == "PDF/X-1a" { + crate::pdfx::verify(&r.bytes, Standard::PdfX1a).unwrap_or_else(|e| panic!("{what}: {e}")); + } + (image_spaces(&r.bytes), image_samples(&r.bytes)) + }; + let (spaces, samples) = export(&tagged_png); + assert_eq!(spaces, device(space), "{what}: tagged"); + let want = converted_samples(&img, |rgb| to_dest(from_p3(rgb))); + let as_numbers = converted_samples(&img, to_dest); + assert!( + samples.len() == 1 && samples_close(&samples[0], &want, false, 1), + "{what}: converted from the profile, {}", + max_diff(&samples[0], &want) + ); + assert!(!samples_close(&samples[0], &as_numbers, false, 8), "{what}: not converted as its numbers"); + let (spaces, samples) = export(&untagged_png); + assert_eq!(spaces, device(space), "{what}: untagged"); + let untagged = if keeps { img.to_rgb8().into_raw() } else { as_numbers }; + assert!(samples.len() == 1 && samples_close(&samples[0], &untagged, false, 1), "{what}: untagged, {}", max_diff(&samples[0], &untagged)); + } + // With RGB colours ICC-tagged as sRGB, the tagged image is written as its sRGB samples, in an + // ICC-based colour space with the sRGB profile. + let settings = json!({"output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB, "profiles": "all"}}); + let (spaces, pdf) = cms::with_active(active.clone(), || export_images(&tagged_png, settings)); + let is_srgb = |icc: &[u8]| { + let p = cms::IccProfile::from_bytes(None, icc).unwrap(); + [[0.2, 0.5, 0.9], [0.9, 0.1, 0.4]].iter().all(|v| p.to_srgb(v, intent).unwrap().iter().zip(v).all(|(a, b)| (a - b).abs() < 0.01)) + }; + assert!(spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.as_deref().is_some_and(is_srgb), "tagged as sRGB: {spaces:?}"); + let samples = image_samples(&pdf); + let want = converted_samples(&img, |rgb| from_p3(rgb).to_vec()); + assert!(samples.len() == 1 && samples_close(&samples[0], &want, false, 1), "tagged as sRGB, {}", max_diff(&samples[0], &want)); + // A gray image keeps its gray profile, in a CMYK and in an RGB destination, and in an RGB one + // with RGB colours ICC-tagged as sRGB (`all` profiles, PDF/A-2b). + let gray = gray_profile(&[0x01CD]); + let gray_doc = doc(tagged(&colour().grayscale(), &gray, ImageFormat::Tiff), "image/tiff"); + for (what, settings) in [ + (GENERIC_CMYK, json!({"output": {"conversion": "preserveNumbers", "destination": GENERIC_CMYK}})), + (WIDE_GAMUT_RGB, json!({"output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB}})), + ("all profiles", json!({"output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB, "profiles": "all"}})), + ("PDF/A-2b", json!({"standard": "pdfA2b", "output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB}})), + ] { + let (spaces, _) = cms::with_active(active.clone(), || export_images(&gray_doc, settings)); + assert!(spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.as_deref() == Some(gray.as_slice()), "gray, {what}: {spaces:?}"); + } + // In an sRGB destination it is converted to sRGB grays and written without it. + let settings = json!({"output": {"conversion": "preserveNumbers", "destination": SRGB}}); + let (spaces, _) = cms::with_active(active.clone(), || export_images(&gray_doc, settings)); + assert!(spaces.len() == 1 && spaces[0].space == "DeviceGray" && spaces[0].icc.is_none(), "gray, sRGB: {spaces:?}"); + // A profile the CMS can't read: the image keeps it and its numbers in an RGB destination, and + // its numbers are converted as sRGB ones to a CMYK destination, with a warning each. + let unread = icc_profile(b"RGB ", 600); + let unread_doc = doc(tagged(&img, &unread, ImageFormat::Png), "image/png"); + let unread_export = |destination: &str| { + let mut s: PdfSettings = serde_json::from_value(json!({"output": {"conversion": "preserveNumbers", "destination": destination}})).unwrap(); + s.compression.compress_text = false; + cms::with_active(active.clone(), || export_with_report(&unread_doc, &PdfOptions { settings: s, ..Default::default() })).unwrap() + }; + let r = unread_export(WIDE_GAMUT_RGB); + assert!(r.warnings.iter().any(|w| w.contains("the image keeps it")), "{:?}", r.warnings); + let spaces = image_spaces(&r.bytes); + assert!(spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.as_deref() == Some(unread.as_slice()), "unread profile: {spaces:?}"); + let r = unread_export(GENERIC_CMYK); + assert!(r.warnings.iter().any(|w| w.contains("converted to the destination as sRGB")), "{:?}", r.warnings); + let as_srgb = converted_samples(&img, to_cmyk); + assert!(image_samples(&r.bytes).first().is_some_and(|s| samples_close(s, &as_srgb, false, 1)), "unread profile, CMYK: converted as sRGB"); +} diff --git a/crates/pdf/src/tests/file_info.rs b/crates/pdf/src/tests/file_info.rs index 4c837ba67f..57bbdcd58c 100644 --- a/crates/pdf/src/tests/file_info.rs +++ b/crates/pdf/src/tests/file_info.rs @@ -94,8 +94,10 @@ fn the_xmp_packet_gives_file_info() { FileInfo { title: Some("Poster".into()), author: Some("Ada Lovelace, Charles Babbage".into()), + author_title: None, description: Some("A poster\nfor the fair".into()), keywords: Some(vec!["fair".into(), "print".into()]), + rating: None, copyright_notice: Some("(c) 2026 Ada".into()), copyright_url: Some("https://example.com/rights".into()), copyrighted: Some(false), @@ -270,3 +272,48 @@ fn a_written_pdf_gives_its_copyright_back() { let f = file_info(&export(&d, &PdfOptions::uncompressed()).unwrap(), None).unwrap(); assert_eq!((f.author.as_deref(), f.copyright_notice.as_deref()), (Some("Ada"), Some("(c) Ada"))); } + +#[test] +fn a_metadata_template_gives_its_file_info_back() { + let f = FileInfo { + title: Some("Fair poster".into()), + author: Some("Ada & <Lovelace>".into()), + author_title: Some("Designer, \"lead\"".into()), + description: Some("A poster\r\nfor the fair".into()), + keywords: Some(vec!["fair".into(), "print, large".into()]), + rating: Some(4), + copyright_notice: Some("(c) 2026 Ada".into()), + copyright_url: Some("https://example.com/rights?a=1&b=2".into()), + copyrighted: Some(true), + ..Default::default() + }; + let xmp = metadata_template(&f); + assert!(xmp.starts_with("<?xpacket begin=") && xmp.trim_end().ends_with("<?xpacket end=\"w\"?>"), "{xmp}"); + assert_eq!(read_template(xmp.as_bytes()), Some(f)); + // A public-domain status writes Marked False; fields without a value and the dates are left out. + let f = FileInfo { copyrighted: Some(false), author: Some(" ".into()), created: Some(CREATED), ..Default::default() }; + let xmp = metadata_template(&f); + assert!(!xmp.contains("dc:creator") && !xmp.contains("CreateDate") && xmp.contains("<xmpRights:Marked>False</xmpRights:Marked>"), "{xmp}"); + assert_eq!(read_template(xmp.as_bytes()), Some(FileInfo { copyrighted: Some(false), ..Default::default() })); + // The template is the PDF packet's format: a PDF whose metadata stream holds one reads the same. + let f = FileInfo { author: Some("Ada".into()), author_title: Some("Editor".into()), rating: Some(2), ..Default::default() }; + let read = file_info(&pdf(None, Some(&metadata_template(&f))), None).unwrap(); + assert_eq!((read.author, read.author_title, read.rating), (f.author, f.author_title, f.rating)); +} + +#[test] +fn a_metadata_template_reads_ratings_and_refuses_what_is_not_xmp() { + let rated = |r: &str| read_template(packet(&description(&format!("xmp:Rating=\"{r}\""), "")).as_bytes()).unwrap().rating; + assert_eq!([rated("0"), rated("5"), rated("3.0"), rated(" 2 ")], [Some(0), Some(5), Some(3), Some(2)]); + // A rejected file's -1, fractions, ratings past 5 and words are left out. + assert_eq!([rated("-1"), rated("2.5"), rated("6"), rated("high")], [None; 4]); + // XML without `rdf:RDF`, text and a packet that isn't well-formed are not templates. + assert_eq!(read_template(b"<root><title>Poster"), None); + assert_eq!(read_template(b"Ada Lovelace"), None); + assert_eq!(read_template(packet("").as_bytes()), None); + // An XMP packet with no File Info is a template with no fields. + assert_eq!(read_template(packet("").as_bytes()), Some(FileInfo::default())); + // Longer than the longest template read, it is refused without being parsed. + let long = packet(&description("", &" ".repeat(MAX_TEMPLATE_BYTES))); + assert_eq!(read_template(long.as_bytes()), None); +} 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/import_options.rs b/crates/pdf/src/tests/import_options.rs index 2ed84d5dc0..a419d64137 100644 --- a/crates/pdf/src/tests/import_options.rs +++ b/crates/pdf/src/tests/import_options.rs @@ -91,6 +91,27 @@ fn trim_box_artboards_take_the_bleed_box_round_them_as_the_document_bleed() { assert_eq!((d.artboards[0].rect.width(), d.setup.bleed), (300.0, [0.0; 4])); } +#[test] +fn trim_box_artboards_keep_the_bleed_between_them() { + // The second page's bleed box is its trim box: the document's bleed (10 mm, over half the + // 36 pt gap) still goes round its artboard. + let edge = Some([50.0, 50.0, 250.0, 150.0]); + let plain = PdfPage { bleed: edge, trim: edge, ..PdfPage::new(300.0, 200.0, "0 g 50 50 200 100 re f") }; + let bytes = pdf(&[bled_page(), plain, bled_page()], None); + let d = open(&bytes, ImportOptions { crop: CropTo::Trim, ..Default::default() }); + let starts: Vec = d.artboards.iter().map(|a| a.rect.x0).collect(); + let step = 200.0 + 36.0 + 2.0 * BLEED; + assert!(near([starts[0], starts[1], starts[2], 0.0], [0.0, step, 2.0 * step, 0.0]), "{starts:?}"); + // Each artboard's bleed ends 36 pt before the next one's begins. + for pair in d.artboards.windows(2) { + let (a, b) = (d.setup.bleed_rect(pair[0].rect), d.setup.bleed_rect(pair[1].rect)); + assert!((b.x0 - a.x1 - 36.0).abs() < 1e-3, "{a:?} {b:?}"); + } + // On the crop boxes there is no bleed, and the artboards are 36 pt apart. + let d = open(&bytes, ImportOptions::default()); + assert_eq!(d.artboards.iter().map(|a| a.rect.x0).collect::>(), [0.0, 336.0, 672.0]); +} + #[test] fn missing_boxes_fall_back_to_the_crop_box_and_boxes_are_clipped_to_the_media_box() { let page = PdfPage { crop: Some([10.0, 10.0, 290.0, 390.0]), art: Some([-50.0, 0.0, 100.0, 100.0]), ..PdfPage::new(300.0, 400.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/settings.rs b/crates/pdf/src/tests/settings.rs index e159b7b162..d4dd5a63ce 100644 --- a/crates/pdf/src/tests/settings.rs +++ b/crates/pdf/src/tests/settings.rs @@ -41,6 +41,24 @@ fn json_is_camel_case_and_partial_objects_keep_defaults() { } } +/// The Profiles setting is unset when left out, `null` or `"default"` (written as `null`), and set +/// by a choice's id; another value is refused. +#[test] +fn the_profiles_setting_can_be_left_unset() { + assert_eq!(serde_json::to_value(PdfSettings::default()).unwrap()["output"]["profiles"], serde_json::Value::Null); + for unset in [json!({}), json!({"profiles": null}), json!({"profiles": "default"})] { + assert_eq!(settings(json!({"output": unset.clone()})).output.profiles, None, "{unset}"); + } + for (id, want) in [("none", ProfileInclusion::None), ("all", ProfileInclusion::All), ("taggedSource", ProfileInclusion::TaggedSource)] { + let s = settings(json!({"output": {"profiles": id}})); + assert_eq!(s.output.profiles, Some(want), "{id}"); + assert_eq!(serde_json::from_value::(serde_json::to_value(&s).unwrap()).unwrap(), s, "{id} round-trips"); + } + for bad in [json!("Default"), json!("never"), json!(1)] { + assert!(serde_json::from_value::(json!({"output": {"profiles": bad.clone()}})).is_err(), "{bad}"); + } +} + #[test] fn passwords_are_never_serialized() { let s = settings(json!({"security": {"openPassword": "secret", "permissionsPassword": "owner"}})); 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 4bd499b9d4..61569cc79e 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -19,13 +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 } -flate2 = { workspace = true } +craft-gif = { workspace = true } +craft-image-codecs = { 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" -# PNG rows read one at a time (MIT OR Apache-2.0; already used by the image crate's PNG reader). -png = "0.18" +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" @@ -39,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"] } @@ -46,9 +46,8 @@ 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"] } -tiff = "0.11" -# Reads the PSD exports back (MIT OR Apache-2.0). -psd = "0.3" +image = { workspace = true } +craft-tiff = { workspace = true } +craft-psd = { workspace = true } proptest = { workspace = true } serde_json = { 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 635f906839..891c325c75 100644 --- a/crates/render/src/encode.rs +++ b/crates/render/src/encode.rs @@ -10,6 +10,7 @@ pub mod gif; pub mod jpeg; pub mod png; pub mod psd; +mod psd_type; pub mod quantize; pub mod tga; pub mod tiff; @@ -185,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/psd.rs b/crates/render/src/encode/psd.rs index 98c031c89a..c1fa1a2a5f 100644 --- a/crates/render/src/encode/psd.rs +++ b/crates/render/src/encode/psd.rs @@ -1,19 +1,22 @@ //! PSD export: a layered bitmap at 8 bits per channel, written from the format's public -//! specification. The file holds the header, the resolution and colour profile resources, the -//! layer records and their channels (PackBits row by row; groups as section dividers), then the +//! specification. The file holds the header, the resolution, colour profile and slices resources, +//! the layer records and their channels (PackBits row by row; groups as section dividers), then the //! merged image, which readers that skip layers show. RGB, CMYK (stored as 255 − ink, as the //! format keeps inks) or grayscale. +use std::collections::HashMap; use std::sync::Arc; use vectorcraft_color::{BlendMode, cms}; -use vectorcraft_doc::{Document, Knockout, LayerColor, Node, NodeKind}; -use vectorcraft_geom::Rect; +use vectorcraft_doc::text::TypeAntiAlias; +use vectorcraft_doc::{Document, Knockout, LayerColor, Node, NodeId, NodeKind, SliceKind, SliceOptions, SliceSource}; +use vectorcraft_geom::{Point, Rect}; use super::jpeg::{self, ColorModel}; +use super::psd_type; use super::tiff::packbits; use super::{RasterExportOptions, RasterFormat, on_white}; -use crate::{RenderOptions, Rendered, Renderer, fx}; +use crate::{AntiAlias, RenderOptions, Rendered, Renderer, fx}; /// Most pixels a side of a PSD can have (larger images need the format's large-document variant). pub const MAX_SIDE: u32 = 30_000; @@ -33,6 +36,11 @@ pub struct PsdOptions { /// its objects together (a clipping mask, an opacity mask, its own appearance, knockout) stays /// one pixel layer. pub max_editability: bool, + /// With `layers`: horizontal and vertical point type in layers and sublayers is written as type + /// layers that a reader can edit, each with its pixels: type in solid colours without strokes, + /// effects or an appearance of its own. A layer that holds such type becomes a group of its type + /// layers and pixel layers of the art between them. + pub preserve_text: bool, /// With `layers`: hidden layers (and hidden objects) are written as hidden layers instead of /// being left out. pub hidden_layers: bool, @@ -42,7 +50,7 @@ pub struct PsdOptions { impl Default for PsdOptions { fn default() -> Self { - Self { color_model: ColorModel::Rgb, layers: true, max_editability: false, hidden_layers: false, embed_icc: true } + Self { color_model: ColorModel::Rgb, layers: true, max_editability: false, preserve_text: false, hidden_layers: false, embed_icc: true } } } @@ -141,6 +149,8 @@ struct Record { hidden: bool, /// Section divider: [`OPEN_GROUP`] or [`END_GROUP`]. divider: Option, + /// A type layer's type tool object (`TySh`). + type_tool: Option>, } /// Section divider kinds. @@ -159,6 +169,7 @@ impl Record { opacity: 255, hidden: false, divider: None, + type_tool: None, } } @@ -238,6 +249,9 @@ impl Record { if let Some(kind) = self.divider { block(&mut extra, b"lsct", &[&kind.to_be_bytes()[..], b"8BIM", &self.blend].concat())?; } + if let Some(data) = &self.type_tool { + block(&mut extra, b"TySh", data)?; + } out.extend(len32(extra.len())?.to_be_bytes()); out.extend(extra); Ok(()) @@ -289,6 +303,8 @@ struct File { records: Vec, ppi: f64, icc: Option>, + /// Image resource 1050's data, when the file has slices. + slices: Option>, } /// Refuse a size the format can't store. @@ -319,7 +335,8 @@ impl File { out.extend(mode(self.model).to_be_bytes()); // No colour mode data. out.extend(0u32.to_be_bytes()); - // Image resources: the resolution (16.16 fixed point, pixels per inch shown in inches), the profile. + // Image resources: the resolution (16.16 fixed point, pixels per inch shown in inches), the + // profile, the slices. let ppi = if self.ppi.is_finite() && self.ppi > 0.0 { self.ppi } else { 72.0 }; let fixed = (ppi.min(30_000.0) * 65536.0).round() as u32; let res = [fixed.to_be_bytes(), [0, 1, 0, 1], fixed.to_be_bytes(), [0, 1, 0, 1]].concat(); @@ -328,6 +345,9 @@ impl File { if let Some(icc) = &self.icc { resource(&mut resources, 1039, icc)?; } + if let Some(slices) = &self.slices { + resource(&mut resources, SLICES, slices)?; + } out.extend(len32(resources.len())?.to_be_bytes()); out.extend(resources); self.write_layers(&mut out)?; @@ -377,17 +397,20 @@ fn icc(o: &PsdOptions) -> Result>, String> { pub fn encode(img: &Rendered, ppi: f64, o: &PsdOptions) -> Result, String> { let inks = (o.color_model == ColorModel::Cmyk).then(|| jpeg::separated(img)); let merged = planes(o.color_model, &img.to_straight(), inks.as_deref(), true, false); - File { width: img.width, height: img.height, model: o.color_model, merged, alpha: false, records: vec![], ppi, icc: icc(o)? }.write() + File { width: img.width, height: img.height, model: o.color_model, merged, alpha: false, records: vec![], ppi, icc: icc(o)?, slices: None } + .write() } /// `region` of `doc` as a PSD with `opts` (see [`PsdOptions`]). The merged image is the export's /// render; with Write Layers each part is also drawn alone as its own layer, cropped to what it -/// paints, its opacity and blend mode in the layer's record. +/// paints, its opacity and blend mode in the layer's record. The user and object slices that reach +/// into `region` are written with or without layers ([`slices`]). pub(crate) fn export(r: &mut Renderer, doc: &Document, region: Rect, opts: &RasterExportOptions) -> Result, String> { let o = &opts.psd; let scale = opts.scale(); let (width, height) = crate::region_pixels(region, scale); check_size(width, height)?; + let slices = slices(doc, region, scale, (width, height))?; let ro = opts.render_options(RasterFormat::Psd); let (mut merged, mut alpha) = { let px = r.render_region_with(doc, region, scale, &ro).to_straight(); @@ -413,7 +436,156 @@ pub(crate) fn export(r: &mut Renderer, doc: &Document, region: Rect, opts: &Rast merged.pop(); alpha = false; } - File { width, height, model: o.color_model, merged, alpha, records, ppi: opts.ppi, icc: icc(o)? }.write() + File { width, height, model: o.color_model, merged, alpha, records, ppi: opts.ppi, icc: icc(o)?, slices }.write() +} + +/// The image resource that holds the slices. +const SLICES: u16 = 1050; + +/// The most slices one file holds (as many as `document.open` reads). +pub(crate) const MAX_SLICES: usize = 10_000; + +/// The longest text of a slice, in UTF-16 units (as long as `document.open` reads). +pub(crate) const MAX_SLICE_TEXT: usize = 65_536; + +/// Resource 1050's data for the user and object slices of `doc` that reach into `region`, in the +/// "Slices resource format" of the Photoshop File Formats Specification +/// (), version 6: the bounds of all +/// the slices, the group's name, the count, then one record per slice. `None` when no slice +/// reaches into `region`. Each rectangle is the slice as laid out ([`Document::slice_layout`]), +/// clipped to `region` and given in the `size` canvas's pixels at `scale`, at least one pixel +/// each way. Every slice is written as one the user made (origin 2): an object slice keeps its +/// rectangle and options. Auto slices aren't written; a reader lays them out again. An HTML Text +/// slice is written as No Image with its type's text as HTML. Text alignment is written as the +/// default. An error when a slice's bounds aren't finite, or there are more than [`MAX_SLICES`] +/// slices, a text longer than [`MAX_SLICE_TEXT`], or more than 4 GB of slices ([`room`]). +fn slices(doc: &Document, region: Rect, scale: f64, (w, h): (u32, u32)) -> Result>, String> { + let users: HashMap = doc.slices.iter().map(|s| (s.id, &s.options)).collect(); + let mut found = vec![]; + for area in doc.slice_layout().iter().filter(|a| a.source != SliceSource::Auto) { + let Some(id) = area.id else { continue }; + let r = area.rect; + if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) { + let number = area.number; + return Err(format!("slice {number} has no finite bounds and can't be written to PSD")); + } + let Some(options) = users.get(&id).copied().or_else(|| doc.slice_options(id)) else { continue }; + // The part inside `region`, found before the region is rounded to whole pixels. + let (x0, y0, x1, y1) = (r.x0.max(region.x0), r.y0.max(region.y0), r.x1.min(region.x1), r.y1.min(region.y1)); + if !(x0 < x1 && y0 < y1) { + continue; + } + let edge = |v: f64, origin: f64, max: u32| ((v - origin) * scale).clamp(0.0, f64::from(max)); + let (l, t, r, b) = (edge(x0, region.x0, w), edge(y0, region.y0, h), edge(x1, region.x0, w), edge(y1, region.y0, h)); + // Whole pixels, at least one each way. + let span = |a: f64, b: f64, max: u32| { + let max = i64::from(max); + let (mut a, mut b) = ((a.round() as i64).clamp(0, max), (b.round() as i64).clamp(0, max)); + if b <= a { + a = a.min(max - 1); + b = a + 1; + } + (a as i32, b as i32) + }; + let ((l, r), (t, b)) = (span(l, r, w), span(t, b, h)); + let text = match options.kind { + SliceKind::HtmlText => doc.node(id).map(html_text).unwrap_or_default(), + _ => options.text.clone(), + }; + found.push(([l, t, r, b], options, text)); + } + if found.is_empty() { + return Ok(None); + } + if found.len() > MAX_SLICES { + let count = found.len(); + return Err(format!("the document has {count} slices, more than the {MAX_SLICES} a PSD file holds")); + } + let (mut top, mut left, mut bottom, mut right) = (i32::MAX, i32::MAX, 0, 0); + for ([l, t, r, b], _, _) in &found { + (left, top, right, bottom) = (left.min(*l), top.min(*t), right.max(*r), bottom.max(*b)); + } + let mut out = 6u32.to_be_bytes().to_vec(); + for v in [top, left, bottom, right] { + out.extend(v.to_be_bytes()); + } + let stem = doc.title.rsplit_once('.').map_or(doc.title.as_str(), |(s, _)| s); + unicode(&mut out, stem)?; + out.extend((found.len() as u32).to_be_bytes()); + // IDs from 1. + for ((rect, o, text), id) in found.into_iter().zip(1u32..) { + out.extend(id.to_be_bytes()); + // Group 0; made by the user. + out.extend(0u32.to_be_bytes()); + out.extend(2u32.to_be_bytes()); + unicode(&mut out, &o.name)?; + out.extend(u32::from(o.kind == SliceKind::Image).to_be_bytes()); + for v in rect { + out.extend(v.to_be_bytes()); + } + for s in [&o.url, &o.target, &o.message, &o.alt] { + unicode(&mut out, s)?; + } + // The cell text is HTML, as a No Image slice shows it. + out.push(1); + unicode(&mut out, &text)?; + // The default horizontal and vertical alignment. + out.extend([0; 8]); + out.extend(background(o)); + } + Ok(Some(out)) +} + +/// A slice's background as alpha, red, green and blue: none (all 0), the matte (alpha 0 over a +/// colour) or an opaque `#rrggbb`. +fn background(o: &SliceOptions) -> [u8; 4] { + let bg = o.background.trim(); + if bg.eq_ignore_ascii_case("matte") { + return [0, 255, 255, 255]; + } + let hex = bg.strip_prefix('#').filter(|h| h.len() == 6 && h.bytes().all(|b| b.is_ascii_hexdigit())); + match hex.and_then(|h| u32::from_str_radix(h, 16).ok()) { + Some(c) => { + let [_, r, g, b] = c.to_be_bytes(); + [255, r, g, b] + } + None => [0; 4], + } +} + +/// The text of type object `n` as the HTML an HTML Text slice shows: `&`, `<` and `>` escaped, a +/// line break as `
` (CR LF is one break). Empty for anything but type. +fn html_text(n: &Node) -> String { + let NodeKind::Text(t) = &n.kind else { return String::new() }; + t.plain_text() + .replace("\r\n", "\n") + .split(['\n', '\r', '\u{2029}']) + .map(|l| l.replace('&', "&").replace('<', "<").replace('>', ">")) + .collect::>() + .join("
") +} + +/// `s` as a Unicode string: a count of UTF-16 units, then the units. An error past +/// [`MAX_SLICE_TEXT`] units, or when the string would take `out` past [`room`]. +fn unicode(out: &mut Vec, s: &str) -> Result<(), String> { + let units = s.encode_utf16().count(); + if units > MAX_SLICE_TEXT { + return Err(format!("a slice's text has more than the {MAX_SLICE_TEXT} characters a PSD file holds")); + } + room(out.len(), units)?; + out.extend((units as u32).to_be_bytes()); + out.extend(s.encode_utf16().flat_map(|u| u.to_be_bytes())); + Ok(()) +} + +/// An error when `units` UTF-16 units and their count, added to a slices resource of `len` bytes, +/// make it longer than the 4 GB a PSD resource holds. +pub(crate) fn room(len: usize, units: usize) -> Result<(), String> { + let end = units.checked_mul(2).and_then(|n| n.checked_add(4)).and_then(|n| n.checked_add(len)); + match end.map(u32::try_from) { + Some(Ok(_)) => Ok(()), + _ => Err("the slices are too large for PSD (at most 4 GB)".into()), + } } /// Draws the parts of a document as layer records, bottom first. @@ -451,13 +623,40 @@ impl Parts<'_> { return; } let (hidden, opacity) = (!n.visible, opacity_byte(n.opacity)); - if self.o.max_editability + if self.o.preserve_text + && let Some(t) = psd_type::editable(n) + { + let record = self.draw(n); + let [top, left, bottom, right] = record.rect.map(f64::from); + let origin = Point::new(self.region.x0, self.region.y0); + let aa = if self.ro.anti_alias == AntiAlias::None { TypeAntiAlias::None } else { t.anti_alias }; + let type_tool = Some(psd_type::type_block(t, origin, self.scale, Rect::new(left, top, right, bottom), aa)); + self.records.push(Record { blend: blend_key(n.blend), opacity, hidden, type_tool, ..record }); + return; + } + let per_object = self.o.max_editability; + let hidden_layers = self.o.hidden_layers; + if (per_object || self.o.preserve_text && holds_type(n, hidden_layers)) && splits(n) && let Some(children) = n.children() { self.records.push(Record { divider: Some(END_GROUP), ..Record::empty(GROUP_END.into(), self.colors()) }); - for c in children { - self.add(c); + if per_object { + for c in children { + self.add(c); + } + } else { + // The art between type layers stays together, one pixel layer per stretch. + let mut stretch: Vec> = vec![]; + for c in children { + if type_layer(c, hidden_layers) { + self.add_stretch(n, std::mem::take(&mut stretch)); + self.add(c); + } else { + stretch.push(c.clone()); + } + } + self.add_stretch(n, stretch); } // A group in normal blending lets its layers blend with what is below it. let blend = if n.blend == BlendMode::Normal && !n.isolate { *b"pass" } else { blend_key(n.blend) }; @@ -468,6 +667,22 @@ impl Parts<'_> { self.records.push(Record { blend: blend_key(n.blend), opacity, hidden, ..record }); } + /// `nodes`, children of layer `layer` next to each other, drawn together as one pixel layer + /// named after the layer (nothing when they paint nothing). + fn add_stretch(&mut self, layer: &Node, nodes: Vec>) { + if nodes.is_empty() { + return; + } + let mut part = layer.clone(); + if let Some(children) = part.children_mut() { + *children = nodes; + } + let record = self.draw(&part); + if record.rect != [0; 4] { + self.records.push(record); + } + } + /// `n` drawn alone, visible, at full opacity in normal blending (its record carries those). fn draw(&mut self, n: &Node) -> Record { let name = n.display_name(); @@ -532,6 +747,30 @@ fn splits(n: &Node) -> bool { matches!(n.kind, NodeKind::Layer { clip: false, .. }) && n.extras().mask.is_none() && n.knockout != Knockout::On && !fx::has_object_fx(n) } +/// Does layer `n`, or a sublayer that can be written as a group, hold point type that can be a type +/// layer? Not when other art in it blends in a mode other than normal (the object, or a fill or +/// stroke of it, as [`Node::blends_through`] sees it): drawn as a pixel layer of its own, it would no +/// longer blend with the type or the art below. Hidden type counts only when `hidden` (Include +/// Hidden Layers) writes it. +fn holds_type(n: &Node, hidden: bool) -> bool { + let Some(children) = n.children().filter(|_| splits(n)) else { return false }; + let mut held = false; + for c in children { + if type_layer(c, hidden) { + held = true; + } else if Node::children_blend(std::slice::from_ref(c), &mut |c| c.blends_through()) { + return false; + } + } + held +} + +/// Is child `c` written as a type layer, or as a group holding one ([`holds_type`])? A hidden child +/// is written only when `hidden`. +fn type_layer(c: &Node, hidden: bool) -> bool { + (c.visible || hidden) && (psd_type::editable(c).is_some() || holds_type(c, hidden)) +} + /// Does anything in `n` carry effects of its own that may paint outside the art's bounds? fn reaches_beyond(n: &Node) -> bool { fx::has_object_fx(n) || n.children().is_some_and(|c| c.iter().any(|c| reaches_beyond(c))) diff --git a/crates/render/src/encode/psd_type.rs b/crates/render/src/encode/psd_type.rs new file mode 100644 index 0000000000..f65e85bcf9 --- /dev/null +++ b/crates/render/src/encode/psd_type.rs @@ -0,0 +1,547 @@ +//! Type layers of PSD export: point type as a type tool object (the `TySh` block of the format's +//! public specification), so a reader can edit the text. The block holds the text's transform, the +//! text descriptor (the text, its orientation and bounds, and its `EngineData`: the runs of +//! character and paragraph attributes with the fonts they use) and an unwarped warp descriptor. +//! The layer keeps its pixels for readers that show them. + +use vectorcraft_color::Paint; +use vectorcraft_doc::text::TypeAntiAlias; +use vectorcraft_doc::{CharStyle, Composer, Justify, Node, NodeKind, ParaStyle, TextKind, TextObject}; +use vectorcraft_geom::{Affine, Point, Rect}; + +/// Point type that a type layer draws as `n` draws: horizontal or vertical point type with text, +/// whose characters use only the attributes a type layer carries ([`carried`]) in solid colours +/// with whole-number tracking, each drawn with its own font (no fallback font), without strokes or +/// inline graphics, whose paragraphs set only an alignment ([`flat`]) and run left to right, and +/// without System Layout, Optical Margin Alignment, ruby, an appearance of its own, effects or an +/// opacity mask. Other type stays pixels. +pub(super) fn editable(n: &Node) -> Option<&TextObject> { + let NodeKind::Text(t) = &n.kind else { return None }; + let text = t.plain_text(); + let has_cjk = text.chars().any(cjk); + let flat = |p: &ParaStyle| flat(p, has_cjk); + let plain = matches!(t.kind, TextKind::Point) + && !text.is_empty() + && !t.system_layout + && !t.optical_margin + && t.ruby.is_empty() + && !t.stacks_warichu() + && flat(&t.para) + && t.paras.iter().all(flat) + && text.split('\n').enumerate().all(|(i, p)| !vectorcraft_text::paragraph_is_rtl(p, t.para_at(i).direction)) + && n.appearance.items.is_empty() + && n.appearance.effects.is_empty() + && n.extras().mask.is_none() + && !crate::fx::has_object_fx(n) + && t.runs + .iter() + .all(|r| r.inline.is_none() && matches!(r.style.fill, Paint::Solid { .. }) && matches!(r.style.stroke, Paint::None) && carried(&r.style)) + // A type layer's tracking is a whole number of thousandths of an em. + && t.runs.iter().all(|r| r.style.tracking.fract() == 0.0) + // The type layer names one font per run: a character its font lacks would be drawn with + // another. Breaks, joiners and variation selectors draw no glyph of their own (as the + // shaper's `drawn_chars` counts them). + && t.runs.iter().all(|r| face(&r.style).is_some_and(|f| r.text.chars().all(|c| !drawn(c) || f.covers(c)))); + plain.then_some(&**t) +} + +/// Does `c` need a glyph of its own: not a control character (tab, line or paragraph break), a +/// line separator, a joiner or a variation selector? +fn drawn(c: char) -> bool { + !(c.is_control() || matches!(c, '\u{200C}' | '\u{200D}' | '\u{2028}' | '\u{FE00}'..='\u{FE0F}' | '\u{E0100}'..='\u{E01EF}')) +} + +/// The face the text of style `s` is drawn with: its font version when that is installed. +fn face(s: &CharStyle) -> Option> { + vectorcraft_text::FontDb::global().face_version(&s.font_family, &s.font_style, s.font_version.as_deref()) +} + +/// Does paragraph `p` set only its alignment, the others being at their defaults (no indents, +/// spacing, tabs, bullets or numbers, direction, Auto Leading, word or letter spacing, glyph scaling +/// or hanging punctuation)? Settings that only choose where area type breaks its lines or what +/// hangs where it breaks them (hyphenation, the single-line or every-line composer, kinsoku, +/// Burasagari, Bunri-Kinshi, breaking Korean anywhere) and the paragraph style's name may be set, +/// and so may Mojikumi when `cjk` is false (it spaces only Chinese, Japanese and Korean characters). +/// A paragraph set to a Standard composer is not flat. +fn flat(p: &ParaStyle, cjk: bool) -> bool { + let only = ParaStyle { + justify: p.justify, + style_name: p.style_name.clone(), + hyphenate: p.hyphenate, + hyphenation: p.hyphenation.clone(), + composer: if matches!(p.composer, Composer::SingleLine | Composer::EveryLine) { p.composer } else { ParaStyle::default().composer }, + kinsoku: p.kinsoku, + kinsoku_type: p.kinsoku_type, + burasagari: p.burasagari, + bunri_kinshi: p.bunri_kinshi, + korean_line_break_anywhere: p.korean_line_break_anywhere, + mojikumi: if cjk { ParaStyle::default().mojikumi } else { p.mojikumi }, + ..ParaStyle::default() + }; + only == *p +} + +/// Is `c` in a block of Chinese, Japanese or Korean characters or their punctuation? +fn cjk(c: char) -> bool { + matches!(c, '\u{1100}'..='\u{11FF}' | '\u{2E80}'..='\u{9FFF}' | '\u{A960}'..='\u{A97F}' | '\u{AC00}'..='\u{D7FF}' | '\u{F900}'..='\u{FAFF}' | '\u{FE30}'..='\u{FE4F}' | '\u{FF00}'..='\u{FFEF}' | '\u{20000}'..='\u{3FFFF}') +} + +/// Does `s` set only attributes a type layer carries (font and its version, size, leading, +/// tracking, scaling, baseline shift, all caps, underline, strikethrough, fill), the others being +/// at their defaults? Attributes that change nothing drawn without a stroke (the stroke's own +/// settings, overprint, the character style's name) may be set, and so may the language when it +/// is the default, English: USA. The type layer does not record the language, so type in another +/// language stays pixels. +fn carried(s: &CharStyle) -> bool { + if !s.language.as_deref().is_none_or(|l| l.eq_ignore_ascii_case("en-US")) { + return false; + } + let only = CharStyle { + language: s.language.clone(), + font_family: s.font_family.clone(), + font_style: s.font_style.clone(), + font_version: s.font_version.clone(), + size: s.size, + leading: s.leading, + tracking: s.tracking, + baseline_shift: s.baseline_shift, + h_scale: s.h_scale, + v_scale: s.v_scale, + fill: s.fill.clone(), + stroke: s.stroke.clone(), + stroke_width: s.stroke_width, + stroke_cap: s.stroke_cap, + stroke_join: s.stroke_join, + stroke_miter_limit: s.stroke_miter_limit, + stroke_dash: s.stroke_dash.clone(), + stroke_align: s.stroke_align, + overprint_fill: s.overprint_fill, + overprint_stroke: s.overprint_stroke, + style_name: s.style_name.clone(), + underline: s.underline, + strikethrough: s.strikethrough, + all_caps: s.all_caps, + ..CharStyle::default() + }; + only == *s +} + +/// A value of the `EngineData` text engine document. +enum E { + Dict(Vec<(&'static str, E)>), + Array(Vec), + Str(String), + Int(i64), + Real(f64), + Bool(bool), +} + +impl E { + fn is_container(&self) -> bool { + match self { + E::Dict(_) => true, + E::Array(a) => a.iter().any(|v| matches!(v, E::Dict(_) | E::Array(_))), + _ => false, + } + } + + /// Writes the value with tab indents and a key per line. + fn write(&self, depth: usize, out: &mut Vec) { + let tabs = |out: &mut Vec, n: usize| out.extend(std::iter::repeat_n(b'\t', n)); + match self { + E::Dict(items) => { + out.extend(b"<<\n"); + for (k, v) in items { + tabs(out, depth + 1); + out.push(b'/'); + out.extend(k.as_bytes()); + if v.is_container() { + out.push(b'\n'); + tabs(out, depth + 1); + } else { + out.push(b' '); + } + v.write(depth + 1, out); + out.push(b'\n'); + } + tabs(out, depth); + out.extend(b">>"); + } + E::Array(items) if self.is_container() => { + out.extend(b"[\n"); + for v in items { + tabs(out, depth); + v.write(depth, out); + out.push(b'\n'); + } + tabs(out, depth); + out.push(b']'); + } + E::Array(items) => { + out.push(b'['); + for v in items { + out.push(b' '); + v.write(depth, out); + } + out.extend(b" ]"); + } + // UTF-16BE after a byte order mark, with `(`, `)` and `\` escaped. + E::Str(s) => { + out.push(b'('); + for b in [0xFE, 0xFF].into_iter().chain(s.encode_utf16().flat_map(u16::to_be_bytes)) { + if matches!(b, b'(' | b')' | b'\\') { + out.push(b'\\'); + } + out.push(b); + } + out.push(b')'); + } + E::Int(i) => out.extend(i.to_string().as_bytes()), + E::Real(r) => out.extend(real(*r).as_bytes()), + E::Bool(b) => out.extend(if *b { &b"true"[..] } else { b"false" }), + } + } +} + +/// A number as the text engine writes it: `12.0`, `.5`, `-.25`; at most five decimals. +fn real(r: f64) -> String { + if !r.is_finite() { + return "0.0".into(); + } + let mut s = format!("{r:.5}"); + while s.ends_with('0') { + s.pop(); + } + if s.ends_with('.') { + s.push('0'); + } + if s == "-0.0" { + s = "0.0".into(); + } + match (s.strip_prefix("0."), s.strip_prefix("-0.")) { + (Some(rest), _) if rest != "0" => format!(".{rest}"), + (_, Some(rest)) => format!("-.{rest}"), + _ => s, + } +} + +/// A descriptor value (the format's ActionDescriptor items). +enum V { + Text(String), + Enum(&'static str, &'static str), + Long(i32), + Doub(f64), + /// A unit (`#Pnt`: points) and its value. + UntF(&'static [u8; 4], f64), + Objc(&'static str, Vec<(&'static str, V)>), + Raw(Vec), +} + +/// A class, key or enumeration id: a four-character code after a zero length, else its length and +/// bytes. `warp` is written as a string, as readers look it up. +fn id(out: &mut Vec, s: &str) { + if s.len() == 4 && s != "warp" { + out.extend(0u32.to_be_bytes()); + } else { + out.extend((s.len() as u32).to_be_bytes()); + } + out.extend(s.as_bytes()); +} + +/// A Unicode string: its UTF-16 unit count, then the units (`nul`: a terminating zero counted). +fn unicode(out: &mut Vec, s: &str, nul: bool) { + let units: Vec = s.encode_utf16().chain(nul.then_some(0)).collect(); + out.extend((units.len() as u32).to_be_bytes()); + out.extend(units.iter().flat_map(|u| u.to_be_bytes())); +} + +/// A descriptor: an empty class name, the class id, then its items. +fn descriptor(out: &mut Vec, class: &str, items: &[(&str, V)]) { + unicode(out, "", false); + id(out, class); + out.extend((items.len() as u32).to_be_bytes()); + for (key, v) in items { + id(out, key); + match v { + V::Text(s) => { + out.extend(b"TEXT"); + unicode(out, s, true); + } + V::Enum(ty, value) => { + out.extend(b"enum"); + id(out, ty); + id(out, value); + } + V::Long(i) => { + out.extend(b"long"); + out.extend(i.to_be_bytes()); + } + V::Doub(d) => { + out.extend(b"doub"); + out.extend(d.to_be_bytes()); + } + V::UntF(unit, d) => { + out.extend(b"UntF"); + out.extend(*unit); + out.extend(d.to_be_bytes()); + } + V::Objc(class, items) => { + out.extend(b"Objc"); + descriptor(out, class, items); + } + V::Raw(data) => { + out.extend(b"tdta"); + out.extend((data.len() as u32).to_be_bytes()); + out.extend(data); + } + } + } +} + +/// The PostScript name of the face the text is drawn with (the style's font version when that is +/// installed), as type layers name fonts; without the face installed, its family and style without +/// spaces. +fn postscript(s: &CharStyle) -> String { + if let Some(face) = face(s) { + return face.postscript_name(); + } + let squeeze = |s: &str| -> String { s.chars().filter(|c| c.is_ascii_graphic() && !"[](){}<>/%".contains(*c)).collect() }; + match s.font_style.as_str() { + "" | "Regular" => squeeze(&s.font_family), + style => format!("{}-{}", squeeze(&s.font_family), squeeze(style)), + } +} + +/// The character attributes of `s` at `px` pixels per point, its font being `font` in the font set. +fn style_data(s: &CharStyle, font: usize, px: f64) -> E { + let rgb = match &s.fill { + Paint::Solid { color, .. } => color.to_rgb(), + _ => [0.0; 3], + }; + E::Dict(vec![ + ("Font", E::Int(font as i64)), + ("FontSize", E::Real(s.size * px)), + ("FauxBold", E::Bool(false)), + ("FauxItalic", E::Bool(false)), + ("AutoLeading", E::Bool(s.leading.is_none())), + ("Leading", E::Real(s.leading.unwrap_or(0.0) * px)), + ("HorizontalScale", E::Real(s.h_scale / 100.0)), + ("VerticalScale", E::Real(s.v_scale / 100.0)), + ("Tracking", E::Int(s.tracking.round() as i64)), + ("AutoKerning", E::Bool(true)), + ("Kerning", E::Int(0)), + ("BaselineShift", E::Real(s.baseline_shift * px)), + ("FontCaps", E::Int(if s.all_caps { 2 } else { 0 })), + ("Underline", E::Bool(s.underline)), + ("Strikethrough", E::Bool(s.strikethrough)), + ("FillFlag", E::Bool(true)), + ("FillColor", E::Dict(vec![("Type", E::Int(1)), ("Values", E::Array([1.0, rgb[0], rgb[1], rgb[2]].map(|v| E::Real(f64::from(v))).into()))])), + ]) +} + +/// The paragraph attributes of alignment `j`. +fn paragraph_data(j: Justify) -> E { + let n = match j { + Justify::Auto | Justify::Left => 0, + Justify::Right => 1, + Justify::Center => 2, + Justify::JustifyLeft => 3, + Justify::JustifyRight => 4, + Justify::JustifyCenter => 5, + Justify::JustifyAll => 6, + }; + E::Dict(vec![("Justification", E::Int(n)), ("AutoLeading", E::Real(1.2)), ("LeadingType", E::Int(0))]) +} + +/// The anti-aliasing method `aa` as the text descriptor's `AntA` value and the `EngineData` +/// `AntiAlias` number. +fn anti_alias(aa: TypeAntiAlias) -> (&'static str, i64) { + match aa { + TypeAntiAlias::None => ("Anno", 0), + TypeAntiAlias::Crisp => ("AnCr", 1), + TypeAntiAlias::Strong => ("AnSt", 2), + TypeAntiAlias::Sharp => ("AnSh", 4), + } +} + +/// The `EngineData` of `t` at `px` pixels per point, drawn with anti-aliasing `aa`: the text with a +/// `\r` after each paragraph, a style run per text run and a paragraph run per paragraph (lengths in +/// UTF-16 units), point type's shape, and the fonts. +fn engine_data(t: &TextObject, px: f64, aa: TypeAntiAlias) -> Vec { + let text = t.plain_text().replace('\n', "\r"); + let mut fonts: Vec = vec![]; + let (mut styles, mut lengths) = (vec![], vec![]); + let runs: Vec<_> = t.runs.iter().filter(|r| !r.text.is_empty()).collect(); + for (i, r) in runs.iter().enumerate() { + let name = postscript(&r.style); + let font = fonts.iter().position(|f| *f == name).unwrap_or_else(|| { + fonts.push(name); + fonts.len() - 1 + }); + styles.push(E::Dict(vec![("StyleSheet", E::Dict(vec![("StyleSheetData", style_data(&r.style, font, px))]))])); + // The closing `\r` belongs to the last run. + lengths.push(E::Int(r.text.encode_utf16().count() as i64 + i64::from(i + 1 == runs.len()))); + } + let (mut paras, mut para_lengths) = (vec![], vec![]); + for (i, p) in text.split('\r').enumerate() { + paras.push(E::Dict(vec![( + "ParagraphSheet", + E::Dict(vec![("DefaultStyleSheet", E::Int(0)), ("Properties", paragraph_data(t.para_at(i).justify))]), + )])); + para_lengths.push(E::Int(p.encode_utf16().count() as i64 + 1)); + } + let (writing, procession) = if t.vertical { (2, 1) } else { (0, 0) }; + let point = |x: f64, y: f64| E::Array(vec![E::Real(x), E::Real(y)]); + let shape = E::Dict(vec![ + ("ShapeType", E::Int(0)), + ("Procession", E::Int(procession)), + ("Lines", E::Dict(vec![("WritingDirection", E::Int(writing)), ("Children", E::Array(vec![]))])), + ( + "Cookie", + E::Dict(vec![( + "Photoshop", // brand-ok: the key's name in the files + E::Dict(vec![ + ("ShapeType", E::Int(0)), + ("PointBase", point(0.0, 0.0)), + ( + "Base", + E::Dict(vec![ + ("ShapeType", E::Int(0)), + ("TransformPoint0", point(1.0, 0.0)), + ("TransformPoint1", point(0.0, 1.0)), + ("TransformPoint2", point(0.0, 0.0)), + ]), + ), + ]), + )]), + ), + ]); + let first = runs.first().map_or_else(|| style_data(&CharStyle::default(), 0, px), |r| style_data(&r.style, 0, px)); + let resources = || { + E::Dict(vec![ + ( + "FontSet", + E::Array( + fonts + .iter() + .map(|f| E::Dict(vec![("Name", E::Str(f.clone())), ("Script", E::Int(0)), ("FontType", E::Int(1)), ("Synthetic", E::Int(0))])) + .collect(), + ), + ), + ("StyleSheetSet", E::Array(vec![E::Dict(vec![("Name", E::Str("Normal RGB".into())), ("StyleSheetData", E::Dict(vec![]))])])), + ( + "ParagraphSheetSet", + E::Array(vec![E::Dict(vec![ + ("Name", E::Str("Normal RGB".into())), + ("DefaultStyleSheet", E::Int(0)), + ("Properties", paragraph_data(Justify::Left)), + ])]), + ), + ("TheNormalStyleSheet", E::Int(0)), + ("TheNormalParagraphSheet", E::Int(0)), + ]) + }; + let mut normal = resources(); + // The normal style sheet holds the first run's attributes. + if let E::Dict(items) = &mut normal + && let Some((_, E::Array(sheets))) = items.iter_mut().find(|(k, _)| *k == "StyleSheetSet") + && let Some(E::Dict(sheet)) = sheets.first_mut() + && let Some((_, data)) = sheet.iter_mut().find(|(k, _)| *k == "StyleSheetData") + { + *data = first; + } + let doc = E::Dict(vec![ + ( + "EngineDict", + E::Dict(vec![ + ("Editor", E::Dict(vec![("Text", E::Str(format!("{text}\r")))])), + ("ParagraphRun", E::Dict(vec![("RunArray", E::Array(paras)), ("RunLengthArray", E::Array(para_lengths)), ("IsJoinable", E::Int(1))])), + ("StyleRun", E::Dict(vec![("RunArray", E::Array(styles)), ("RunLengthArray", E::Array(lengths)), ("IsJoinable", E::Int(2))])), + ("AntiAlias", E::Int(anti_alias(aa).1)), + ("UseFractionalGlyphWidths", E::Bool(t.fractional_widths)), + ( + "Rendered", + E::Dict(vec![ + ("Version", E::Int(1)), + ("Shapes", E::Dict(vec![("WritingDirection", E::Int(writing)), ("Children", E::Array(vec![shape]))])), + ]), + ), + ]), + ), + ("ResourceDict", resources()), + ("DocumentResources", normal), + ]); + let mut out = b"\n\n".to_vec(); + doc.write(0, &mut out); + out.push(b'\n'); + out +} + +/// The `TySh` block of point type `t`, drawn into a canvas whose top left is `origin` (document +/// points) at `px` pixels per point with anti-aliasing `aa`; `ink` is what the layer paints, in +/// canvas pixels. The transform maps the text's own space, in pixels with its origin at the first +/// baseline's start, to the canvas. +pub(super) fn type_block(t: &TextObject, origin: Point, px: f64, ink: Rect, aa: TypeAntiAlias) -> Vec { + let [a, b, c, d, e, f] = t.xf.as_coeffs(); + let xf = Affine::new([a, b, c, d, (e - origin.x) * px, (f - origin.y) * px]); + // The ink in text space: the canvas rectangle taken back through the transform. + let bounds = if xf.determinant().abs() > 1e-12 && [ink.x0, ink.y0, ink.x1, ink.y1].iter().all(|v| v.is_finite()) { + let inv = xf.inverse(); + let pts = [(ink.x0, ink.y0), (ink.x1, ink.y0), (ink.x0, ink.y1), (ink.x1, ink.y1)].map(|(x, y)| inv * Point::new(x, y)); + let (xs, ys) = (pts.map(|p| p.x), pts.map(|p| p.y)); + let (min, max) = (|v: [f64; 4]| v.into_iter().fold(f64::INFINITY, f64::min), |v: [f64; 4]| v.into_iter().fold(f64::NEG_INFINITY, f64::max)); + [min(xs), min(ys), max(xs), max(ys)] + } else { + [0.0; 4] + }; + let rect = |class: &'static str| { + V::Objc( + class, + vec![ + ("Left", V::UntF(b"#Pnt", bounds[0])), + ("Top ", V::UntF(b"#Pnt", bounds[1])), + ("Rght", V::UntF(b"#Pnt", bounds[2])), + ("Btom", V::UntF(b"#Pnt", bounds[3])), + ], + ) + }; + let orientation = if t.vertical { "Vrtc" } else { "Hrzn" }; + let mut out = 1u16.to_be_bytes().to_vec(); + for v in xf.as_coeffs() { + out.extend(v.to_be_bytes()); + } + // Text version 50, descriptor version 16. + out.extend(50u16.to_be_bytes()); + out.extend(16u32.to_be_bytes()); + descriptor( + &mut out, + "TxLr", + &[ + ("Txt ", V::Text(t.plain_text().replace('\n', "\r"))), + ("textGridding", V::Enum("textGridding", "None")), + ("Ornt", V::Enum("Ornt", orientation)), + ("AntA", V::Enum("Annt", anti_alias(aa).0)), + ("bounds", rect("bounds")), + ("boundingBox", rect("boundingBox")), + ("TextIndex", V::Long(0)), + ("EngineData", V::Raw(engine_data(t, px, aa))), + ], + ); + // Warp version 1, descriptor version 16: no warp. + out.extend(1u16.to_be_bytes()); + out.extend(16u32.to_be_bytes()); + descriptor( + &mut out, + "warp", + &[ + ("warpStyle", V::Enum("warpStyle", "warpNone")), + ("warpValue", V::Doub(0.0)), + ("warpPerspective", V::Doub(0.0)), + ("warpPerspectiveOther", V::Doub(0.0)), + ("warpRotate", V::Enum("Ornt", "Hrzn")), + ], + ); + // The warped bounds: zeros without a warp. + out.extend([0u8; 16]); + out +} diff --git a/crates/render/src/encode/tests.rs b/crates/render/src/encode/tests.rs index a910480641..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, @@ -86,8 +124,10 @@ fn gray_and_bilevel_images_store_gray() { assert_eq!(gray(&file), levels); let (mime, file) = img.to_bilevel(150.0).unwrap(); assert_eq!(mime, "image/tiff"); - let mut d = ::tiff::decoder::Decoder::new(std::io::Cursor::new(&file)).unwrap(); - assert_eq!(d.colortype().unwrap(), ::tiff::ColorType::Gray(1)); + let tiff = craft_tiff::Tiff::parse(&file).unwrap(); + let ifd = &tiff.ifds[0]; + assert_eq!(ifd.u16(craft_tiff::tags::SAMPLES_PER_PIXEL), Some(1)); + assert_eq!(ifd.value(craft_tiff::tags::BITS_PER_SAMPLE).unwrap().to_u64_vec(), vec![1]); let bw: Vec = [0u8, 0, 255, 255, 255, 0].iter().flat_map(|&g| [g, 255]).collect(); assert_eq!(gray(&file), bw, "from 128 up is white"); // Half-covered white over the light grey; a clear pixel is white. @@ -114,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] @@ -173,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_psd.rs b/crates/render/src/encode/tests_psd.rs index a488cceff2..012921cb37 100644 --- a/crates/render/src/encode/tests_psd.rs +++ b/crates/render/src/encode/tests_psd.rs @@ -1,15 +1,16 @@ //! PSD export: the header, the layer records (names, bounds, opacity, blend modes, groups, -//! hidden layers), the merged image, the colour models, and a reader's view of the file. +//! hidden layers), the merged image, the colour models, the slices, and a reader's view of the +//! file. use std::sync::Arc; use vectorcraft_color::{BlendMode, Color}; -use vectorcraft_doc::{Document, LayerColor, Node}; +use vectorcraft_doc::{Document, LayerColor, Node, NodeId, Slice, SliceKind, SliceOptions}; use vectorcraft_geom::Rect; use vectorcraft_testkit::fixtures::DocBuilder; use super::jpeg::ColorModel; -use super::psd::{MAX_SIDE, PsdOptions}; +use super::psd::{MAX_SIDE, MAX_SLICE_TEXT, MAX_SLICES, PsdOptions, room}; use super::*; /// A 100 × 60 pt document: a red square on Layer 1, and on "Top" a half-opaque blue multiply @@ -58,6 +59,8 @@ struct Rec { opacity: u8, hidden: bool, divider: Option, + /// The type tool object of a type layer. + type_tool: Option>, } /// The file: header channels, colour mode, image resources, layer count and records. @@ -95,7 +98,7 @@ fn parse(f: &[u8]) -> Parsed<'_> { let end = p + 16 + u32_at(f, p + 12); let mut q = p + 16 + 8; q += (1 + f[q] as usize).next_multiple_of(4); - let (mut name, mut divider) = (String::new(), None); + let (mut name, mut divider, mut type_tool) = (String::new(), None, None); while q < end { assert_eq!(&f[q..q + 4], b"8BIM"); let len = u32_at(f, q + 8); @@ -103,11 +106,12 @@ fn parse(f: &[u8]) -> Parsed<'_> { match &f[q + 4..q + 8] { b"luni" => name = String::from_utf16(&(0..u32_at(data, 0)).map(|i| u16_at(data, 4 + i * 2)).collect::>()).unwrap(), b"lsct" => divider = Some(u32_at(data, 0)), + b"TySh" => type_tool = Some(data.to_vec()), _ => {} } q += 12 + len; } - out.records.push(Rec { name, rect, channels, blend, opacity, hidden: flags & 2 != 0, divider }); + out.records.push(Rec { name, rect, channels, blend, opacity, hidden: flags & 2 != 0, divider, type_tool }); p = end; } out @@ -144,9 +148,18 @@ fn unpack(mut src: &[u8], out: &mut Vec) { } } -/// The composite as a reader sees it. +/// The stored composite: RGB stays white-matted, with its original alpha. fn merged(f: &[u8]) -> Vec { - ::psd::Psd::from_bytes(f).expect("a PSD a reader takes").rgba() + let psd = craft_psd::PsdFile::from_bytes(f).expect("a PSD a reader takes"); + if psd.header.color_mode != craft_psd::ColorMode::Rgb { + return psd.composite_rgba8().expect("composite").data; + } + assert_eq!(psd.header.depth, 8); + let samples = psd.decode_merged().expect("stored composite planes"); + let count = psd.header.width as usize * psd.header.height as usize; + (0..count) + .flat_map(|i| [samples[i], samples[count + i], samples[2 * count + i], if psd.merged_has_alpha() { samples[3 * count + i] } else { 255 }]) + .collect() } fn pixel(px: &[u8], width: usize, x: usize, y: usize) -> [u8; 4] { @@ -168,11 +181,12 @@ fn layers_are_the_top_level_layers_and_the_merged_image_is_the_render() { assert_eq!(p.records[1].rect, [0, 0, 50, 60], "the blue square and the corner"); // A reader decodes it: the layers, in place, and the merged image. - let psd = ::psd::Psd::from_bytes(&file).unwrap(); - assert_eq!((psd.width(), psd.height(), psd.layers().len()), (100, 60, 2)); - let red = psd.layer_by_name("Layer 1").unwrap().rgba(); - assert_eq!(pixel(&red, 100, 20, 20), [255, 0, 0, 255]); - assert_eq!(pixel(&red, 100, 50, 45)[3], 0, "the blue square isn't on Layer 1"); + let psd = craft_psd::PsdFile::from_bytes(&file).unwrap(); + assert_eq!((psd.header.width, psd.header.height, psd.layers().len()), (100, 60, 2)); + let layer = psd.iter_layers().find(|l| l.name() == "Layer 1").unwrap(); + assert_eq!(layer.record.rect, craft_psd::layer::Rect { top: 10, left: 10, bottom: 40, right: 40 }); + let red = layer.rgba8().unwrap().data; + assert_eq!(pixel(&red, 30, 10, 10), [255, 0, 0, 255]); // The merged image is the flat render: colours on white where transparent, alpha apart. let img = Renderer::new().render_region_with(&doc, doc.artboards[0].rect, 1.0, &opts(PsdOptions::default()).render_options(RasterFormat::Psd)); @@ -200,7 +214,7 @@ fn flat_writes_the_merged_image_alone_on_white() { assert_eq!(o.encode(&img, RasterFormat::Psd).unwrap(), file); let file = export(&doc, &RasterExportOptions { ppi: 150.0, ..o }); assert_eq!(u32_at(parse(&file).resources, 12), 150 << 16); - assert_eq!(::psd::Psd::from_bytes(&file).unwrap().width(), 208); + assert_eq!(craft_psd::PsdFile::from_bytes(&file).unwrap().header.width, 208); } #[test] @@ -230,8 +244,11 @@ fn maximum_editability_writes_groups_and_an_object_per_layer() { assert_eq!((p.records[4].opacity, p.records[4].blend, p.records[4].rect), (128, *b"mul ", [20, 30, 50, 60])); assert_eq!((p.records[8].blend, p.records[8].opacity), (*b"pass", 255)); assert_eq!(p.records[6].rect, [0, 0, 6, 6]); - let psd = ::psd::Psd::from_bytes(&file).unwrap(); - assert_eq!((psd.layers().len(), psd.groups().len()), (3, 3)); + let psd = craft_psd::PsdFile::from_bytes(&file).unwrap(); + let content_layers = psd.layers().iter().filter(|l| matches!(l.section_type(), craft_psd::SectionType::Other)).count(); + let groups = + psd.layers().iter().filter(|l| matches!(l.section_type(), craft_psd::SectionType::OpenFolder | craft_psd::SectionType::ClosedFolder)).count(); + assert_eq!((content_layers, groups), (3, 3)); assert_eq!(merged(&file), merged(&export(&doc, &opts(PsdOptions::default()))), "the same merged image"); // Hidden layers: written hidden, drawn as if visible, instead of left out. @@ -300,8 +317,8 @@ fn a_background_colour_is_the_bottom_layer() { let p = parse(&file); assert_eq!((p.channels, p.count), (3, 3), "opaque: no merged alpha"); assert_eq!((p.records[0].name.as_str(), p.records[0].rect), ("Background", [0, 0, 60, 100])); - let psd = ::psd::Psd::from_bytes(&file).unwrap(); - assert!(psd.layer_by_name("Background").unwrap().rgba().chunks(4).all(|p| p == [0, 0, 255, 255])); + let psd = craft_psd::PsdFile::from_bytes(&file).unwrap(); + assert!(psd.iter_layers().find(|l| l.name() == "Background").unwrap().rgba8().unwrap().data.chunks(4).all(|p| p == [0, 0, 255, 255])); assert_eq!(pixel(&merged(&file), 100, 5, 50), [0, 0, 255, 255]); } @@ -344,6 +361,373 @@ fn the_profile_and_the_size_limit() { assert!(err.contains(&MAX_SIDE.to_string()), "{err}"); } +/// A descriptor value as the format's specification lays it out. +#[derive(Debug, PartialEq)] +enum Item { + Text(String), + Enum(String, String), + Long(i32), + Doub(f64), + Unit(String, f64), + Object(String, Vec<(String, Item)>), + Raw(Vec), +} + +/// Reads an id (a four-character code after a zero length, else a length and its bytes) at `at`. +fn read_id(d: &[u8], at: &mut usize) -> String { + let n = u32_at(d, *at); + let len = if n == 0 { 4 } else { n }; + let s = String::from_utf8(d[*at + 4..*at + 4 + len].to_vec()).unwrap(); + *at += 4 + len; + s +} + +fn read_unicode(d: &[u8], at: &mut usize) -> String { + let n = u32_at(d, *at); + let units: Vec = (0..n).map(|i| u16_at(d, *at + 4 + i * 2)).collect(); + *at += 4 + n * 2; + String::from_utf16(&units).unwrap().trim_end_matches('\0').to_string() +} + +/// Reads a descriptor at `at`: its class and items. +fn read_descriptor(d: &[u8], at: &mut usize) -> (String, Vec<(String, Item)>) { + read_unicode(d, at); + let class = read_id(d, at); + let count = u32_at(d, *at); + *at += 4; + let mut items = vec![]; + for _ in 0..count { + let key = read_id(d, at); + let ty = d[*at..*at + 4].to_vec(); + *at += 4; + let f64_at = |at: usize| f64::from_be_bytes(d[at..at + 8].try_into().unwrap()); + let v = match &ty[..] { + b"TEXT" => Item::Text(read_unicode(d, at)), + b"enum" => Item::Enum(read_id(d, at), read_id(d, at)), + b"long" => { + *at += 4; + Item::Long(u32_at(d, *at - 4) as i32) + } + b"doub" => { + *at += 8; + Item::Doub(f64_at(*at - 8)) + } + b"UntF" => { + let unit = String::from_utf8(d[*at..*at + 4].to_vec()).unwrap(); + *at += 12; + Item::Unit(unit, f64_at(*at - 8)) + } + b"Objc" => { + let (class, items) = read_descriptor(d, at); + Item::Object(class, items) + } + b"tdta" => { + let n = u32_at(d, *at); + *at += 4 + n; + Item::Raw(d[*at - n..*at].to_vec()) + } + other => panic!("unexpected item type {other:?}"), + }; + items.push((key, v)); + } + (class, items) +} + +/// A type tool object: its transform, its text descriptor and its warp descriptor. +struct TypeTool { + transform: [f64; 6], + text: Vec<(String, Item)>, + warp: (String, Vec<(String, Item)>), +} + +fn type_tool(d: &[u8]) -> TypeTool { + assert_eq!(u16_at(d, 0), 1, "version"); + let transform = std::array::from_fn(|i| f64::from_be_bytes(d[2 + i * 8..10 + i * 8].try_into().unwrap())); + assert_eq!((u16_at(d, 50), u32_at(d, 52)), (50, 16), "text and descriptor versions"); + let mut at = 56; + let (class, text) = read_descriptor(d, &mut at); + assert_eq!(class, "TxLr"); + assert_eq!((u16_at(d, at), u32_at(d, at + 2)), (1, 16), "warp and descriptor versions"); + at += 6; + let warp = read_descriptor(d, &mut at); + assert_eq!(d.len(), (at + 16).next_multiple_of(2), "the four warped bounds end the block (padded to an even length)"); + TypeTool { transform, text, warp } +} + +fn item<'a>(items: &'a [(String, Item)], key: &str) -> &'a Item { + &items.iter().find(|(k, _)| k == key).unwrap_or_else(|| panic!("no {key}")).1 +} + +/// `s` as the text engine stores a string: UTF-16BE after a byte order mark. +fn engine_string(s: &str) -> Vec { + [0xFE, 0xFF].into_iter().chain(s.encode_utf16().flat_map(u16::to_be_bytes)).collect() +} + +fn type_node(b: &mut DocBuilder, origin: (f64, f64), text: &str, f: impl FnOnce(&mut vectorcraft_doc::TextObject)) -> Node { + use vectorcraft_doc::{CharStyle, NodeKind, TextObject}; + let style = CharStyle { size: 12.0, fill: vectorcraft_color::Paint::solid(Color::rgb8(0, 0, 0)), ..CharStyle::default() }; + let mut t = TextObject::point(vectorcraft_geom::Point::new(origin.0, origin.1), text, style); + f(&mut t); + Node::new(b.alloc(), NodeKind::Text(Box::new(t))) +} + +/// Layer 1: a red square, point type, a blue square. +fn type_doc() -> Document { + let mut b = DocBuilder::new(100.0, 60.0); + b.rect(Rect::new(0.0, 0.0, 30.0, 30.0), Color::rgb8(255, 0, 0), |_| {}); + let t = type_node(&mut b, (20.0, 40.0), "Hi\nyou", |_| {}); + b.add(t); + b.rect(Rect::new(60.0, 10.0, 90.0, 40.0), Color::rgb8(0, 0, 255), |_| {}); + b.build() +} + +#[test] +fn preserve_text_writes_point_type_as_a_type_layer_between_pixel_layers() { + let doc = type_doc(); + let o = RasterExportOptions { ppi: 144.0, ..opts(PsdOptions { preserve_text: true, ..PsdOptions::default() }) }; + let file = export(&doc, &o); + let p = parse(&file); + let rows: Vec<(&str, Option, bool)> = p.records.iter().map(|r| (r.name.as_str(), r.divider, r.type_tool.is_some())).collect(); + assert_eq!( + rows, + [ + ("", Some(3), false), + ("Layer 1", None, false), + ("Hi\nyou", None, true), + ("Layer 1", None, false), + ("Layer 1", Some(1), false), + ], + "the layer becomes a group: the art below the type, the type layer, the art above it" + ); + assert_eq!(p.records[1].rect, [0, 0, 60, 60], "the red square alone, at 2 pixels a point"); + assert_eq!(p.records[3].rect, [20, 120, 80, 180], "the blue square alone"); + assert_ne!(p.records[2].rect, [0; 4], "the type layer keeps its pixels"); + + let t = type_tool(p.records[2].type_tool.as_deref().unwrap()); + assert_eq!(t.transform, [1.0, 0.0, 0.0, 1.0, 40.0, 80.0], "the first baseline's start, in pixels"); + assert_eq!(item(&t.text, "Txt "), &Item::Text("Hi\ryou".into())); + assert_eq!(item(&t.text, "Ornt"), &Item::Enum("Ornt".into(), "Hrzn".into())); + let Item::Object(_, bounds) = item(&t.text, "bounds") else { panic!("bounds") }; + let [l, top, r, bottom] = ["Left", "Top ", "Rght", "Btom"].map(|k| match item(bounds, k) { + Item::Unit(_, v) => *v, + other => panic!("{other:?}"), + }); + assert!(l < 4.0 && top < 0.0 && r > l && bottom > 24.0, "the ink around the baselines: {l} {top} {r} {bottom}"); + assert_eq!(t.warp.0, "warp"); + assert_eq!(item(&t.warp.1, "warpStyle"), &Item::Enum("warpStyle".into(), "warpNone".into())); + + let Item::Raw(engine) = item(&t.text, "EngineData") else { panic!("EngineData") }; + let has = |needle: &[u8]| engine.windows(needle.len()).any(|w| w == needle); + assert!(has(&engine_string("Hi\ryou\r")), "the text ends with a paragraph break"); + assert!(has(b"/FontSize 24.0"), "the size in pixels at 144 ppi"); + assert!(has(b"/RunLengthArray [ 3 4 ]"), "a paragraph run per paragraph, breaks counted"); + assert!(has(b"/RunLengthArray [ 7 ]"), "one style run over the text and the closing break"); + assert!(has(b"/Values [ 1.0 0.0 0.0 0.0 ]"), "black"); + assert!(has(b"/ShapeType 0"), "point type"); + assert!(has(b"/UseFractionalGlyphWidths true"), "Fractional Widths on"); + + // A reader takes the file, and the merged image is the same render. + assert_eq!(craft_psd::PsdFile::from_bytes(&file).unwrap().layers().len(), p.records.len()); + let plain = export(&doc, &RasterExportOptions { ppi: 144.0, ..opts(PsdOptions::default()) }); + assert_eq!(merged(&file), merged(&plain)); + assert_eq!(parse(&plain).records.iter().filter(|r| r.type_tool.is_some()).count(), 0, "off: no type layers"); +} + +#[test] +fn type_a_type_layer_cant_draw_stays_pixels() { + use vectorcraft_doc::{NodeKind, TextKind}; + use vectorcraft_geom::PathData; + let mut b = DocBuilder::new(100.0, 60.0); + let area = type_node(&mut b, (10.0, 20.0), "Area", |t| { + t.kind = TextKind::Area { frame: PathData::from_bezpath(&vectorcraft_geom::Shape::to_path(&Rect::new(5.0, 5.0, 60.0, 50.0), 0.1)) }; + }); + b.add(area); + let stroked = type_node(&mut b, (10.0, 50.0), "Stroked", |t| { + t.runs[0].style.stroke = vectorcraft_color::Paint::solid(Color::rgb8(255, 0, 0)); + t.runs[0].style.stroke_width = 1.0; + }); + b.add(stroked); + let kerned = type_node(&mut b, (40.0, 50.0), "Kerned", |t| t.runs[0].style.kerning = Some(50.0)); + b.add(kerned); + let indented = type_node(&mut b, (70.0, 50.0), "Indented", |t| t.para.first_line_indent = 4.0); + b.add(indented); + let listed = type_node(&mut b, (10.0, 35.0), "Listed", |t| t.para.list = Some(vectorcraft_doc::text::ParaList::default())); + b.add(listed); + let system = type_node(&mut b, (40.0, 35.0), "System", |t| t.system_layout = true); + b.add(system); + let hanging = type_node(&mut b, (70.0, 35.0), "\"Hung\"", |t| t.optical_margin = true); + b.add(hanging); + let tabbed = type_node(&mut b, (10.0, 10.0), "a\tb", |t| { + t.para.tabs = vec![vectorcraft_doc::TabStop { position: 30.0, align: Default::default(), leader: String::new(), align_on: '.' }]; + }); + b.add(tabbed); + let leading = type_node(&mut b, (40.0, 10.0), "Auto", |t| t.para.justification.auto_leading = 150.0); + b.add(leading); + let standard = type_node(&mut b, (40.0, 20.0), "Std", |t| t.para.composer = vectorcraft_doc::Composer::StandardEveryLine); + b.add(standard); + // Hebrew: right to left from its first strong character, so Auto alignment is right. In an + // installed font that covers it when there is one; otherwise its font lacks it. + let hebrew_face = vectorcraft_text::FontDb::global().face_covering('ש'); + let hebrew = type_node(&mut b, (70.0, 10.0), "שלום", |t| { + if let Some(f) = &hebrew_face { + (t.runs[0].style.font_family, t.runs[0].style.font_style) = (f.family.clone(), f.style.clone()); + } + }); + b.add(hebrew); + let tracked = type_node(&mut b, (10.0, 58.0), "Tracked", |t| t.runs[0].style.tracking = 0.5); + b.add(tracked); + let british = type_node(&mut b, (70.0, 58.0), "Colour", |t| t.runs[0].style.language = Some("en-GB".into())); + b.add(british); + // Drawn partly with a fallback font: the bundled fonts have no 縦. + let fallback = type_node(&mut b, (40.0, 58.0), "A縦", |_| {}); + b.add(fallback); + let mut doc = b.build(); + let with = |o: PsdOptions| export(&doc, &opts(o)); + assert_eq!(with(PsdOptions { preserve_text: true, ..PsdOptions::default() }), with(PsdOptions::default()), "one pixel layer either way"); + + // An empty point type object has no text to edit. + let empty = Node::new( + doc.alloc_id(), + NodeKind::Text(Box::new(vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "", Default::default()))), + ); + doc.insert(Some(doc.layers[0].id), usize::MAX, empty).unwrap(); + let file = export(&doc, &opts(PsdOptions { preserve_text: true, ..PsdOptions::default() })); + assert!(parse(&file).records.iter().all(|r| r.type_tool.is_none())); +} + +#[test] +fn vertical_type_and_maximum_editability() { + let mut b = DocBuilder::new(100.0, 60.0); + b.rect(Rect::new(0.0, 0.0, 10.0, 10.0), Color::rgb8(255, 0, 0), |_| {}); + let t = type_node(&mut b, (50.0, 10.0), "Up", |t| t.vertical = true); + b.add(t); + let hidden = type_node(&mut b, (10.0, 50.0), "Hidden", |_| {}); + b.add(Node { visible: false, ..hidden }); + let doc = b.build(); + let o = opts(PsdOptions { preserve_text: true, max_editability: true, hidden_layers: true, ..PsdOptions::default() }); + let file = export(&doc, &o); + let p = parse(&file); + let rows: Vec<(&str, bool, bool)> = p.records.iter().map(|r| (r.name.as_str(), r.type_tool.is_some(), r.hidden)).collect(); + let square = doc.layers[0].children().unwrap()[0].display_name(); + assert_eq!( + rows, + [("", false, false), (square.as_str(), false, false), ("Up", true, false), ("Hidden", true, true), ("Layer 1", false, false)], + "each object a layer of its own; hidden type is a hidden type layer" + ); + let t = type_tool(p.records[2].type_tool.as_deref().unwrap()); + assert_eq!(item(&t.text, "Ornt"), &Item::Enum("Ornt".into(), "Vrtc".into())); + let Item::Raw(engine) = item(&t.text, "EngineData") else { panic!("EngineData") }; + assert!(engine.windows(19).any(|w| w == b"/WritingDirection 2"), "vertical writing"); +} + +#[test] +fn type_layer_keeps_fractional_widths_off() { + let mut b = DocBuilder::new(100.0, 60.0); + let t = type_node(&mut b, (10.0, 30.0), "Whole", |t| t.fractional_widths = false); + b.add(t); + let file = export(&b.build(), &opts(PsdOptions { preserve_text: true, ..PsdOptions::default() })); + let p = parse(&file); + let record = p.records.iter().find(|r| r.type_tool.is_some()).expect("a type layer"); + let t = type_tool(record.type_tool.as_deref().unwrap()); + let Item::Raw(engine) = item(&t.text, "EngineData") else { panic!("EngineData") }; + let needle = b"/UseFractionalGlyphWidths false"; + assert!(engine.windows(needle.len()).any(|w| w == needle), "whole-point advances, as the pixels are drawn"); +} + +#[test] +fn type_layer_keeps_the_anti_aliasing_method() { + use vectorcraft_doc::text::TypeAntiAlias; + let engine_anti_alias = |doc: &Document, o: &RasterExportOptions| { + let file = export(doc, o); + let p = parse(&file); + let t = type_tool(p.records.iter().find_map(|r| r.type_tool.as_deref()).expect("a type layer")); + let Item::Raw(engine) = item(&t.text, "EngineData") else { panic!("EngineData") }; + let at = engine.windows(11).position(|w| w == b"/AntiAlias ").expect("AntiAlias"); + let Item::Enum(_, method) = item(&t.text, "AntA") else { panic!("AntA") }; + (method.clone(), engine[at + 11]) + }; + let o = opts(PsdOptions { preserve_text: true, ..PsdOptions::default() }); + for (aa, key, number) in [ + (TypeAntiAlias::None, "Anno", b'0'), + (TypeAntiAlias::Sharp, "AnSh", b'4'), + (TypeAntiAlias::Crisp, "AnCr", b'1'), + (TypeAntiAlias::Strong, "AnSt", b'2'), + ] { + let mut b = DocBuilder::new(100.0, 60.0); + let t = type_node(&mut b, (10.0, 30.0), "Edges", |t| t.anti_alias = aa); + b.add(t); + let doc = b.build(); + assert_eq!(engine_anti_alias(&doc, &o), (key.to_string(), number), "{aa:?}"); + let hard = RasterExportOptions { anti_alias: crate::AntiAlias::None, ..o.clone() }; + assert_eq!(engine_anti_alias(&doc, &hard), ("Anno".to_string(), b'0'), "{aa:?} exported without anti-aliasing"); + } +} + +#[test] +fn variation_selectors_and_joiners_need_no_glyph() { + let mut b = DocBuilder::new(100.0, 60.0); + // In English: USA, the default language, given by its tag. + let t = type_node(&mut b, (10.0, 30.0), "A\u{FE0F}\u{200D}B\u{E0100}", |t| t.runs[0].style.language = Some("en-US".into())); + b.add(t); + let file = export(&b.build(), &opts(PsdOptions { preserve_text: true, ..PsdOptions::default() })); + assert_eq!(parse(&file).records.iter().filter(|r| r.type_tool.is_some()).count(), 1); +} + +#[test] +fn hidden_type_left_out_keeps_its_layer_whole() { + let mut b = DocBuilder::new(100.0, 60.0); + b.rect(Rect::new(0.0, 0.0, 30.0, 30.0), Color::rgb8(255, 0, 0), |_| {}); + let t = type_node(&mut b, (20.0, 40.0), "Hidden", |_| {}); + b.add(Node { visible: false, ..t }); + b.rect(Rect::new(60.0, 10.0, 90.0, 40.0), Color::rgb8(0, 0, 255), |_| {}); + let doc = b.build(); + let with = |o: PsdOptions| export(&doc, &opts(o)); + assert_eq!(with(PsdOptions { preserve_text: true, ..PsdOptions::default() }), with(PsdOptions::default()), "one pixel layer either way"); + let shown = parse(&with(PsdOptions { preserve_text: true, hidden_layers: true, ..PsdOptions::default() })) + .records + .iter() + .filter(|r| r.type_tool.is_some() && r.hidden) + .count(); + assert_eq!(shown, 1, "with hidden layers: a hidden type layer"); +} + +#[test] +fn blending_art_keeps_its_layer_whole() { + use vectorcraft_color::BlendMode; + use vectorcraft_doc::AppearanceItem; + // The square's blend mode, on the object (`fill`: false) or on its fill. + let build = |blend: BlendMode, above: bool, fill: bool| { + let mut b = DocBuilder::new(100.0, 60.0); + let square = |b: &mut DocBuilder| { + b.rect(Rect::new(0.0, 0.0, 60.0, 40.0), Color::rgb8(255, 0, 0), |n| { + if !fill { + n.blend = blend; + } else if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.blend = blend; + } + }); + }; + if !above { + square(&mut b); + } + let t = type_node(&mut b, (10.0, 30.0), "Type", |_| {}); + b.add(t); + if above { + square(&mut b); + } + b.build() + }; + let o = opts(PsdOptions { preserve_text: true, ..PsdOptions::default() }); + for (above, fill) in [(true, false), (false, false), (true, true)] { + let normal = export(&build(BlendMode::Normal, above, fill), &o); + assert_eq!(parse(&normal).records.iter().filter(|r| r.type_tool.is_some()).count(), 1, "normal art (above: {above}): a type layer"); + let doc = build(BlendMode::Multiply, above, fill); + let file = export(&doc, &o); + assert!(parse(&file).records.iter().all(|r| r.type_tool.is_none()), "multiplied art (above: {above}, fill: {fill}): one pixel layer"); + assert_eq!(file, export(&doc, &opts(PsdOptions::default()))); + } +} + #[test] fn long_unicode_name_is_cut_on_a_character_boundary() { let mut b = DocBuilder::new(100.0, 60.0); @@ -352,3 +736,145 @@ fn long_unicode_name_is_cut_on_a_character_boundary() { let file = export(&b.build(), &opts(PsdOptions::default())); assert_eq!(parse(&file).records.last().unwrap().name, "a".repeat(254)); } + +/// `doc()` with a user slice over (20, 5)–(50, 15) and the red square made an object slice. +fn sliced() -> Document { + let mut d = doc(); + let red = d.layers[0].children().unwrap()[0].id; + let user = SliceOptions { + name: "banner".into(), + url: "https://example.com/".into(), + target: "_blank".into(), + message: "Go".into(), + alt: "Banner".into(), + background: "#123456".into(), + ..SliceOptions::default() + }; + let id = d.alloc_id(); + d.slices.push(Slice { id, rect: Rect::new(20.0, 5.0, 50.0, 15.0), options: user }); + let cell = SliceOptions { kind: SliceKind::NoImage, text: "Hi".into(), background: "matte".into(), ..SliceOptions::default() }; + d.node_mut(red).unwrap().extras_mut().slice = Some(Box::new(cell)); + d +} + +/// The slices resource of `file` as an independent reader reads it. +fn slices_of(file: &[u8]) -> Option { + let psd = craft_psd::PsdFile::from_bytes(file).expect("a PSD a reader takes"); + psd.resource(1050).map(|r| craft_psd::slices::SlicesResource::from_bytes(&r.data).expect("a slices resource a reader takes")) +} + +#[test] +fn slices_are_written_with_or_without_layers() { + let d = sliced(); + for layers in [true, false] { + let file = export(&d, &opts(PsdOptions { layers, ..PsdOptions::default() })); + let res = slices_of(&file).expect("the slices resource"); + assert_eq!((res.version, res.bounds, res.group_name.as_str()), (6, [5, 10, 40, 50], "Untitled-1")); + let s = &res.slices; + assert_eq!(s.len(), 2, "{s:?}"); + // Laid out top to bottom: the user slice, then the object slice, both written as made by + // the user. + let user = &s[0]; + assert_eq!((user.id, user.origin, user.layer_id, user.kind, user.rect), (1, 2, None, 1, [20, 5, 50, 15])); + assert_eq!( + (user.name.as_str(), user.url.as_str(), user.target.as_str(), user.message.as_str(), user.alt.as_str()), + ("banner", "https://example.com/", "_blank", "Go", "Banner") + ); + assert_eq!(user.color, [255, 0x12, 0x34, 0x56]); + let cell = &s[1]; + assert_eq!((cell.id, cell.origin, cell.kind, cell.rect), (2, 2, 0, [10, 10, 40, 40])); + assert_eq!((cell.name.as_str(), cell.cell_text.as_str(), cell.cell_text_is_html), ("", "Hi", true)); + assert_eq!((cell.color[0], cell.color[1..].iter().any(|c| *c != 0)), (0, true), "the matte"); + assert_eq!((cell.horizontal_align, cell.vertical_align), (0, 0)); + } + // A document without slices has no slices resource. + assert!(slices_of(&export(&doc(), &opts(PsdOptions::default()))).is_none()); +} + +#[test] +fn slices_are_cut_to_the_exported_region_in_its_pixels() { + let doc = sliced(); + // The right part at 2 px a point: the user slice is cut at the region's left edge, and the red + // square's slice ends at that edge. + let o = RasterExportOptions { ppi: 144.0, ..opts(PsdOptions::default()) }; + let file = Renderer::new().export_region(&doc, Rect::new(40.0, 0.0, 100.0, 60.0), RasterFormat::Psd, &o).unwrap(); + let res = slices_of(&file).unwrap(); + assert_eq!(res.slices.iter().map(|s| s.rect).collect::>(), [[0, 10, 20, 30]]); + assert_eq!(res.bounds, [10, 0, 30, 20]); + // A region no slice reaches has none. + let file = Renderer::new().export_region(&doc, Rect::new(60.0, 30.0, 100.0, 60.0), RasterFormat::Psd, &o).unwrap(); + assert!(slices_of(&file).is_none()); + // A slice thinner than a pixel keeps one pixel. + let mut thin = doc.clone(); + thin.slices[0].rect = Rect::new(20.0, 5.0, 20.2, 15.0); + let res = slices_of(&export(&thin, &opts(PsdOptions::default()))).unwrap(); + assert_eq!(res.slices[0].rect, [20, 5, 21, 15]); + // The overlap is found before the region is rounded to whole pixels: a slice inside a region + // that ends at 10.4 keeps its last pixel, and one past a region that ends at 10.6 isn't written. + let o = opts(PsdOptions::default()); + let mut edge = doc.clone(); + edge.slices[0].rect = Rect::new(10.1, 5.0, 10.3, 15.0); + edge.node_mut(edge.layers[0].children().unwrap()[0].id).unwrap().extras_mut().slice = None; + let file = Renderer::new().export_region(&edge, Rect::new(0.0, 0.0, 10.4, 60.0), RasterFormat::Psd, &o).unwrap(); + assert_eq!(slices_of(&file).unwrap().slices.iter().map(|s| s.rect).collect::>(), [[9, 5, 10, 15]]); + edge.slices[0].rect = Rect::new(10.7, 5.0, 10.9, 15.0); + let file = Renderer::new().export_region(&edge, Rect::new(0.0, 0.0, 10.6, 60.0), RasterFormat::Psd, &o).unwrap(); + assert!(slices_of(&file).is_none()); +} + +#[test] +fn an_html_text_slice_writes_one_break_for_each_line_ending() { + use vectorcraft_doc::{CharStyle, NodeKind, TextObject}; + use vectorcraft_geom::Point; + let mut d = DocBuilder::new(100.0, 60.0).build(); + let t = TextObject::point(Point::new(10.0, 30.0), "A\r\nB\rC\nD\u{2029}E", CharStyle { size: 12.0, ..CharStyle::default() }); + let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + n.extras_mut().slice = Some(Box::new(SliceOptions { kind: SliceKind::HtmlText, ..SliceOptions::default() })); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let res = slices_of(&export(&d, &opts(PsdOptions::default()))).unwrap(); + assert_eq!(res.slices[0].cell_text, "A
B
C
D
E"); +} + +#[test] +fn slice_ids_count_from_1_and_the_limits_are_errors() { + let mut doc = doc(); + for i in 0..20 { + let id = doc.alloc_id(); + let x = f64::from(i) * 5.0; + doc.slices.push(Slice { id, rect: Rect::new(x, 0.0, x + 5.0, 5.0), options: SliceOptions::default() }); + } + let res = slices_of(&export(&doc, &opts(PsdOptions::default()))).unwrap(); + let ids: Vec = res.slices.iter().map(|s| s.id).collect(); + assert_eq!(ids, (1..=20).collect::>()); + let export_err = |d: &Document| { + Renderer::new().export_region(d, d.artboards[0].rect, RasterFormat::Psd, &opts(PsdOptions::default())).err().unwrap_or_default() + }; + let mut long = doc.clone(); + long.slices[0].options.alt = "a".repeat(MAX_SLICE_TEXT + 1); + let e = export_err(&long); + assert!(e.contains("characters"), "{e}"); + let mut many = doc.clone(); + many.slices = (0..=MAX_SLICES as u64) + .map(|i| Slice { id: NodeId(1_000_000 + i), rect: Rect::new(0.0, 0.0, 5.0, 5.0), options: SliceOptions::default() }) + .collect(); + let e = export_err(&many); + assert!(e.contains("slices"), "{e}"); + // Not clipped to the artboard, a slice keeps bounds that aren't finite. + let mut bad = doc; + bad.slices_clip_to_artboard = false; + bad.slices[0].rect = Rect::new(f64::NAN, 0.0, 5.0, 5.0); + let e = export_err(&bad); + assert!(e.contains("finite"), "{e}"); +} + +#[test] +fn slices_past_4_gb_are_an_error_before_they_are_written() { + let max = u32::MAX as usize; + assert_eq!(room(0, MAX_SLICE_TEXT), Ok(())); + assert_eq!(room(max - 4 - 2 * 10, 10), Ok(())); + let e = room(max - 4 - 2 * 10, 11).err().unwrap_or_default(); + assert!(e.contains("4 GB"), "{e}"); + assert!(room(max, 0).is_err()); + assert!(room(0, usize::MAX).is_err()); +} 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 c70eacd2fc..392e4ed6d2 100644 --- a/crates/render/src/encode/tests_tiff.rs +++ b/crates/render/src/encode/tests_tiff.rs @@ -1,22 +1,25 @@ //! TIFF export: byte order, LZW, colour models and samples, resolution, profile, strips. -use std::io::Cursor; - -use tiff::decoder::{Decoder, DecodingResult}; -use tiff::tags::Tag; +use craft_tiff::Tiff; +use craft_tiff::tags; use super::jpeg::ColorModel; use super::tiff::{self as t, ByteOrder, Compression, Image, Layout, Photometric, TiffOptions}; -fn decoder(file: &[u8]) -> Decoder> { - Decoder::new(Cursor::new(file)).expect("a TIFF") +fn ifd0(file: &[u8]) -> craft_tiff::Ifd { + Tiff::parse(file).expect("a TIFF").ifds.into_iter().next().expect("IFD0") +} + +fn tag_u16_vec(ifd: &craft_tiff::Ifd, tag: u16) -> Option> { + ifd.value(tag).map(|v| v.to_u64_vec().into_iter().map(|x| x as u16).collect()) +} + +fn tag_u32_vec(ifd: &craft_tiff::Ifd, tag: u16) -> Option> { + ifd.value(tag).map(|v| v.to_u64_vec().into_iter().map(|x| x as u32).collect()) } fn pixels(file: &[u8]) -> Vec { - match decoder(file).read_image().expect("decodes") { - DecodingResult::U8(v) => v, - _ => panic!("8-bit samples"), - } + craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, file).expect("decodes").into_data() } /// Straight RGBA: flat areas (as art is) with a transparent corner when `clear`. @@ -46,7 +49,7 @@ fn byte_order_writes_an_ii_or_mm_header() { assert_eq!(&file[..4], magic); let rgb: Vec = px.chunks(4).flat_map(|p| &p[..3]).copied().collect(); assert_eq!(pixels(&file), rgb, "{order:?}"); - assert_eq!(decoder(&file).get_tag_ascii_string(Tag::Software).unwrap(), "VectorCraft"); + assert_eq!(ifd0(&file).string(tags::SOFTWARE).as_deref(), Some("VectorCraft")); } for (s, o) in [("little", ByteOrder::Little), ("MM", ByteOrder::Big), ("mac", ByteOrder::Big), ("ii", ByteOrder::Little), ("big", ByteOrder::Big)] { @@ -61,44 +64,51 @@ fn lzw_is_smaller_and_decodes_the_same() { let plain = t::encode_samples(&px, 120, 90, 72.0, &TiffOptions { lzw: false, ..opts(ColorModel::Rgb) }).unwrap(); let lzw = t::encode_samples(&px, 120, 90, 72.0, &opts(ColorModel::Rgb)).unwrap(); assert!(lzw.len() * 4 < plain.len(), "{} vs {}", lzw.len(), plain.len()); - assert_eq!(decoder(&lzw).get_tag_unsigned::(Tag::Compression).unwrap(), 5); - assert_eq!(decoder(&plain).get_tag_unsigned::(Tag::Compression).unwrap(), 1); + assert_eq!(ifd0(&lzw).u16(tags::COMPRESSION), Some(5)); + assert_eq!(ifd0(&plain).u16(tags::COMPRESSION), Some(1)); assert_eq!(pixels(&lzw), px, "transparency kept as an alpha channel"); assert_eq!(pixels(&plain), px); - // The image crate reads it too. - let img = image::load_from_memory_with_format(&lzw, image::ImageFormat::Tiff).unwrap().to_rgba8(); - assert_eq!(img.into_raw(), px); + let img = craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, &lzw).unwrap(); + assert_eq!(img.data(), px); } #[test] fn colour_models_write_their_samples() { let px = art(9, 6, true); let rgba = t::encode_samples(&px, 9, 6, 72.0, &opts(ColorModel::Rgb)).unwrap(); - assert_eq!(decoder(&rgba).colortype().unwrap(), tiff::ColorType::RGBA(8)); - assert_eq!(decoder(&rgba).get_tag_u16_vec(Tag::ExtraSamples).unwrap(), [2], "unassociated alpha"); + let rgba_ifd = ifd0(&rgba); + assert_eq!(rgba_ifd.u16(tags::PHOTOMETRIC), Some(2)); + assert_eq!(rgba_ifd.u16(tags::SAMPLES_PER_PIXEL), Some(4)); + assert_eq!(tag_u16_vec(&rgba_ifd, tags::BITS_PER_SAMPLE).as_deref(), Some([8, 8, 8, 8].as_slice())); + assert_eq!(tag_u16_vec(&rgba_ifd, tags::EXTRA_SAMPLES).as_deref(), Some([2].as_slice()), "unassociated alpha"); let opaque = art(9, 6, false); let rgb = t::encode_samples(&opaque, 9, 6, 72.0, &opts(ColorModel::Rgb)).unwrap(); - assert_eq!(decoder(&rgb).colortype().unwrap(), tiff::ColorType::RGB(8)); - assert!(decoder(&rgb).find_tag(Tag::ExtraSamples).unwrap().is_none()); + let rgb_ifd = ifd0(&rgb); + assert_eq!(rgb_ifd.u16(tags::PHOTOMETRIC), Some(2)); + assert_eq!(rgb_ifd.u16(tags::SAMPLES_PER_PIXEL), Some(3)); + assert!(rgb_ifd.value(tags::EXTRA_SAMPLES).is_none()); let gray = t::encode_samples(&opaque, 9, 6, 72.0, &opts(ColorModel::Gray)).unwrap(); - assert_eq!(decoder(&gray).colortype().unwrap(), tiff::ColorType::Gray(8)); - assert_eq!(decoder(&gray).get_tag_unsigned::(Tag::PhotometricInterpretation).unwrap(), 1, "black is zero"); + let gray_ifd = ifd0(&gray); + assert_eq!(gray_ifd.u16(tags::SAMPLES_PER_PIXEL), Some(1)); + assert_eq!(tag_u16_vec(&gray_ifd, tags::BITS_PER_SAMPLE).as_deref(), Some([8].as_slice())); + assert_eq!(gray_ifd.u16(tags::PHOTOMETRIC), Some(1), "black is zero"); let g = pixels(&gray); assert_eq!((g[0], g[8]), (super::jpeg::to_gray()([200, 30, 40]), 255), "lightness; white stays white"); let on_white = t::encode_samples(&px, 9, 6, 72.0, &opts(ColorModel::Gray)).unwrap(); - assert_eq!(decoder(&on_white).colortype().unwrap(), tiff::ColorType::Gray(8), "grey has no alpha: few readers take it"); + let on_white_ifd = ifd0(&on_white); + assert_eq!(on_white_ifd.u16(tags::SAMPLES_PER_PIXEL), Some(1), "grey has no alpha: few readers take it"); assert_eq!(pixels(&on_white)[0], 255, "the transparent corner is white"); // CMYK: four samples a pixel, ink amounts as given. let inks: Vec = (0..9 * 6 * 4).map(|i| (i * 7 % 256) as u8).collect(); let cmyk = t::encode_samples(&inks, 9, 6, 72.0, &opts(ColorModel::Cmyk)).unwrap(); - let mut d = decoder(&cmyk); - assert_eq!(d.colortype().unwrap(), tiff::ColorType::CMYK(8)); - assert_eq!(d.get_tag_unsigned::(Tag::SamplesPerPixel).unwrap(), 4); - assert_eq!(d.get_tag_unsigned::(Tag::PhotometricInterpretation).unwrap(), 5, "separated"); - assert_eq!(d.get_tag_unsigned::(Tag::Unknown(332)).unwrap(), 1, "CMYK inks"); - assert_eq!(pixels(&cmyk), inks); + let d = ifd0(&cmyk); + assert_eq!(d.u16(tags::SAMPLES_PER_PIXEL), Some(4)); + assert_eq!(d.u16(tags::PHOTOMETRIC), Some(5), "separated"); + assert_eq!(d.u16(332), Some(1), "CMYK inks"); + let cmyk_img = craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, &cmyk).unwrap(); + assert_eq!(cmyk_img.data(), inks); } #[test] @@ -106,16 +116,18 @@ fn resolution_tags_and_the_profile() { let px = art(4, 4, false); for (ppi, rational) in [(300.0, (300, 1)), (72.5, (7250, 100))] { let file = t::encode_samples(&px, 4, 4, ppi, &opts(ColorModel::Rgb)).unwrap(); - let mut d = decoder(&file); - for tag in [Tag::XResolution, Tag::YResolution] { - assert_eq!(d.get_tag(tag).unwrap(), tiff::decoder::ifd::Value::Rational(rational.0, rational.1)); + let d = ifd0(&file); + for tag in [tags::X_RESOLUTION, tags::Y_RESOLUTION] { + let Some(craft_tiff::Value::Rational(v)) = d.value(tag) else { panic!("rational") }; + assert_eq!(v.as_slice(), &[rational]); } - assert_eq!(d.get_tag_unsigned::(Tag::ResolutionUnit).unwrap(), 2, "inches"); + assert_eq!(d.u16(tags::RESOLUTION_UNIT), Some(2), "inches"); } for model in ColorModel::ALL { let src = if model == ColorModel::Cmyk { vec![0; 64] } else { px.clone() }; let file = t::encode_samples(&src, 4, 4, 72.0, &TiffOptions { embed_icc: true, ..opts(model) }).unwrap(); - let icc = decoder(&file).get_tag_u8_vec(Tag::IccProfile).unwrap(); + let ifd = ifd0(&file); + let icc = ifd.bytes(tags::ICC_PROFILE).unwrap(); assert_eq!(&icc[36..40], b"acsp", "{model:?}: an ICC profile"); let space: &[u8; 4] = match model { ColorModel::Rgb => b"RGB ", @@ -125,7 +137,7 @@ fn resolution_tags_and_the_profile() { assert_eq!(&icc[16..20], space, "{model:?}"); } let file = t::encode_samples(&px, 4, 4, 72.0, &opts(ColorModel::Rgb)).unwrap(); - assert!(decoder(&file).find_tag(Tag::IccProfile).unwrap().is_none()); + assert!(ifd0(&file).value(tags::ICC_PROFILE).is_none()); } #[test] @@ -135,10 +147,10 @@ fn big_images_take_several_strips_in_either_order() { for order in ByteOrder::ALL { for lzw in [false, true] { let file = t::encode_samples(&px, w, h, 72.0, &TiffOptions { lzw, byte_order: order, ..opts(ColorModel::Gray) }).unwrap(); - let mut d = decoder(&file); - let offsets = d.get_tag_u32_vec(Tag::StripOffsets).unwrap(); + let d = ifd0(&file); + let offsets = tag_u32_vec(&d, tags::STRIP_OFFSETS).unwrap(); // 300 bytes a row: 27 rows a strip. - assert_eq!(d.get_tag_u32(Tag::RowsPerStrip).unwrap(), 27); + assert_eq!(d.u32(tags::ROWS_PER_STRIP), Some(27)); assert_eq!(offsets.len(), 4); assert!(offsets.iter().all(|o| o % 2 == 0), "strips start on a word"); assert_eq!(pixels(&file).len(), (w * h) as usize, "{order:?} lzw {lzw}"); @@ -152,11 +164,19 @@ fn packbits_and_bilevel_images_decode() { let rows = [0b1010_1010u8, 0b1100_0000, 0xFF, 0xC0, 0, 0]; let image = Image { width: 10, height: 3, data: &rows, photometric: Photometric::WhiteIsZero, samples: 1, bits: 1, alpha: false }; let file = t::write(&image, &Layout { byte_order: ByteOrder::Big, compression: Compression::PackBits, ppi: 72.0, icc: None }).unwrap(); - let mut d = decoder(&file); - assert_eq!(d.colortype().unwrap(), tiff::ColorType::Gray(1)); - assert_eq!(d.get_tag_unsigned::(Tag::Compression).unwrap(), 32773); + let d = ifd0(&file); + assert_eq!(d.u16(tags::SAMPLES_PER_PIXEL), Some(1)); + assert_eq!(tag_u16_vec(&d, tags::BITS_PER_SAMPLE).as_deref(), Some([1].as_slice())); + assert_eq!(d.u16(tags::COMPRESSION), Some(32773)); // The decoder turns WhiteIsZero into black-is-zero. - assert_eq!(pixels(&file), rows.map(|b| !b)); + let dec = craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, &file).unwrap(); + assert_eq!(dec.width(), 10); + assert_eq!(dec.height(), 3); + assert_eq!( + dec.data(), + [0, 255, 0, 255, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + "WhiteIsZero samples are inverted and row padding is ignored" + ); // A buffer that doesn't match the size is refused, not written. let short = Image { data: &rows[..5], ..image }; assert!(t::write(&short, &Layout { byte_order: ByteOrder::Little, compression: Compression::None, ppi: 72.0, icc: None }).is_err()); @@ -182,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/fx/bounds.rs b/crates/render/src/fx/bounds.rs index e6400c90af..aefe50a947 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -96,8 +96,9 @@ pub(crate) fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { return art.visual_bounds_with(symbols).map(|r| with_raster_reach(symbols, n, r)); } // Copies that each carry the raster effects listed before their Transform effect reach as far - // as each copy's raster effects paint, and the raster effects after it spread them all. - if effects::outer_effects(n).len() < n.appearance.effects.len() + // as each copy's raster effects paint, and the raster effects after it spread them all, + // as do copies whose fills and strokes each carry their own raster effects. + if (effects::outer_effects(n).len() < n.appearance.effects.len() || effects::has_copied_row_raster(n)) && let Some(art) = effects::reshape(Some(symbols.document()), n, None) { return cull_bounds(symbols, &art); @@ -688,6 +689,16 @@ fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool, brush: b _ => None, }; let reshaped = effects::reshape(Some(symbols.document()), n, symbol.as_ref()); + // Copies that each carry the raster effects listed before their Transform effect reach + // as far as each copy's raster effects paint, and the raster effects after it spread + // them all: the art and each copy in it are groups with those raster effects, measured + // with their reach ([`effects::has_container_appearance`]). + if effects::outer_effects(n).len() < n.appearance.effects.len() + && let Some(r) = &reshaped + { + let a = live_content_reach(symbols, n); + return cull_bounds_in(symbols, r, after_reshape, false).map(|b| b.inflate(a, a)); + } let b = match &reshaped { Some(r) if has_instance_row_effects(n) => instance_piece_bounds(symbols, r), Some(r) if matches!(n.kind, NodeKind::Text(_)) || (matches!(n.kind, NodeKind::Image(_)) && !r.clips()) => { diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index 50d0245c12..3bbd803cc2 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -337,6 +337,38 @@ fn a_transform_after_a_drop_shadow_scales_the_shadow_with_the_art() { } } +/// A Transform effect listed after a Bas Relief turns its light with the art: a group of a black +/// square centered on a white one, lit from the top and turned 90° counterclockwise about its +/// center, draws as the group lit from the left. +#[test] +fn a_transform_after_bas_relief_turns_its_light_with_the_art() { + let relieved = |effects: Vec<(&str, serde_json::Value)>| { + let mut d = Document::new(100.0, 100.0); + let mut square = + |r: Rect, c: Color| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::basic(Paint::solid(c), Paint::None, 0.0))); + let members = vec![square(Rect::new(20.0, 20.0, 80.0, 80.0), Color::WHITE), square(Rect::new(40.0, 40.0, 60.0, 60.0), Color::BLACK)]; + let mut g = Node::group(d.alloc_id(), members); + g.appearance.effects = effects.into_iter().map(|(id, p)| Effect { id: id.into(), params: p, visible: true }).collect(); + let l = d.layers[0].id; + d.insert(Some(l), 0, g).unwrap(); + render(&d) + }; + let relief = |light: &str| ("sketch.basRelief", json!({"lightDirection": light})); + let turned = relieved(vec![relief("top"), ("distort.transform", json!({"rotate": 90}))]); + let left = relieved(vec![relief("left")]); + let top = relieved(vec![relief("top")]); + // The largest difference of a channel between two images. + let diff = |a: &Rendered, b: &Rendered| { + (0..100u32) + .flat_map(|y| (0..100u32).map(move |x| (x, y))) + .map(|(x, y)| a.pixel(x, y).iter().zip(b.pixel(x, y)).map(|(p, q)| p.abs_diff(q)).max().unwrap_or(0)) + .max() + .unwrap_or(0) + }; + assert!(diff(&left, &top) > 50, "the light's direction shows: {}", diff(&left, &top)); + assert!(diff(&turned, &left) <= 2, "turned top light draws as a left light: {}", diff(&turned, &left)); +} + /// An object's or a group's Transform effect transforms the raster effects of what it holds with /// the art: halving a 40 pt square about its center halves the 10 pt offset of its fill's shadow, /// and of a group member's own shadow, with Scale Strokes & Effects off or on. 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 c130fbe346..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,36 +282,40 @@ 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 is read a row at a time when the reader's buffers fit the allowance. - let row_scratch = if format == image::ImageFormat::Png { - png_reader(bytes).filter(|r| !r.info().interlaced).and_then(|r| png_row_scratch(&r)).filter(|&s| s <= 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 == 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, 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 +/// allowance even when RGBA16's declared samples exceed the shared whole-image default budget. +/// Row scratch and the reduced pixmap are admitted separately before decoding starts. +fn png_streaming_limits(source_pixels: u64) -> craft_image_codecs::Limits { + craft_image_codecs::Limits { max_width: u32::MAX, max_height: u32::MAX, max_pixels: source_pixels, max_alloc: source_pixels.saturating_mul(8) } } /// How many rows of an image decoded whole [`reduced_pixmap`] converts to RGBA at a time. @@ -283,17 +329,58 @@ const PNG_KEPT_ROWS: u64 = 128 << 10; /// stream buffer grows by. const PNG_WINDOW_AND_STEP: u64 = (32 << 10) + (8 << 10); -/// The most memory `r` takes in its buffers to read its image a row at a time: the stream buffer -/// holds the rows already read up to [`PNG_KEPT_ROWS`] or four rows, whichever is more, the previous -/// and current rows, and [`PNG_WINDOW_AND_STEP`]. The buffer grows by doubling its reservation, -/// and while it grows its old reservation and the new one, up to twice the size it holds, are both -/// allocated: three times that size at most. A copy of a stored row and the row given out come on -/// top. `None` when a row given out doesn't fit memory. -fn png_row_scratch(r: &png::Reader>) -> Option { - let info = r.info(); - // A filter byte and the row's samples, in whole bytes. - let stored = 1 + (u64::from(info.width) * info.color_type.samples() as u64 * info.bit_depth as u64).div_ceil(8); - let out = u64::try_from(r.output_line_size(info.width)?).ok()?; +/// The most memory `craft-image-codecs`'s PNG row decoder takes in its buffers to read its image +/// a row at a time: the stream buffer holds the rows already read up to [`PNG_KEPT_ROWS`] or four +/// rows, whichever is more, the previous and current rows, and [`PNG_WINDOW_AND_STEP`]. The buffer +/// grows by doubling its reservation, and while it grows its old reservation and the new one, up +/// to twice the size it holds, are both allocated: three times that size at most. A copy of a +/// stored row and the row given out come on top. `None` when a row given out doesn't fit memory. +fn png_row_scratch(hdr: &craft_image_codecs::PngHeader) -> Option { + let out = u64::from(hdr.width).checked_mul(hdr.layout.channels() as u64)?.checked_mul(hdr.sample.bytes() as u64)?; + png_row_scratch_for_row(out) +} + +/// The row decoder rejects a truncated PNG's tiny IDAT before it can report its header. For a +/// size estimate, the image decoder still gives us the declared output bytes; use those only when +/// the PNG header says it is a static, non-interlaced image, the format the renderer can stream. +fn png_row_scratch_from_header(bytes: &[u8], width: u32, height: u32, total_bytes: u64) -> Option { + const SIG: &[u8; 8] = b"\x89PNG\r\n\x1a\n"; + if bytes.get(..8)? != SIG || height == 0 || !total_bytes.is_multiple_of(u64::from(height)) { + return None; + } + let mut at = 8usize; + let mut header = false; + loop { + let len = u32::from_be_bytes(bytes.get(at..at + 4)?.try_into().ok()?) as usize; + let kind = bytes.get(at + 4..at + 8)?; + let data_at = at.checked_add(8)?; + let end = data_at.checked_add(len)?; + let data = bytes.get(data_at..end)?; + match kind { + b"IHDR" if len == 13 && !header => { + header = true; + if at != 8 + || u32::from_be_bytes(data[..4].try_into().ok()?) != width + || u32::from_be_bytes(data[4..8].try_into().ok()?) != height + || data[12] != 0 + { + return None; + } + } + b"acTL" | b"eXIf" => return None, + b"IDAT" if header => { + let row = total_bytes / u64::from(height); + return row.checked_add(1).and_then(png_row_scratch_for_row); + } + _ => {} + } + at = end.checked_add(4)?; // CRC + } +} + +fn png_row_scratch_for_row(out: u64) -> Option { + // A filter byte and the row's samples. + let stored = 1u64.checked_add(out)?; let kept = (stored * 4).next_multiple_of(64).max(PNG_KEPT_ROWS); let stream = kept + stored * 2 + PNG_WINDOW_AND_STEP; Some(stream * 3 + stored + out) @@ -313,14 +400,6 @@ fn fitted_dims(w: u32, h: u32, allowance: u64) -> Option<(u32, u32)> { (u64::from(nw) * u64::from(nh) * 4 <= allowance).then_some((nw, nh)) } -/// A PNG reader of `bytes` that gives 8-bit gray, gray with alpha, RGB or RGBA rows, with its -/// header and the chunks before the pixels read. -fn png_reader(bytes: &[u8]) -> Option>> { - let mut d = png::Decoder::new(std::io::Cursor::new(bytes)); - d.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16); - d.read_info().ok() -} - /// `bytes` decoded at the size [`reduction`] gives. Each pixel of the result is the mean of the /// image's pixels it covers. [`Undecoded::Unreadable`] when they can't be read, and /// [`Undecoded::NoRoom`] when the result and what reading takes ([`Reduction::scratch`]) don't fit @@ -335,26 +414,67 @@ fn reduced_pixmap(bytes: &[u8], r: &Reduction) -> Result Option { + shrunk_with_png_limits(bytes, r, &png_streaming_limits(allowance())) +} + +fn shrunk_with_png_limits(bytes: &[u8], r: &Reduction, png_limits: &craft_image_codecs::Limits) -> Option { let mut shrink = Shrink::new(r.size, r.to); if r.rows { - let mut reader = png_reader(bytes)?; - let (color, _) = reader.output_color_type(); - while let Some(row) = reader.next_row().ok()? { - let data = row.data(); - match color { - png::ColorType::Grayscale => shrink.row(data.iter().map(|&g| [g, g, g, 255])), - png::ColorType::GrayscaleAlpha => shrink.row(data.as_chunks::<2>().0.iter().map(|&[g, a]| [g, g, g, a])), - png::ColorType::Rgb => shrink.row(data.as_chunks::<3>().0.iter().map(|&[r, g, b]| [r, g, b, 255])), - png::ColorType::Rgba => shrink.row(data.as_chunks::<4>().0.iter().copied()), - png::ColorType::Indexed => return None, - } + use craft_image_codecs::{ChannelLayout, CodecError, Format, PngDecodeRows, SampleType}; + let mut dec = PngDecodeRows::new_streaming(bytes, png_limits).ok()?; + if !dec.streamable() { + return None; + } + let hdr = dec.header(); + // Yield after each row and stop once all pixels have arrived. The pinned decoder's + // first tail batch only locates a text chunk; later batches inflate/retain its value. + // Never run those batches: the renderer needs pixels, not ancillary text. Its underlying + // PNG reader also ignores text chunks before IDAT, so neither location retains text. + for _ in 0..hdr.height { + let _extras = dec + .step_stream::(1, &mut || false, &mut |_y, row| { + match (hdr.layout, hdr.sample) { + (ChannelLayout::Gray, SampleType::U8) => shrink.row(row.iter().map(|&g| [g, g, g, 255])), + (ChannelLayout::GrayA, SampleType::U8) => shrink.row(row.as_chunks::<2>().0.iter().map(|&[g, a]| [g, g, g, a])), + (ChannelLayout::Rgb, SampleType::U8) => shrink.row(row.as_chunks::<3>().0.iter().map(|&[r, g, b]| [r, g, b, 255])), + (ChannelLayout::Rgba, SampleType::U8) => shrink.row(row.as_chunks::<4>().0.iter().copied()), + (ChannelLayout::Gray, SampleType::U16) => shrink.row(row.as_chunks::<2>().0.iter().map(|&g| { + let v = (u16::from_ne_bytes(g) >> 8) as u8; + [v, v, v, 255] + })), + (ChannelLayout::GrayA, SampleType::U16) => shrink.row(row.as_chunks::<4>().0.iter().map(|&[g0, g1, a0, a1]| { + let g = (u16::from_ne_bytes([g0, g1]) >> 8) as u8; + let a = (u16::from_ne_bytes([a0, a1]) >> 8) as u8; + [g, g, g, a] + })), + (ChannelLayout::Rgb, SampleType::U16) => shrink.row(row.as_chunks::<6>().0.iter().map(|&[r0, r1, g0, g1, b0, b1]| { + [ + (u16::from_ne_bytes([r0, r1]) >> 8) as u8, + (u16::from_ne_bytes([g0, g1]) >> 8) as u8, + (u16::from_ne_bytes([b0, b1]) >> 8) as u8, + 255, + ] + })), + (ChannelLayout::Rgba, SampleType::U16) => { + shrink.row(row.as_chunks::<8>().0.iter().map(|&[r0, r1, g0, g1, b0, b1, a0, a1]| { + [ + (u16::from_ne_bytes([r0, r1]) >> 8) as u8, + (u16::from_ne_bytes([g0, g1]) >> 8) as u8, + (u16::from_ne_bytes([b0, b1]) >> 8) as u8, + (u16::from_ne_bytes([a0, a1]) >> 8) as u8, + ] + })) + } + _ => { + return Err(CodecError::Unsupported { format: Format::Png, reason: "unsupported PNG channel layout".into() }); + } + } + Ok(()) + }) + .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(); @@ -474,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)), } } @@ -589,6 +709,130 @@ mod tests { assert_eq!(room_for(MAX_DECODE_ALLOC, MAX_DECODE_ALLOC), Ok(())); } + #[test] + fn streaming_header_accepts_rgba16_above_whole_image_default() { + // Header-only fixture: opening the stream checks declared size without allocating or + // decoding the 1.2 GB canvas. Padding meets the decoder's compressed-size plausibility + // bound; no rows are requested from this deliberately incomplete image. + let (w, h) = (10_000u32, 15_000u32); + let mut bytes = b"\x89PNG\r\n\x1a\n".to_vec(); + let ihdr = [&b"IHDR"[..], &w.to_be_bytes(), &h.to_be_bytes(), &[16, 6, 0, 0, 0]].concat(); + let mut idat = b"IDAT\x78\x9c".to_vec(); + idat.resize(1_200_000, 0); + for chunk in [&ihdr[..], &idat, b"IEND"] { + bytes.extend((chunk.len() as u32 - 4).to_be_bytes()); + bytes.extend(chunk); + let mut crc = flate2::Crc::new(); + crc.update(chunk); + bytes.extend(crc.sum().to_be_bytes()); + } + let default = craft_image_codecs::Limits { max_alloc: 1 << 30, max_pixels: 150_000_000, ..Default::default() }; + assert!(craft_image_codecs::PngDecodeRows::new_streaming(&bytes, &default).is_err()); + let rows = craft_image_codecs::PngDecodeRows::new_streaming(&bytes, &png_streaming_limits(150_000_000)).unwrap(); + assert_eq!((rows.header().width, rows.header().height), (w, h)); + assert!(rows.streamable()); + assert!(craft_image_codecs::PngDecodeRows::new_streaming(&bytes, &png_streaming_limits(149_999_999)).is_err()); + } + + #[test] + fn streaming_reduction_does_not_retain_text_after_pixels() { + let mut bytes = Vec::new(); + striped(8).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let mut chunk = b"tEXtComment\0".to_vec(); + chunk.extend(std::iter::repeat_n(b'x', 1 << 20)); + // PNG's IEEE CRC over type and payload, kept local to this fixture. + let mut crc = u32::MAX; + for &byte in &chunk { + crc ^= u32::from(byte); + for _ in 0..8 { + crc = (crc >> 1) ^ (0xedb88320 & 0u32.wrapping_sub(crc & 1)); + } + } + let mut tail = ((chunk.len() - 4) as u32).to_be_bytes().to_vec(); + tail.extend(chunk); + tail.extend((!crc).to_be_bytes()); + bytes.splice(bytes.len() - 12..bytes.len() - 12, tail); + let limits = craft_image_codecs::Limits { max_alloc: 1 << 19, ..Default::default() }; + let mut full = craft_image_codecs::PngDecodeRows::new_streaming(&bytes, &limits).unwrap(); + assert!(full.step_stream::(1, &mut || true, &mut |_, _| Ok(())).is_err()); + // The renderer stops after the pixels instead of retaining ancillary text. + let reduced = shrunk_with_png_limits(&bytes, &Reduction { size: (8, 1), to: (4, 1), rows: true, scratch: 0 }, &limits).unwrap(); + assert_eq!((reduced.width(), reduced.height()), (4, 1)); + 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/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index 37f3fbf4f7..8e18b3a045 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -653,7 +653,20 @@ impl Renderer { if view.shows_outlines() { let opts = RenderOptions { outline: true, ..f.opts.clone() }; let frame = Frame { opts: &opts, ..*f }; - for c in shapes { + // An Abutting trace's seam fills hold no traced outline: a clip group of paths that are + // each stroked without a fill or (on a stretched image, the strokes' outlines) filled + // without a stroke, named "Seam Fills" or, renamed, still the lowest shape, where the + // trace puts it. + let seam_fills = |i: usize, c: &Arc| { + let one_paint = |m: &Arc| { + matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) + && m.appearance.fill_paint().is_none() != m.appearance.stroke_paint().is_none() + }; + (i == 0 || c.name.as_deref() == Some("Seam Fills")) + && matches!(&c.kind, NodeKind::Group { clip: true, children } + if children.split_first().is_some_and(|(_, members)| !members.is_empty() && members.iter().all(one_paint))) + }; + for (_, c) in shapes.iter().enumerate().filter(|(i, c)| !seam_fills(*i, c)) { self.draw_outline_member(ctx, &frame, c); } } diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 99fa434ca3..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 @@ -1883,14 +1885,14 @@ fn a_png_past_the_allowance_draws_at_reduced_size() { assert_eq!((pm.width(), pm.height(), [c.r, c.g, c.b, c.a]), (300, 300, [200, 40, 40, 255])); // A row is read only while the reader's buffers fit the allowance, counting the stream buffer // three times for the moment it grows. Below 4,096 columns of 16-bit RGBA they take 516,103 - // bytes and 60 a column: 1,398 columns take 599,983 bytes, within 600,000, and 1,399 columns - // take 600,043 and are not decoded (their samples, 8 bytes a pixel, are past it too). + // bytes plus 64 bytes a column: 1,310 columns take 599,943 bytes, within 600,000, and 1,311 + // columns take 600,007 and are not decoded (their samples, 8 bytes a pixel, are past it too). let wide = |w: u32| { let img = image::ImageBuffer::, _>::from_pixel(w, 60, image::Rgba([51400, 10280, 10280, 65535])); encoded(image::DynamicImage::ImageRgba16(img), image::ImageFormat::Png) }; - assert_eq!(with_allowance(600_000, || paint::reduced_size(&wide(1398))), Some((1398, 60))); - assert_eq!(with_allowance(600_000, || paint::reduced_size(&wide(1399))), None); + assert_eq!(with_allowance(600_000, || paint::reduced_size(&wide(1310))), Some((1310, 60))); + assert_eq!(with_allowance(600_000, || paint::reduced_size(&wide(1311))), None); // An image of more pixels than the allowance has bytes is not read: 1,000 × 400 8-bit gray // pixels are drawn at 500 × 200 within 400,000 bytes, and 1,000 × 401 are not. let gray = |h: u32| encoded(image::DynamicImage::ImageLuma8(image::GrayImage::from_pixel(1000, h, image::Luma([90]))), image::ImageFormat::Png); @@ -1938,13 +1940,13 @@ fn a_reduced_decode_counts_what_reading_takes_beside_the_images_paints_hold() { // Decoded whole: 14,400 bytes of RGB and a 16-row band of 8,960 bytes, beside a 73 × 54 result // of 15,768 bytes. let jpeg = encoded(image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(80, 60, image::Rgb([30, 120, 200]))), image::ImageFormat::Jpeg); - // Read a row at a time: 540,103 bytes in the reader's buffers for 400 columns of 16-bit RGBA, + // Read a row at a time: 541,703 bytes in the reader's buffers for 400 columns of 16-bit RGBA, // beside a 387 × 387 result of 599,076 bytes. let png = encoded( image::DynamicImage::ImageRgba16(image::ImageBuffer::from_pixel(400, 400, image::Rgba([51400, 10280, 10280, 65535]))), image::ImageFormat::Png, ); - for (bytes, allowance, room, size) in [(&jpeg, 16_000, 15_768 + 14_400 + 8_960, (73, 54)), (&png, 600_000, 599_076 + 540_103, (387, 387))] { + for (bytes, allowance, room, size) in [(&jpeg, 16_000, 15_768 + 14_400 + 8_960, (73, 54)), (&png, 600_000, 599_076 + 541_703, (387, 387))] { let failed = decode_failures(); let none = with_allowance(allowance, || with_room(room - 1, || paint::decode_pixmap_or_why(bytes))); assert_eq!(none.err(), Some(paint::Undecoded::NoRoom), "not decoded with a byte too few, and tried again later"); 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 f93124e1b9..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)); @@ -1242,3 +1310,84 @@ fn each_copy_of_a_transform_effect_draws_its_own_shadow() { let b = crate::fx::visual_bounds(&d.symbol_boxes(), n).unwrap(); assert!(b.x1 >= 80.0 - 1e-9, "{b:?}"); } + +/// Each copy of a fill's own Transform effect, and each copy of its object's Transform effect, +/// draws the fill's drop shadow under itself, scaled with it: as for the object's own shadow +/// above, the copy's green shadow is 40 pt to its right. A 4 pt stroke's own Transform effect +/// gives each copy the shadow of its stroke: the copy's right edge (38..42 across) casts it at +/// 78..82. The bounds reach as far as the copy's shadow. +#[test] +fn each_copy_of_a_fills_or_strokes_transform_draws_its_own_shadow() { + let shadow = || fx("stylize.dropShadow", json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"})); + let copies = || fx("distort.transform", json!({"scaleH": 200, "scaleV": 200, "moveV": 60, "copies": 1})); + let square = |item: AppearanceItem| { + Node::path(NodeId(0), shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), Appearance { items: vec![item], ..Default::default() }) + }; + let mut red = FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0))); + red.effects = vec![shadow(), copies()]; + let own = square(AppearanceItem::Fill(red.clone())); + red.effects = vec![shadow()]; + let mut owner = square(AppearanceItem::Fill(red)); + owner.appearance.effects = vec![copies()]; + for (what, n) in [("own", own), ("object's", owner)] { + let d = doc_with(Document::new(100.0, 100.0), n); + let img = render(&d); + assert_eq!(img.pixel(20, 20), [255, 0, 0, 255], "{what}: the square"); + assert_eq!(img.pixel(45, 20), [0, 255, 0, 255], "{what}: the square's shadow"); + assert_eq!(img.pixel(20, 80), [255, 0, 0, 255], "{what}: the copy"); + assert_eq!(img.pixel(70, 80), [0, 255, 0, 255], "{what}: the copy's shadow, 40 pt to its right"); + assert_eq!(img.pixel(85, 80), [255, 255, 255, 255], "{what}: past the copy's shadow"); + let n = &d.layers[0].children().unwrap()[0]; + let b = crate::fx::visual_bounds(&d.symbol_boxes(), n).unwrap(); + assert!(b.x1 >= 80.0 - 1e-9, "{what}: {b:?}"); + } + let mut blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0); + blue.effects = vec![shadow(), copies()]; + let d = doc_with(Document::new(100.0, 100.0), square(AppearanceItem::Stroke(blue))); + let img = render(&d); + assert_eq!(img.pixel(50, 20), [0, 255, 0, 255], "the square's stroke shadow"); + assert_eq!(img.pixel(80, 80), [0, 255, 0, 255], "the copy's stroke shadow, 40 pt to the right of its edge"); + assert_eq!(img.pixel(60, 80), [255, 255, 255, 255], "inside the copy's stroke shadow"); +} + +/// Each copy of an image's Transform effect draws the drop shadow listed before the effect under +/// itself, scaled with it: the red image (20..50) has its green shadow 10 pt to its right, and its +/// copy scaled 50 % and moved 40 pt down (27.5..42.5 across, 67.5..82.5 down) has its own 5 pt to +/// its right. +#[test] +fn each_copy_of_an_images_transform_effect_draws_its_own_shadow() { + let shadow = fx("stylize.dropShadow", json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"})); + let copies = fx("distort.transform", json!({"scaleH": 50, "scaleV": 50, "moveV": 40, "copies": 1})); + let img = render(&image_doc(vec![shadow, copies])); + assert_eq!(img.pixel(35, 35), [255, 0, 0, 255], "the image"); + assert_eq!(img.pixel(55, 35), [0, 255, 0, 255], "the image's shadow"); + assert_eq!(img.pixel(35, 75), [255, 0, 0, 255], "the copy"); + assert_eq!(img.pixel(45, 75), [0, 255, 0, 255], "the copy's shadow, 5 pt to its right"); + assert_eq!(img.pixel(50, 75), [255, 255, 255, 255], "past the copy's shadow"); +} + +/// Each copy of a symbol instance's Transform effect draws the drop shadow listed before the effect +/// under itself, scaled with it: the black square (40..60) has its green shadow 10 pt to its right, +/// and its copy scaled 150 % and moved 30 pt down (35..65 across, 65..95 down) has its own 15 pt to +/// its right. The bounds reach as far as the copy's shadow, and as far as a shadow listed after the +/// Transform effect paints below all of them. +#[test] +fn each_copy_of_a_symbol_instances_transform_effect_draws_its_own_shadow() { + let shadow = fx("stylize.dropShadow", json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"})); + let copies = fx("distort.transform", json!({"scaleH": 150, "scaleV": 150, "moveV": 30, "copies": 1})); + let below = fx("stylize.dropShadow", json!({"x": 0, "y": 20, "blur": 0, "opacity": 100, "mode": "normal", "color": "#0000ff"})); + let d = symbol_doc(vec![shadow.clone(), copies.clone(), below]); + let n = &d.layers[0].children().unwrap()[0]; + let b = crate::brush_fx::cull_bounds(&d.symbol_boxes(), n).unwrap(); + assert!(b.x1 >= 80.0 - 1e-9 && b.y1 >= 115.0 - 1e-9, "{b:?}"); + let d = symbol_doc(vec![shadow, copies]); + let img = render(&d); + assert_eq!(img.pixel(50, 50), [0, 0, 0, 255], "the instance"); + assert_eq!(img.pixel(65, 50), [0, 255, 0, 255], "the instance's shadow"); + assert_eq!(img.pixel(50, 80), [0, 0, 0, 255], "the copy"); + assert_eq!(img.pixel(77, 80), [0, 255, 0, 255], "the copy's shadow, 15 pt to its right"); + assert_eq!(img.pixel(85, 80), [255, 255, 255, 255], "past the copy's shadow"); + let n = &d.layers[0].children().unwrap()[0]; + let b = crate::brush_fx::cull_bounds(&d.symbol_boxes(), n).unwrap(); + assert!(b.x1 >= 80.0 - 1e-9, "{b:?}"); +} 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 05107bfb65..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; @@ -38,7 +41,13 @@ const UNIQUE_PLACEHOLDER: &str = "u_vc_unique_-"; pub(crate) fn export(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>) -> Output { // Live geometry effects (Roughen, Warp, Offset Path, Effect → Pathfinder…) export as their result. - let baked = vectorcraft_effects::bake_document(doc); + // An instance of a symbol whose art has such effects is written as that art placed by the + // instance and then baked, as the canvas draws it; other symbols keep one `` def. + // Hidden layers and objects are written when the options keep them; layers that do not print + // always are. `native` (Preserve Editing) is the document as it is, with its live effects. + let hidden = opts.hidden_layers; + let layers = vectorcraft_effects::WrittenLayers { hidden, non_printing: true, hidden_objects: hidden }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, true, layers); let doc = baked.as_ref().unwrap_or(doc); if opts.object_ids != ObjectIds::Unique { return write(doc, opts, native, ""); @@ -149,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/nodes.rs b/crates/svg/src/export/nodes.rs index ea1d5ab95b..b9af2a6c06 100644 --- a/crates/svg/src/export/nodes.rs +++ b/crates/svg/src/export/nodes.rs @@ -1061,8 +1061,8 @@ impl Writer<'_> { (self.xf, self.instance_xf) = saved; return; } - if let Some(def) = self.symbol_use(sym, n, *xf) { - let m = self.xf * *xf; + let m = self.xf * *xf; + if let Some(def) = self.symbol_use(sym, n, m) { let tr = if m == Affine::IDENTITY { String::new() } else { format!(" transform=\"{}\"", self.matrix(m)) }; self.line(&format!("")); return; @@ -1103,7 +1103,8 @@ impl Writer<'_> { } } - /// The id of the `` def instance `inst` (transform `xf`) can ``, written on first + /// The id of the `` def instance `inst` can `` with transform `xf` (the ``'s + /// own: the instance's transform after those of the instances it sits in), written on first /// use. `None` when the instance needs its own copy of the art: stained by its fill, or moved /// by a transform under which the def would not look as the canvas paints it ([`Reuse`]). fn symbol_use(&mut self, sym: &vectorcraft_doc::Symbol, inst: &Node, xf: Affine) -> Option { diff --git a/crates/svg/src/export/output.rs b/crates/svg/src/export/output.rs index 818a64e293..3ed101340a 100644 --- a/crates/svg/src/export/output.rs +++ b/crates/svg/src/export/output.rs @@ -164,14 +164,22 @@ impl Writer<'_> { } /// Reserve ids for every named object up front so generated def ids never collide with them. + /// Symbols' art takes no ids, also where the drawing holds it placed by an instance (every + /// instance of the symbol writes it). pub(super) fn assign_name_ids(&mut self) { if self.opts.object_ids == ObjectIds::Minimal { return; } + let mut art = HashSet::new(); + for s in &self.doc.symbols { + s.art.walk(&mut |n| { + art.insert(n.id); + }); + } let mut named: Vec<(NodeId, String)> = Vec::new(); self.doc.walk(|n| { // Ruler guides are not written, so their names reserve no id. - if n.is_ruler_guide() { + if n.is_ruler_guide() || art.contains(&n.id) { return; } if let Some(name) = &n.name { diff --git a/crates/svg/src/export/paint.rs b/crates/svg/src/export/paint.rs index 7e67f09cf7..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))) } @@ -37,9 +43,25 @@ pub(super) enum StrokePlan { Written(Written), } +/// Visit `n` and the descendants the writer draws ([`Writer::node_body`]): a hidden layer or object +/// and what it holds only with `hidden` (SVG Options › hidden layers kept), and a template layer's +/// art never. +fn walk_drawn<'a>(n: &'a Node, hidden: bool, f: &mut impl FnMut(&'a Node)) { + if !(n.visible || hidden) { + return; + } + f(n); + if matches!(n.kind, NodeKind::Layer { template: true, .. }) { + return; + } + for c in n.children().into_iter().flatten() { + walk_drawn(c, hidden, f); + } +} + impl Writer<'_> { pub(super) fn count_colorized_images(&mut self, art: &Node) { - art.walk(&mut |n| { + walk_drawn(art, self.opts.hidden_layers, &mut |n| { let NodeKind::Image(im) = &n.kind else { return }; let Some(Paint::Solid { color, .. }) = n.extras().colorize.as_deref() else { return }; let shown = self.doc.shown_image(n, im); @@ -81,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 @@ -176,7 +199,7 @@ impl Writer<'_> { self.count_colorized_images(art); // Each image's count and its first piece, which shows what they all show. let mut seen: HashMap<(String, u32, u32), (usize, vectorcraft_doc::ImageObject)> = HashMap::new(); - art.walk(&mut |c| { + walk_drawn(art, self.opts.hidden_layers, &mut |c| { if let NodeKind::Image(im) = &c.kind { let shown = self.doc.shown_image(c, im); let im = &*shown; @@ -521,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/export/text.rs b/crates/svg/src/export/text.rs index 2f8e8b8a1b..672005bdf6 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -86,11 +86,15 @@ impl Writer<'_> { // type with warichu, whose stacked lines a reader's can't place either. So are // small capitals, superscript and subscript and tab leaders, which SVG text doesn't draw (#3869), // and a glyph chosen for a character, which a reader's draws with the default glyph. So - // is type in one of the document's composite fonts, which a reader can't find by its name. + // is type in one of the document's composite fonts, which a reader can't find by its name, + // and type with an Adjust Diacritic Position, whose marks a reader's draws where the + // font puts them. let unwritable = t.runs.iter().any(|r| { r.style.small_caps.is_some() || r.style.position != vectorcraft_doc::CharPosition::Normal || r.style.glyph_alternate.is_some() + || r.style.diacritic_horizontal != 0.0 + || r.style.diacritic_vertical != 0.0 || vectorcraft_doc::CompositeFont::named(&doc.composite_fonts, &r.style.font_family).is_some() }) || std::iter::once(&t.para).chain(&t.paras).any(|p| p.tabs.iter().any(|tab| !tab.leader.is_empty())); let outlined = self.opts.outline_text @@ -294,6 +298,11 @@ impl Writer<'_> { self.warn("type on a path with bullets or numbers is outlined to keep its look"); return self.text_outlines(n, t); } + // Nor the character a repeat mark is drawn as in the mark's width (Kurikaeshi Moji Shori). + if !lay.repeat_marks.is_empty() { + self.warn("type on a path that starts with a repeat mark drawn as the character it repeats is outlined to keep its look"); + return self.text_outlines(n, t); + } return self.text_on_path(n, t, path, *start); } self.note_fonts(t, &lay); @@ -434,7 +443,8 @@ impl Writer<'_> { // reader would draw elsewhere, the next segment is placed. place = seg.brk || (!fewer && !base.anchored && positioned); if (st.h_scale - st.v_scale).abs() > 1e-9 || seg.scale != 1.0 { - attrs.push_str(&format!(" textLength=\"{}\" lengthAdjust=\"spacingAndGlyphs\"", self.num(seg.advance * seg.scale))); + let length = seg.advance * seg.scale + seg.repeat_widen; + attrs.push_str(&format!(" textLength=\"{}\" lengthAdjust=\"spacingAndGlyphs\"", self.num(length))); } if st.rotation != 0.0 { attrs.push_str(&format!(" rotate=\"{}\"", self.num(-st.rotation))); @@ -491,7 +501,11 @@ impl Writer<'_> { }); let Some(chars) = self.fonts.get_mut(at).map(|u| &mut u.chars) else { continue }; // As written: a list marker's characters, a hyphen where a line breaks, capitals for All - // Caps, the style's Digits. + // Caps, the style's Digits, the character a repeat mark is drawn as. + if let Some(c) = shown_repeat(lay, i, g) { + chars.insert(c); + continue; + } let src = lay.marker_text(i).unwrap_or_else(|| if g.len == 0 { "-" } else { plain.get(g.byte..g.byte + g.len).unwrap_or("") }); for c in src.chars().filter(|c| !c.is_control() && *c != '\u{ad}').map(|c| st.digits.map(c)) { if st.all_caps { @@ -707,6 +721,9 @@ struct Segment { /// Glyph Scaling of the segment's one glyph (Justification…), which a reader stretches it to /// (`textLength`); 1 for other segments. scale: f64, + /// How much wider than the repeat mark the canvas draws the character the mark is drawn as + /// (Kurikaeshi Moji Shori), which a reader stretches it to (`textLength`); 0 for other segments. + repeat_widen: f64, /// A list marker's characters and tab, written in /// [`vectorcraft_doc::text::ParaList::marker_style`] of the run's style. marker: bool, @@ -716,6 +733,41 @@ struct Segment { /// given its own position (points). const PLACE_TOLERANCE: f64 = 1e-6; +/// Kurikaeshi Moji Shori: the character glyph `i` of `lay` shows when the layout drew a repeat mark +/// as the character it repeats ([`vectorcraft_text::TextLayout::repeat_marks`]), or None. +fn shown_repeat(lay: &vectorcraft_text::TextLayout, i: usize, g: &vectorcraft_text::PositionedGlyph) -> Option { + if lay.repeat_marks.is_empty() || g.len == 0 || lay.marker_text(i).is_some() { + return None; + } + // The marks are in text order, one per line. + let at = lay.repeat_marks.binary_search_by_key(&g.byte, |&(byte, _)| byte).ok()?; + lay.repeat_marks.get(at).map(|&(_, c)| c) +} + +/// Kurikaeshi Moji Shori: how much wider than repeat mark `cluster` the canvas draws glyph `g`, the +/// character the mark is drawn as in the mark's place (text space), or 0 when the face or the +/// mark's glyph is not found. +fn repeat_widen(g: &vectorcraft_text::PositionedGlyph, cluster: &str) -> f64 { + let Some(face) = FontDb::global().face_by_id(g.font_id) else { return 0.0 }; + // ゝ or ヽ with a combining voicing mark is drawn as one glyph, the voiced mark's. + let mark = match cluster { + "ゝ\u{3099}" => 'ゞ', + "ヽ\u{3099}" => 'ヾ', + _ => match cluster.chars().next() { + Some(c) => c, + None => return 0.0, + }, + }; + let mark_gid = face.glyph_for(mark); + if mark_gid == 0 { + return 0.0; + } + // Font units along the baseline → text space (size, Horizontal Scale and Glyph Scaling). + let [a, b, ..] = g.xf.as_coeffs(); + let widen = (face.advance(g.gid) - face.advance(mark_gid)) * a.hypot(b); + if widen.is_finite() { widen } else { 0.0 } +} + /// The laid-out lines of `t` as segments: a new segment at every style change, after tabs and, /// on justified lines, after each word space (unless `fewer`). The text comes from the clusters /// the layout placed: soft hyphens draw nothing, a line broken by hyphenation ends in `-`, all @@ -804,9 +856,16 @@ fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) - } None => (g.advance, g.origin.x), }; - let src: String = source(line.glyph_start + k, g).chars().filter(|c| *c != '\u{ad}').map(|c| run.style.digits.map(c)).collect(); + let repeat = shown_repeat(lay, line.glyph_start + k, g); + let src: String = match repeat { + Some(c) => c.to_string(), + None => source(line.glyph_start + k, g).chars().filter(|c| *c != '\u{ad}').map(|c| run.style.digits.map(c)).collect(), + }; + let widen = if repeat.is_some() { repeat_widen(g, source(line.glyph_start + k, g)) } else { 0.0 }; let piece = if run.style.all_caps { src.to_uppercase() } else { src }; - let brk = piece == "\t" || (split_words && !piece.is_empty() && piece.chars().all(char::is_whitespace)); + // The character a repeat mark is drawn as takes the mark's width on the canvas, which a + // reader does not know: the text after it is placed anew. + let brk = piece == "\t" || (split_words && !piece.is_empty() && piece.chars().all(char::is_whitespace)) || repeat.is_some(); // A glyph Glyph Scaling widens or narrows is a segment of its own, stretched to its width. let scale = if reader.is_some() && (g.scale - 1.0).abs() > 1e-9 && g.scale.is_finite() { g.scale } else { 1.0 }; let fresh = std::mem::take(&mut after_inline) || scale != 1.0 || segs.last().is_some_and(|last| last.scale != 1.0); @@ -820,7 +879,8 @@ fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) - let marker = lay.marker_of(line.glyph_start + k).is_some(); let tab_apart = piece == "\t" && (run.style.h_scale - run.style.v_scale).abs() > 1e-9; match segs.last_mut() { - Some(last) if last.run == g.run && !last.brk && !fresh && !moved && last.marker == marker && !tab_apart => { + // The character a repeat mark is drawn as is a segment of its own, stretched to its width. + Some(last) if last.run == g.run && !last.brk && !fresh && !moved && last.marker == marker && !tab_apart && repeat.is_none() => { last.text.push_str(&piece); last.advance += advance; last.brk = brk; @@ -830,7 +890,7 @@ fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) - last.brk |= moved || last.marker != marker; end_segment(last, tail, t, lay, &mut unkerned); } - segs.push(Segment { run: g.run, x, y: g.origin.y, text: piece, advance, brk, scale, marker }); + segs.push(Segment { run: g.run, x, y: g.origin.y, text: piece, advance, brk, scale, repeat_widen: widen, marker }); } } tail = set.map(|_| (g.byte, advance)); 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 c60d22f983..631bed3d0c 100644 --- a/crates/svg/src/import/files.rs +++ b/crates/svg/src/import/files.rs @@ -875,7 +875,8 @@ fn raster(format: image::ImageFormat) -> Option { /// TIFF) leaves the pixels as stored. Otherwise the pixels are read ([`decoded`], /// [`tiff_pixels`]), turned or flipped as the orientation says, and written as PNG, so usvg sizes /// and fits the image as it is shown, with the resolution the file declares -/// ([`vectorcraft_doc::ppi::resolution`]), its axes swapped by a quarter turn. A CMYK TIFF also +/// ([`vectorcraft_doc::ppi::resolution`]), its axes swapped by a quarter turn, and the ICC profile +/// the file carries when its color space is the written samples' (gray or RGB). A CMYK TIFF also /// keeps its inks as a CMYK TIFF ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]), and a CMYK JPEG /// or TIFF that is turned keeps them turned ([`vectorcraft_doc::cmyk::turned_cmyk`]). `None` when /// the pixels can't be read, and for a TIFF with more strips or tiles than the decoder can count @@ -893,7 +894,7 @@ fn shown(bytes: Arc>, format: image::ImageFormat) -> Option { return Some(Shown { kind, bytes, cmyk: None }); } let tiff = image::guess_format(&bytes).ok() == Some(F::Tiff); - let mut img = if tiff { tiff_pixels(&bytes)? } else { decoded(&bytes, format)? }; + let (mut img, icc) = if tiff { tiff_pixels(&bytes)? } else { decoded(&bytes, format)? }; let ppi = vectorcraft_doc::ppi::resolution(&bytes); // The resolution describes the stored pixels; a quarter turn swaps its axes. let quarter = orientation.is_some_and(|o| o.to_exif() >= 5); @@ -906,33 +907,49 @@ fn shown(bytes: Arc>, format: image::ImageFormat) -> Option { if let Some(orientation) = orientation { img.apply_orientation(orientation); } + use image::DynamicImage as D; + let img = match img { + D::ImageLuma8(_) | D::ImageLumaA8(_) | D::ImageRgb8(_) | D::ImageRgba8(_) => img, + D::ImageLuma16(_) | D::ImageLumaA16(_) | D::ImageRgb16(_) | D::ImageRgba16(_) => img, + other => D::ImageRgba8(other.into_rgba8()), + }; let mut png = Vec::new(); - img.write_to(&mut std::io::Cursor::new(&mut png), F::Png).ok()?; + let mut encoder = image::codecs::png::PngEncoder::new(&mut png); + if let Some(icc) = icc.filter(|icc| png_takes_icc(&img, icc)) { + // A profile the encoder doesn't take leaves the image without one. + let _ = image::ImageEncoder::set_icc_profile(&mut encoder, icc); + } + img.write_with_encoder(encoder).ok()?; if let Some(ppi) = shown_ppi { png = vectorcraft_doc::ppi::with_png_resolution(&png, ppi); } Some(Shown { kind: ImageKind::PNG, bytes: Arc::new(png), cmyk }) } +/// Can a PNG of `img`'s samples carry ICC profile `icc`? Its color space must be the samples': +/// `GRAY` for gray samples, `RGB ` for RGB ones. +fn png_takes_icc(img: &image::DynamicImage, icc: &[u8]) -> bool { + let want = if img.color().has_color() { *b"RGB " } else { *b"GRAY" }; + vectorcraft_doc::cmyk::icc_color_space(icc) == Some(want) +} + /// The pixels of encoded image `bytes` (`format` when their bytes don't say), as stored, decoded /// within [`vectorcraft_doc::MAX_RASTER_ALLOC`], counted as decoded and as RGBA, as Open and Place -/// decode them; `None` when they can't be. -fn decoded(bytes: &[u8], format: image::ImageFormat) -> Option { - use image::ImageDecoder as _; +/// decode them, with the ICC profile their samples are in when the file carries one the decoder +/// 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>)> { 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 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; } - image::DynamicImage::from_decoder(decoder).ok() + 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 @@ -940,15 +957,17 @@ fn decoded(bytes: &[u8], format: image::ImageFormat) -> Option Option { +/// ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]). Pixels the image decoder reads come with the +/// TIFF's ICC profile; the other readers give sRGB pixels, without one. `None` when they can't be +/// read. +fn tiff_pixels(bytes: &[u8]) -> Option<(image::DynamicImage, Option>)> { use image::DynamicImage::ImageRgba8; let cms = vectorcraft_color::cms::active(); if let Some(img) = vectorcraft_doc::cmyk::extra_samples_tiff_rgba(bytes, |c| cms.cmyk_to_srgb(c, false)) { - return Some(ImageRgba8(img)); + return Some((ImageRgba8(img), None)); } if let Some(read) = vectorcraft_doc::cmyk::group3_tiff_rgba(bytes) { - return read.ok().map(ImageRgba8); + return read.ok().map(|img| (ImageRgba8(img), None)); } decoded(bytes, image::ImageFormat::Tiff).or_else(|| decoded(&vectorcraft_doc::cmyk::stored_cmyk_tiff(bytes, None)?, image::ImageFormat::Tiff)) } @@ -1480,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 91180981db..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}; @@ -315,9 +318,51 @@ impl V { } } -/// σ of a blur with standard deviations `x`, `y` (their mean: the effects blur evenly). -fn sd(x: f32, y: f32) -> f64 { - (x as f64 + y as f64) / 2.0 +/// σ of a blur with standard deviations `x`, `y` in a user space the document scales by the same +/// amount in every direction when `even` (turned, flipped or scaled alike along both axes). The +/// effects blur evenly: `None` when the blur differs by direction in the document, unless `blurs` +/// is [`Blurs::Nearest`], which takes the mean. +fn sd(x: f32, y: f32, even: bool, blurs: Blurs) -> Option { + let uneven = (x > 0.0 || y > 0.0) && (x != y || !even); + (blurs == Blurs::Nearest || !uneven).then_some((x as f64 + y as f64) / 2.0) +} + +/// How [`effects`] reads a blur that differs by direction in the document, which the effects +/// draw the same in every direction. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Blurs { + /// Not as an effect: the filter is left for an SVG Filters effect ([`kept`]), which draws it. + Exact, + /// As the even blur of the mean standard deviation. + Nearest, +} + +/// Whether the linear part of `ts` scales every direction by the same amount (a turn, a flip and +/// an even scale), so an even blur stays even in the document. +fn even_space(ts: Affine) -> bool { + let [a, b, c, d, _, _] = ts.as_coeffs(); + let tol = 1e-9 * ts.determinant().abs().sqrt().max(1.0); + let near = |p: f64, q: f64| (p - q).abs() <= tol; + (near(a, d) && near(b, -c)) || (near(a, -d) && near(b, c)) +} + +/// `filters` (in the order they apply) imported in user space mapped to the document by `ts`: as +/// the live effects they draw as ([`effects`]), else as SVG Filters effects that keep their XML +/// ([`kept`]), else as the live effects nearest them (a blur that differs by direction drawn as +/// an even one). With whether they are live effects. `None` when none of these takes them. +pub(super) fn imported( + filters: &[Arc], + ts: Affine, + blends: &HashMap, + sources: &HashMap, +) -> Option<(Vec, bool)> { + if let Some(fx) = effects(filters, ts, blends, Blurs::Exact) { + return Some((fx, true)); + } + if let Some(fx) = kept(filters, ts, sources) { + return Some((fx, false)); + } + effects(filters, ts, blends, Blurs::Nearest).map(|fx| (fx, true)) } fn color(c: usvg::Color) -> Color { @@ -364,9 +409,10 @@ fn transferred(v: V, [r, g, b, a]: [&TransferFunction; 4], srgb: bool) -> Option } } -/// Evaluate one filter's primitives, `k` the scale from its user space to the document. +/// Evaluate one filter's primitives, `k` the scale from its user space to the document, `even` +/// when that scale is the same in every direction ([`even_space`]), blurs read as `blurs` says. /// `None` when one does something the effects cannot represent. -fn eval(f: &Filter, k: f64) -> Option { +fn eval(f: &Filter, k: f64, even: bool, blurs: Blurs) -> Option { let mut results: HashMap<&str, V> = HashMap::new(); let mut last = V::Graphic; for p in f.primitives() { @@ -380,7 +426,7 @@ fn eval(f: &Filter, k: f64) -> Option { let v = match p.kind() { Kind::GaussianBlur(b) => { let linear = p.color_interpolation() == ColorInterpolation::LinearRGB; - input(b.input())?.blur(sd(b.std_dev_x().get(), b.std_dev_y().get()), linear)? + input(b.input())?.blur(sd(b.std_dev_x().get(), b.std_dev_y().get(), even, blurs)?, linear)? } Kind::Offset(o) => input(o.input())?.offset(o.dx() as f64, o.dy() as f64)?, Kind::Flood(fl) => V::Flood(color(fl.color()), fl.opacity().get()), @@ -450,8 +496,8 @@ fn eval(f: &Filter, k: f64) -> Option { } } Kind::DropShadow(d) if matches!(input(d.input())?, V::Graphic) => { - let shape = - Shape { sd: sd(d.std_dev_x().get(), d.std_dev_y().get()), dx: d.dx() as f64, dy: d.dy() as f64, moved: true, inverted: false }; + let sd = sd(d.std_dev_x().get(), d.std_dev_y().get(), even, blurs)?; + let shape = Shape { sd, dx: d.dx() as f64, dy: d.dy() as f64, moved: true, inverted: false }; V::Stack(vec![V::Paint { shape, color: color(d.color()), opacity: d.opacity().get(), clipped: false }, V::Graphic]) } _ => return None, @@ -463,10 +509,12 @@ fn eval(f: &Filter, k: f64) -> Option { } /// The live effects `filters` (in the order they apply) stand for, in user space mapped to the -/// document by `ts`; `blends`: the modes our export recorded ([`blends`]). `None` when one of -/// them isn't an effect the canvas draws. -pub(super) fn effects(filters: &[Arc], ts: Affine, blends: &HashMap) -> Option> { +/// document by `ts`; `blends`: the modes our export recorded ([`blends`]); `blurs`: how a blur +/// that differs by direction reads ([`Blurs`]). `None` when one of them isn't an effect the +/// canvas draws. +fn effects(filters: &[Arc], ts: Affine, blends: &HashMap, blurs: Blurs) -> Option> { let k = ts.determinant().abs().sqrt(); + let even = even_space(ts); let [a, b, c, d, _, _] = ts.as_coeffs(); let along = |dx: f64, dy: f64| Vec2::new(a * dx + c * dy, b * dx + d * dy); let num = |v: f64| (v * 1000.0).round() / 1000.0; @@ -475,7 +523,7 @@ pub(super) fn effects(filters: &[Arc], ts: Affine, blends: &HashMap continue, // SVG blurs in linear light unless the filter asks for sRGB (`color-interpolation-filters`). V::Blurred(sd, true) => ("blur.gaussian", json!({ "radius": blur(sd), "linear": true })), diff --git a/crates/svg/src/import/importer.rs b/crates/svg/src/import/importer.rs index 2eede1f7be..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; @@ -243,48 +244,59 @@ impl Importer { if !matches!(kids.get(main), Some(usvg::Node::Path(p)) if p.is_visible()) { return Some(vec![]); } - let text::PendingText { name, mut obj, servers, paints, non_scaling, under, .. } = self.slots.texts.get(i)?.clone(); - // The scale the type draws at becomes its size (last, below): text space grows by `grow`. - let xf = ts * obj.xf; - let grow = text::size_scale(&obj, xf); - // usvg resolved the `url(#…)` paints (the paths after the main one) in the element's user - // space; runs paint in text space. - let to_text = Affine::scale(grow) * obj.xf.inverse(); + let text::PendingText { name, obj, servers, rest, paints, non_scaling, under, .. } = self.slots.texts.get(i)?.clone(); let slot_paint = |im: &mut Self, k: usize, m: Affine| match kids.get(main + 1 + k) { Some(usvg::Node::Path(p)) => p.fill().map_or(Paint::None, |f| im.paint(f.paint(), m)), _ => Paint::None, }; - let resolved: Vec = (0..paints).map(|k| slot_paint(self, k, to_text)).collect(); - let server = |k: usize| resolved.get(k).cloned().unwrap_or(Paint::None); - for (run, (fill, stroke)) in obj.runs.iter_mut().zip(servers) { - if let Some(k) = fill { - run.style.fill = server(k); + // A text split into several objects becomes a group of them, named after the element. + let whole = rest.is_empty(); + let mut skewed = false; + let mut nodes = Vec::with_capacity(rest.len() + 1); + for (mut obj, servers) in std::iter::once((obj, servers)).chain(rest) { + // The scale the type draws at becomes its size (last, below): text space grows by `grow`. + let xf = ts * obj.xf; + let grow = text::size_scale(&obj, xf); + // usvg resolved the `url(#…)` paints (the paths after the main one) in the element's user + // space; runs paint in text space. + let to_text = Affine::scale(grow) * obj.xf.inverse(); + let resolved: Vec = (0..paints).map(|k| slot_paint(self, k, to_text)).collect(); + let server = |k: usize| resolved.get(k).cloned().unwrap_or(Paint::None); + for (run, (fill, stroke)) in obj.runs.iter_mut().zip(servers) { + if let Some(k) = fill { + run.style.fill = server(k); + } + if let Some(k) = stroke { + run.style.stroke = server(k); + } } - if let Some(k) = stroke { - run.style.stroke = server(k); + obj.xf = xf; + skewed |= non_scaling && !vector_effect::unscale_text(&mut obj, self.screen); + // A stroke under the characters is the object's own: it paints in the document. + let under = under.clone().map(|(mut sl, k)| { + if let Some(k) = k { + sl.paint = slot_paint(self, k, ts); + } + let mut ap = Appearance { items: vec![AppearanceItem::Stroke(sl)], ..Default::default() }; + ap.scale_strokes(if non_scaling { self.screen } else { obj.xf.determinant().abs().sqrt() }); + ap.set_contents_at(1); + ap + }); + text::fold_scale(&mut obj, grow); + let mut n = self.named(if whole { &name } else { "" }, NodeKind::Text(Box::new(obj)))?; + if let Some(ap) = under { + n.appearance = ap.into(); } + nodes.push(Arc::new(n)); } - obj.xf = xf; - if non_scaling && !vector_effect::unscale_text(&mut obj, self.screen) { + if skewed { let label = if name.is_empty() || made_up(&name) { "a text".to_string() } else { format!("text '{name}'") }; self.warn(format!("non-scaling stroke on {label} approximated: the text is stretched or skewed")); } - // A stroke under the characters is the object's own: it paints in the document. - let under = under.map(|(mut sl, k)| { - if let Some(k) = k { - sl.paint = slot_paint(self, k, ts); - } - let mut ap = Appearance { items: vec![AppearanceItem::Stroke(sl)], ..Default::default() }; - ap.scale_strokes(if non_scaling { self.screen } else { obj.xf.determinant().abs().sqrt() }); - ap.set_contents_at(1); - ap - }); - text::fold_scale(&mut obj, grow); - let mut n = self.named(&name, NodeKind::Text(Box::new(obj)))?; - if let Some(ap) = under { - n.appearance = ap.into(); + if whole { + return Some(nodes); } - Some(vec![Arc::new(n)]) + Some(vec![Arc::new(self.named(&name, NodeKind::Group { children: nodes, clip: false })?)]) } fn group_node(&mut self, g: &usvg::Group, acc: Affine) -> Option { @@ -303,11 +315,11 @@ impl Importer { (None, id) => format!("'{id}'"), }; let mask = g.mask().and_then(|m| self.opacity_mask(m, ts, &label)); - // Blurs, shadows and glows become live effects (see [`fx`]); other filters become Effect › - // SVG Filters effects that keep their XML. + // Blurs, shadows and glows become live effects (see [`fx`]); other filters, and blurs that + // differ by direction in the document, become Effect › SVG Filters effects that keep their XML. let effects = match g.filters() { [] => vec![], - filters => fx::effects(filters, ts, &self.blends).or_else(|| fx::kept(filters, ts, &self.filter_sources)).unwrap_or_else(|| { + filters => fx::imported(filters, ts, &self.blends, &self.filter_sources).map(|(fx, _)| fx).unwrap_or_else(|| { // usvg wraps a filtered element in a group of its own: name the element then. let on = match g.children() { [usvg::Node::Group(_)] | [] => label.clone(), @@ -383,7 +395,7 @@ impl Importer { /// () cuts a filter's result at /// its region. A filter that didn't import (drawn without it) clips nothing. fn filter_regions(&mut self, g: &usvg::Group, ts: Affine, mut n: Node) -> Option { - if g.filters().is_empty() || fx::effects(g.filters(), ts, &self.blends).is_none() { + if g.filters().is_empty() || !fx::imported(g.filters(), ts, &self.blends, &self.filter_sources).is_some_and(|(_, live)| live) { return Some(n); } for f in g.filters() { @@ -584,7 +596,8 @@ impl Importer { if p.id().is_empty() || !p.is_visible() || p.fill().is_some_and(|f| f.rule() == usvg::FillRule::EvenOdd) { return None; } - let mut obj = self.slots.texts.get(self.slots.find(p)?)?.obj.clone(); + // A text split into several objects clips by its outlines. + let mut obj = self.slots.texts.get(self.slots.find(p)?).filter(|t| t.rest.is_empty())?.obj.clone(); obj.xf = m * self.slots.inner(p) * obj.xf; let grow = text::size_scale(&obj, obj.xf); for run in &mut obj.runs { @@ -766,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 ef3934c2d6..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; @@ -130,6 +131,7 @@ const BIDI_NESTED: &str = "a unicode-bidi embedding inside another imported one const BIDI_TEXT_OVERRIDE: &str = "unicode-bidi override on the text imported as its paragraph direction; directional override is not supported"; /// One character of a text and the adjustments its position needs. +#[derive(Clone)] struct Cell { ch: char, style: CharStyle, @@ -178,6 +180,9 @@ pub(super) struct PendingText { pub obj: TextObject, /// For each run, the index of its fill's and stroke's `url(#…)` paint, if any. pub servers: Vec<(Option, Option)>, + /// The other point type objects of a text whose absolutely placed characters one object cannot + /// put on their x ([`split`]), after `obj` in text order, each with its runs' paint indices. + pub rest: Vec<(TextObject, Vec)>, /// Number of `url(#…)` paints (the placeholder paths after the main one, in order). pub paints: usize, /// `vector-effect="non-scaling-stroke"`: the character strokes keep their width on screen. @@ -233,7 +238,14 @@ impl TextSlots { return Some(bp.clone()); } let t = self.texts.get(i)?; - let bp = Rc::new(vectorcraft_text::layout(FontDb::global(), &t.obj).to_bezpath()); + let mut bp = vectorcraft_text::layout(FontDb::global(), &t.obj).to_bezpath(); + // The other objects of a split text, in the first one's text space. + for (o, _) in &t.rest { + let mut more = vectorcraft_text::layout(FontDb::global(), o).to_bezpath(); + more.apply_affine(t.obj.xf.inverse() * o.xf); + bp.extend(more.elements().iter().copied()); + } + let bp = Rc::new(bp); self.outlines.borrow_mut().insert(i, bp.clone()); Some(bp) } @@ -534,7 +546,10 @@ fn use_slot( shown.build(style_xml, style_t, &label, &mut found) }; let differs = |(text, paints): &(PendingText, Vec)| { - slots.texts.get(shared).is_none_or(|old| old.obj != text.obj || old.servers != text.servers || old.under != text.under) + slots + .texts + .get(shared) + .is_none_or(|old| old.obj != text.obj || old.servers != text.servers || old.rest != text.rest || old.under != text.under) || inst.paints.get(shared) != Some(paints) }; let slot = built.filter(differs).map(|(text, paints)| { @@ -1337,7 +1352,7 @@ impl Ctx { } let marker = Rect::new(b.x0, b.y0, b.x1.max(b.x0 + 1.0), b.y1.max(b.y0 + 1.0)); let name = t.attribute("id").unwrap_or("").to_string(); - Some((PendingText { name, obj, servers, paints: 0, non_scaling: false, under: None, marker }, Vec::new())) + Some((PendingText { name, obj, servers, rest: vec![], paints: 0, non_scaling: false, under: None, marker }, Vec::new())) } /// Read one ``: the pending text and its `url(#…)` paints. @@ -1469,6 +1484,7 @@ impl Ctx { let mut obj = TextObject::point(Point::ZERO, "", CharStyle::default()); let mut breaks: Vec = vec![]; let mut para_styles: Vec = vec![]; + let mut rest = vec![]; if let Some((tp, followed)) = path { let bp = &followed.path; // Along the path: dx is extra advance, dy shifts off the path. @@ -1549,46 +1565,37 @@ impl Ctx { obj.kind = TextKind::OnPath { path: PathData::from_bezpath(&bp), start: 0.0, end: None }; obj.xf = Affine::IDENTITY; } else { - let origin = Point::new(x[0].unwrap_or(0.0) + dx[0], y[0].unwrap_or(0.0) + dy[0]); - let (justify, left, starts, unplaced) = lines(&mut cells, &x, &y, &dx, &dy, &anchor_of, &pin, origin.x, &mut breaks); - if unplaced > 0 { + let whole = cells.clone(); + let mut ys = vec![]; + let (b, p, unplaced) = place(&mut cells, &x, &y, &dx, &dy, &anchor_of, &pin, &mut obj, &mut ys); + (breaks, para_styles) = (b, p); + if !unplaced.is_empty() { + // One object cannot put every absolutely placed character on its x: the text becomes + // several, the first of them `obj`. + let mut pieces = split(&whole, &x, &y, &dx, &dy, &ys, &anchor_of, &pin, unplaced).into_iter(); + if let Some(first) = pieces.next() { + (obj, cells, breaks, para_styles) = (first.obj, first.cells, first.breaks, first.paras); + } + rest = pieces + .map(|mut p| { + let servers = finish(&mut p.obj, &p.cells, &p.breaks, p.paras, &pin); + (p.obj, servers) + }) + .collect(); warnings.push(format!( - "{label}: {unplaced} absolutely placed character(s) between characters of the other direction keep their place in the line" + "{label}: imported as {} point type objects in a group, since one object cannot put every character on its own x", + rest.len() + 1 )); } - obj.para.justify = justify; - obj.xf = Affine::translate((finite(left), finite(origin.y))); - // Lines anchored differently or at different x (paragraphs aligned or indented - // differently): each line's paragraph takes its alignment, and indents that put it - // where it was. - if starts.iter().any(|&(_, a, ax)| a != starts[0].1 || ax != starts[0].2) { - for (k, &(_, a, ax)) in starts.iter().enumerate() { - let d = finite(ax - left); - let mut pa = ParaStyle { justify: justify_of(a), ..ParaStyle::default() }; - match pa.justify { - Justify::Center if d >= 0.0 => pa.left_indent = 2.0 * d, - Justify::Center => pa.right_indent = -2.0 * d, - Justify::Right => pa.right_indent = -d, - _ => pa.left_indent = d, - } - let count = if k == 0 { 1 } else { breaks.get(k - 1).map_or(1, |b| b.count) }; - para_styles.extend(std::iter::repeat_n(pa, count)); - } - } } - let (runs, servers) = assemble(&cells, &breaks).0; - obj.runs = runs; - if !para_styles.is_empty() { - obj.set_paragraph_styles(para_styles); - } - pin(&mut obj); - keep_reader_anchors(&mut obj); + let servers = finish(&mut obj, &cells, &breaks, para_styles, &pin); // The placeholder covers the text (laid out when a paint server needs its bounding box). - let b = if paints.is_empty() { obj.bounds() } else { Some(obj.xf.transform_rect_bbox(measure(&obj).bounds)) }.unwrap_or_default(); + let bounds = |o: &TextObject| if paints.is_empty() { o.bounds() } else { Some(o.xf.transform_rect_bbox(measure(o).bounds)) }; + let b = rest.iter().filter_map(|(o, _)| bounds(o)).fold(bounds(&obj), |all, b| Some(all.map_or(b, |a| a.union(b)))).unwrap_or_default(); let marker = Rect::new(b.x0, b.y0, b.x1.max(b.x0 + 1.0), b.y1.max(b.y0 + 1.0)); let name = t.attribute("id").unwrap_or("").to_string(); let non_scaling = vector_effect::is_non_scaling(&self.css, t); - Some((PendingText { name, obj, servers, paints: paints.len(), non_scaling, under, marker }, paints)) + Some((PendingText { name, obj, servers, rest, paints: paints.len(), non_scaling, under, marker }, paints)) } } @@ -1683,13 +1690,145 @@ fn leading_tolerance(spacing: f64) -> f64 { 0.01_f64.min(spacing.abs() * 1e-3) } +/// Point type `obj` of `cells` placed by the positioning lists ([`lines`]): sets its justification +/// and transform, and returns its line breaks, its paragraph styles and the absolutely placed +/// characters kerning cannot put on their x. `ys` takes each character's line baseline and y. +#[allow(clippy::too_many_arguments)] +fn place( + cells: &mut [Cell], + x: &[Option], + y: &[Option], + dx: &[f64], + dy: &[f64], + anchor_of: &dyn Fn(usize) -> f64, + pin: &dyn Fn(&mut TextObject), + obj: &mut TextObject, + ys: &mut Vec<(f64, f64)>, +) -> (Vec, Vec, Vec) { + let mut breaks = vec![]; + let mut para_styles = vec![]; + let origin = Point::new(x[0].unwrap_or(0.0) + dx[0], y[0].unwrap_or(0.0) + dy[0]); + let (justify, left, starts, unplaced) = lines(cells, x, y, dx, dy, anchor_of, pin, origin.x, &mut breaks, ys); + obj.para.justify = justify; + obj.xf = Affine::translate((finite(left), finite(origin.y))); + // Lines anchored differently or at different x (paragraphs aligned or indented + // differently): each line's paragraph takes its alignment, and indents that put it + // where it was. + if starts.iter().any(|&(_, a, ax)| a != starts[0].1 || ax != starts[0].2) { + for (k, &(_, a, ax)) in starts.iter().enumerate() { + let d = finite(ax - left); + let mut pa = ParaStyle { justify: justify_of(a), ..ParaStyle::default() }; + match pa.justify { + Justify::Center if d >= 0.0 => pa.left_indent = 2.0 * d, + Justify::Center => pa.right_indent = -2.0 * d, + Justify::Right => pa.right_indent = -d, + _ => pa.left_indent = d, + } + let count = if k == 0 { 1 } else { breaks.get(k - 1).map_or(1, |b| b.count) }; + para_styles.extend(std::iter::repeat_n(pa, count)); + } + } + (breaks, para_styles, unplaced) +} + +/// Gives `obj` the runs of `cells` with `breaks`, its paragraph styles and its paragraph +/// directions; returns the paint indices of its runs. +fn finish(obj: &mut TextObject, cells: &[Cell], breaks: &[Break], para_styles: Vec, pin: &dyn Fn(&mut TextObject)) -> Vec { + let (runs, servers) = assemble(cells, breaks).0; + obj.runs = runs; + if !para_styles.is_empty() { + obj.set_paragraph_styles(para_styles); + } + pin(obj); + keep_reader_anchors(obj); + servers +} + +/// One point type object of a text [`split`] into several, before [`finish`]. +struct Piece { + obj: TextObject, + cells: Vec, + breaks: Vec, + paras: Vec, +} + +/// How many times [`split`] cuts a piece before the characters kerning cannot place; a piece that +/// still has such characters is then cut before each of its chunks. +const MAX_SPLITS: usize = 3; + +/// Point type objects, in text order, that together put every absolutely placed character of +/// `cells` (before [`place`] kerned them) on its x. SVG anchors each chunk on its own and reorders +/// right-to-left characters only within a chunk (SVG 2 › Text, https://www.w3.org/TR/SVG2/text.html), +/// while one object reorders the whole +/// line: a left-to-right character drawn right before a right-to-left one has no kerning between +/// them. The text is cut before each character `unplaced` lists, and each piece placed again. `ys` +/// holds each character's line baseline and y, so that a piece keeps its characters' baselines. +#[allow(clippy::too_many_arguments)] +fn split( + cells: &[Cell], + x: &[Option], + y: &[Option], + dx: &[f64], + dy: &[f64], + ys: &[(f64, f64)], + anchor_of: &dyn Fn(usize) -> f64, + pin: &dyn Fn(&mut TextObject), + unplaced: Vec, +) -> Vec { + let piece = |r: Range| { + let s = r.start; + let mut cells = cells[r.clone()].to_vec(); + let (base, cur) = ys.get(s).copied().unwrap_or((0.0, 0.0)); + // The piece starts on its line's baseline, and its first character keeps its own y. + cells[0].style.baseline_shift += base - cur; + let py: Vec> = r + .clone() + .map(|i| match i - s { + 0 => Some(base), + 1 => y[i].or(Some(cur)), + _ => y[i], + }) + .collect(); + let mut pdy = dy[r.clone()].to_vec(); + pdy[0] = 0.0; + let mut obj = TextObject::point(Point::ZERO, "", CharStyle::default()); + let (breaks, paras, unplaced) = place(&mut cells, &x[r.clone()], &py, &dx[r], &pdy, &|j| anchor_of(s + j), pin, &mut obj, &mut vec![]); + (Piece { obj, cells, breaks, paras }, unplaced.into_iter().map(|j| s + j).collect::>()) + }; + let mut done = vec![]; + let mut todo = vec![(0..cells.len(), unplaced, 0)]; + while let Some((range, failed, round)) = todo.pop() { + // Past the last round every chunk of the piece is a piece of its own, and so has no + // characters to place. + let mut cuts: Vec = if round < MAX_SPLITS { failed } else { (range.start + 1..range.end).filter(|&i| x[i].is_some()).collect() }; + cuts.sort_unstable(); + cuts.dedup(); + let mut from = range.start; + for to in cuts.into_iter().chain([range.end]) { + if to <= from || to > range.end { + continue; + } + match piece(from..to) { + (p, failed) if failed.is_empty() => done.push((from, p)), + (_, failed) => todo.push((from..to, failed, round + 1)), + } + from = to; + } + } + done.sort_by_key(|p| p.0); + done.into_iter().map(|p| p.1).collect() +} + +/// A line's first character, alignment (as for [`justify_of`]) and anchor x. +type LineStart = (usize, f64, f64); + /// Point type: line breaks, baseline shifts and kerning from the positioning lists. Returns the /// justification, the x of the first line's left (or anchor) edge and each line's first /// character, alignment (as for [`justify_of`]) and anchor x. `anchor_of` gives where the chunk /// starting at a character sits on its anchor, and `pin` sets the paragraph directions of the /// text ([`pin_direction`]). When characters are placed on their own, every line is left-aligned -/// and its anchor x is its left edge. Also returns how many absolutely placed characters kerning -/// cannot put on their x. +/// and its anchor x is its left edge. Also returns the absolutely placed characters kerning cannot +/// put on their x. `ys` takes each character's line baseline and y. #[allow(clippy::too_many_arguments)] fn lines( cells: &mut [Cell], @@ -1701,10 +1840,13 @@ fn lines( pin: &dyn Fn(&mut TextObject), x0: f64, breaks: &mut Vec, -) -> (Justify, f64, Vec<(usize, f64, f64)>, usize) { + ys: &mut Vec<(f64, f64)>, +) -> (Justify, f64, Vec, Vec) { let n = cells.len(); let y0 = y[0].unwrap_or(0.0) + dy[0]; let (mut base, mut cur) = (y0, y0); + ys.clear(); + ys.push((y0, y0)); // Line starts (first character, anchor x) and absolutely placed characters (index, x). let mut lines = vec![(0, x0)]; let mut targets: Vec<(usize, f64)> = vec![]; @@ -1723,9 +1865,11 @@ fn lines( breaks.push(Break { at: i, count: count as usize, leading: gap / count }); lines.push((i, ax + dx[i])); (base, cur) = (ny, ny); + ys.push((base, cur)); continue; } cur = ny; + ys.push((base, cur)); match x[i] { Some(ax) => targets.push((i, ax + dx[i])), None => cells[i - 1].kern += dx[i], @@ -1744,7 +1888,7 @@ fn lines( } if targets.is_empty() { let starts = lines.iter().map(|&(s, lx)| (s, anchor_of(s), lx)).collect(); - return (justify_of(anchor_of(0)), x0, starts, 0); + return (justify_of(anchor_of(0)), x0, starts, vec![]); } // Absolutely placed characters: lay the text out left-aligned and kern each one onto its x. // SVG anchors every absolutely placed chunk on its own, so a chunk not anchored at its left @@ -1774,7 +1918,7 @@ fn lines( let mut wants: Vec<(usize, f64)> = vec![]; // Absolutely placed characters drawn right next to a placed neighbor with no kerning between // them (a left-to-right character between right-to-left ones): they stay where the layout puts them. - let mut unplaced = 0; + let mut unplaced = vec![]; // Kerning changes shaping (pair kerning is off for manually kerned characters): repeat until // every character sits on its x. for round in 0..4 { @@ -1811,7 +1955,7 @@ fn lines( // character's horizontal scale, so each correction is divided by it. let mut worst = 0.0f64; let mut from = 0; - unplaced = 0; + unplaced.clear(); while from < wants.len() { let l = line_of(wants[from].0); let to = from + wants[from..].partition_point(|&(i, _)| line_of(i) == l); @@ -1831,35 +1975,35 @@ fn lines( .filter_map(|&(i, _)| (lines[l].0..i).rev().find_map(|j| pens[j]).map(|k| (2 * k.rank + if k.rtl { 1 } else { 3 }, i - 1))) .collect(); cuts.sort_unstable(); - let mut points: Vec<(usize, f64, f64)> = - on_line.iter().filter_map(|&(i, want)| pens[i].map(|p| (2 * p.rank + 2, p.start, want))).collect(); + let mut points: Vec<(usize, f64, f64, usize)> = + on_line.iter().filter_map(|&(i, want)| pens[i].map(|p| (2 * p.rank + 2, p.start, want, i))).collect(); points.sort_by_key(|p| p.0); // The character kerned at the first cut between places `a` and `b`. let cut = |a: usize, b: usize| cuts.get(cuts.partition_point(|c| c.0 <= a)).filter(|c| c.0 < b).map(|c| c.1); let split = points.partition_point(|p| p.0 < home); // Drawn right of the line's first chunk: kerning moves the character away from it. let (mut prev, mut moved) = (home, 0.0); - for &(place, start, want) in &points[split..] { + for &(place, start, want, i) in &points[split..] { if let Some(k) = cut(prev, place) { let d = want - (start - p0 + moved); cells[k].kern += d / spacing_scale(&cells[k].style, false); moved += d; worst = worst.max(d.abs()); } else { - unplaced += 1; + unplaced.push(i); } prev = place; } // Drawn left of it: kerning moves the chunk (and what lies between) away from the character. (prev, moved) = (home, 0.0); - for &(place, start, want) in points[..split].iter().rev() { + for &(place, start, want, i) in points[..split].iter().rev() { if let Some(k) = cut(place, prev) { let d = start - p0 - moved - want; cells[k].kern += d / spacing_scale(&cells[k].style, false); moved += d; worst = worst.max(d.abs()); } else { - unplaced += 1; + unplaced.push(i); } prev = place; } @@ -2064,7 +2208,8 @@ fn pens(lay: &TextLayout, bytes: &[usize], cells: &[Cell]) -> Vec> { .collect() } -type Key = (Option, Option); +/// The indices of a run's fill and stroke `url(#…)` paints. +pub(super) type Key = (Option, Option); type Runs = (Vec, Vec); /// Runs (and their paint indices) from the characters, with `breaks` inserted; also the byte offset 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/clip_text.rs b/crates/svg/tests/it/clip_text.rs index bb92802e60..4cbcc9a812 100644 --- a/crates/svg/tests/it/clip_text.rs +++ b/crates/svg/tests/it/clip_text.rs @@ -125,6 +125,20 @@ fn a_text_clip_path_with_a_clip_rule_or_a_clip_of_its_own_clips_by_its_outlines( assert_eq!(shapes[0].1, vectorcraft_geom::FillRule::EvenOdd); } +#[test] +fn a_text_imported_as_several_objects_clips_by_all_their_outlines() { + // One object cannot put ג on its x, so the text is several objects; the clip outlines all of them. + let d = open( + r##"אbג + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + assert!(!matches!(clip.kind, NodeKind::Text(_)), "{:?}", clip.kind); + let b = clip_bounds(clip); + // ג ends at 220, the first object at 160. + assert!(b.x1 > 200.0 && b.x1 <= 220.0 + 1e-6 && b.x0 < 100.0, "{b:?}"); +} + #[test] fn tspans_and_type_on_a_path_clip_too() { let d = open( 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 d9de61290b..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"); } @@ -362,6 +372,133 @@ fn a_cmyk_tiff_keeps_its_resolution_turned_or_not() { } } +/// A made-up ICC profile of `len` bytes (at least a header's 128) whose header names the color +/// space `space`; the bytes after the header differ from place to place. +fn icc_profile(space: &[u8; 4], len: usize) -> Vec { + let mut icc: Vec = (0..len).map(|i| (i % 251) as u8).collect(); + icc[..4].copy_from_slice(&u32::try_from(len).unwrap().to_be_bytes()); + icc[12..16].copy_from_slice(b"mntr"); + icc[16..20].copy_from_slice(space); + icc[36..40].copy_from_slice(b"acsp"); + icc +} + +/// `tiff` (little-endian) with an ICCProfile tag (34675, of type UNDEFINED) holding `icc`: its first +/// directory copied to the end of the file with the tag added in order. +fn tiff_with_icc(tiff: &[u8], icc: &[u8]) -> Vec { + let at = usize::try_from(u32::from_le_bytes(tiff[4..8].try_into().unwrap())).unwrap(); + let n = usize::from(u16::from_le_bytes([tiff[at], tiff[at + 1]])); + let mut entries: Vec> = tiff[at + 2..at + 2 + 12 * n].chunks(12).map(<[u8]>::to_vec).collect(); + let mut out = tiff.to_vec(); + if out.len() % 2 == 1 { + out.push(0); + } + let data = u32::try_from(out.len()).unwrap(); + out.extend(icc); + if out.len() % 2 == 1 { + out.push(0); + } + let i = entries.iter().position(|e| u16::from_le_bytes([e[0], e[1]]) > 34675).unwrap_or(n); + let count = u32::try_from(icc.len()).unwrap(); + entries.insert(i, [&34675u16.to_le_bytes()[..], &7u16.to_le_bytes(), &count.to_le_bytes(), &data.to_le_bytes()].concat()); + let ifd = u32::try_from(out.len()).unwrap(); + out[4..8].copy_from_slice(&ifd.to_le_bytes()); + out.extend(u16::try_from(n + 1).unwrap().to_le_bytes()); + out.extend(entries.concat()); + out.extend([0; 4]); + out +} + +/// A little-endian EXIF block (a TIFF header and one directory) giving Orientation `orientation`. +fn exif_block(orientation: u16) -> Vec { + let o = orientation.to_le_bytes(); + [b"II".as_slice(), &[0x2a, 0, 8, 0, 0, 0], &[1, 0], &[0x12, 0x01, 3, 0, 1, 0, 0, 0, o[0], o[1], 0, 0], &[0, 0, 0, 0]].concat() +} + +/// The ICC profile and the bits per sample of the PNG `im` is stored as. +fn stored_icc(d: &Document, im: &ImageObject) -> (Option>, u16) { + use image::ImageDecoder as _; + let blob = &d.images[&im.key]; + assert_eq!(blob.mime, "image/png"); + let mut dec = image::codecs::png::PngDecoder::new(std::io::Cursor::new(blob.bytes.as_slice())).unwrap(); + let color = dec.original_color_type(); + (dec.icc_profile().unwrap(), color.bits_per_pixel() / u16::from(color.channel_count())) +} + +/// A raster that import writes again as PNG keeps the gray or RGB ICC profile its file carries, +/// byte for byte, linked and as a data URL: a TIFF, turned or not, and a turned PNG and JPEG, with +/// 16-bit samples kept at 16 bits and the resolution kept beside the profile. A profile of another +/// color space than the written samples', one too short to be a profile, and one on a TIFF whose +/// pixels are read as RGBA by its own reader are left out, and the image still imports. +#[test] +fn a_raster_written_again_as_png_keeps_its_icc_profile() { + use image::{DynamicImage, ImageEncoder as _}; + let (rgb_icc, gray_icc, cmyk_icc) = (icc_profile(b"RGB ", 600), icc_profile(b"GRAY", 300), icc_profile(b"CMYK", 400)); + let rgb8 = DynamicImage::ImageRgb8(image::RgbImage::from_fn(3, 2, |x, y| image::Rgb([u8::try_from(x * 70 + y * 9).unwrap(), 200, 13]))); + let gray8 = DynamicImage::ImageLuma8(image::GrayImage::from_fn(3, 2, |x, y| image::Luma([u8::try_from(x * 80 + y * 7).unwrap()]))); + let rgb16 = DynamicImage::ImageRgb16(image::ImageBuffer::from_fn(3, 2, |x, y| { + let v = u16::try_from(x * 0x1111 + y * 0x2345).unwrap(); + image::Rgb([0x1000 + v, 0x8001 + v, 0xF0F3 - v]) + })); + let tiff_of = |img: &DynamicImage, icc: &[u8]| { + let mut out = Vec::new(); + let mut enc = image::codecs::tiff::TiffEncoder::new(std::io::Cursor::new(&mut out)); + enc.set_icc_profile(icc.to_vec()).unwrap(); + img.write_with_encoder(enc).unwrap(); + out + }; + let png = { + let mut out = Vec::new(); + let mut enc = image::codecs::png::PngEncoder::new(&mut out); + enc.set_icc_profile(rgb_icc.clone()).unwrap(); + enc.set_exif_metadata(exif_block(6)).unwrap(); + rgb16.write_with_encoder(enc).unwrap(); + out + }; + let jpg = { + let mut out = Vec::new(); + let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 95); + enc.set_icc_profile(rgb_icc.clone()).unwrap(); + rgb8.write_with_encoder(enc).unwrap(); + let exif = [b"Exif\0\0".as_slice(), &exif_block(6)].concat(); + let mut turned = out[..2].to_vec(); + turned.extend([0xff, 0xe1]); + turned.extend(u16::try_from(exif.len() + 2).unwrap().to_be_bytes()); + turned.extend(&exif); + turned.extend(&out[2..]); + turned + }; + let gray = [0, 0, 255, 255, 0, 0, 255, 255]; + let turned_gray = tiff_with_icc(&tiff_at(4, 2, 1, &gray, 6, Some((300, 150))), &gray_icc); + let gray_alpha = [0, 255, 0, 255, 255, 255, 255, 255, 0, 255, 0, 255, 255, 255, 255, 255]; + // (what, file, the ICC profile to keep, bits per sample, resolution) + type Case<'a> = (&'a str, Vec, Option<&'a [u8]>, u16, Option<(f64, f64)>); + let cases: Vec = vec![ + ("RGB TIFF", tiff_of(&rgb8, &rgb_icc), Some(&rgb_icc), 8, None), + ("gray TIFF", tiff_of(&gray8, &gray_icc), Some(&gray_icc), 8, None), + ("16-bit RGB TIFF", tiff_of(&rgb16, &rgb_icc), Some(&rgb_icc), 16, None), + ("gray TIFF, orientation 6, with a resolution", turned_gray, Some(&gray_icc), 8, Some((150.0, 300.0))), + ("16-bit RGB PNG, orientation 6", png, Some(&rgb_icc), 16, None), + ("JPEG, orientation 6", jpg, Some(&rgb_icc), 8, None), + ("RGB TIFF with a gray profile", tiff_of(&rgb8, &gray_icc), None, 8, None), + ("gray TIFF with an RGB profile", tiff_of(&gray8, &rgb_icc), None, 8, None), + ("RGB TIFF with a CMYK profile", tiff_of(&rgb8, &cmyk_icc), None, 8, None), + ("RGB TIFF with a profile too short to be one", tiff_of(&rgb8, &rgb_icc[..40]), None, 8, None), + ("gray TIFF with alpha, read as RGBA", tiff_with_icc(&tiff(4, 2, 2, &gray_alpha, 1), &rgb_icc), None, 8, None), + ]; + let dir = folder("icc"); + for (what, file, icc, bits, ppi) in cases { + std::fs::write(dir.join("photo.img"), &file).unwrap(); + let data = format!("data:;base64,{}", base64_encode(&file)); + for href in ["photo.img", data.as_str()] { + let what = format!("{what}, {}", &href[..href.len().min(12)]); + let (d, im) = import_one(&format!(r#""#), Some(&dir)); + assert_eq!(stored_icc(&d, &im), (icc.map(<[u8]>::to_vec), bits), "{what}"); + assert_eq!(stored_ppi(&d, &im), ppi, "{what}"); + } + } +} + /// A turned JPEG that a linked SVG file links to is turned too. #[test] fn a_turned_jpeg_linked_from_a_linked_svg_file_imports_upright() { 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 b39842e4fa..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; @@ -284,6 +285,63 @@ fn a_gaussian_blur_becomes_the_effect_with_its_radius() { assert_eq!(effects(&d)[0].params["radius"], json!(12.0)); } +/// A blur that differs by direction in the document (standard deviations that differ, or an even +/// one in a user space scaled unevenly or skewed) is kept as an SVG filter, which draws it as it +/// is, not as an even Gaussian Blur. In a turned, flipped or evenly scaled user space an even blur +/// stays the effect. +#[test] +fn a_blur_that_differs_by_direction_is_kept_as_its_filter() { + let ids = |body: &str| { + let (d, w) = open(body); + assert!(w.is_empty(), "{w:?}"); + effects(&d).iter().map(|e| e.id.clone()).collect::>() + }; + let blur = |sd: &str, transform: &str| { + format!( + r##""## + ) + }; + assert_eq!(ids(&blur("4 1", "translate(0)")), ["svg.filter"]); + assert_eq!(ids(&blur("3", "scale(1 4)")), ["svg.filter"]); + assert_eq!(ids(&blur("3", "skewX(30)")), ["svg.filter"]); + assert_eq!(ids(&blur("3", "rotate(30) scale(2)")), ["blur.gaussian"]); + assert_eq!(ids(&blur("3", "scale(-2 2)")), ["blur.gaussian"]); + let shadow = |sd: &str| { + format!( + r##""## + ) + }; + assert_eq!(ids(&shadow("3 1")), ["svg.filter"]); + assert_eq!(ids(&shadow("3")), ["stylize.dropShadow"]); +} + +/// An SVG filter's blur in a user space scaled unevenly is written live and opens again as the +/// same effect, which blurs more along the stretched axis, not as an even Gaussian Blur. +#[test] +fn an_exported_blur_in_a_stretched_user_space_opens_as_the_same_effect() { + let xml = r#""#; + let mut d = Document::new(200.0, 120.0); + let mut n = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(60.0, 40.0, 140.0, 80.0)), + Appearance::basic(Paint::solid(Color::rgb(0.9, 0.1, 0.1)), Paint::None, 0.0), + ); + let params = json!({ "xml": xml, "scale": 2.0, "origin": [0.0, 0.0], "axes": [0.5, 0.0, 0.0, 2.0] }); + n.appearance.effects = vec![Effect { id: "svg.filter".into(), params, visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let out = export(&d, &ExportOptions::default()); + assert!(out.contains(">(), ["svg.filter"], "{out}"); + let num = |v: &serde_json::Value| v.as_f64().unwrap(); + let axes: Vec = fx[0].params["axes"].as_array().unwrap().iter().map(num).collect(); + assert!(axes.iter().zip([0.5, 0.0, 0.0, 2.0]).all(|(a, b)| (a - b).abs() < 1e-6), "{axes:?}"); + assert_similar(&render_artboard(&d), &render_artboard(&back), 40.0, 0.02); +} + /// `color-interpolation-filters` (SVG 1.1 §15.7.6, initially linearRGB: /// https://www.w3.org/TR/SVG11/painting.html#ColorInterpolationFiltersProperty) picks whether the /// blur mixes colours in linear light; sRGB, on the primitive or the filter, keeps them as they diff --git a/crates/svg/tests/it/import_text.rs b/crates/svg/tests/it/import_text.rs index fa91f8d162..c8a1cfd4ed 100644 --- a/crates/svg/tests/it/import_text.rs +++ b/crates/svg/tests/it/import_text.rs @@ -974,7 +974,7 @@ fn absolutely_placed_right_to_left_characters_sit_on_their_own_x() { vec![(0..2, 20.0), (3..4, 100.0), (4..5, 160.0)], ), ]; - let unplaced = |w: &[String]| w.iter().any(|w| w.contains("absolutely placed")); + let unplaced = |w: &[String]| w.iter().any(|w| w.contains("point type objects")); for (body, share, chunks) in cases { let (d, w) = import_with_report(&svg(&body)).unwrap(); assert!(!unplaced(&w), "{body}: {w:?}"); @@ -988,12 +988,82 @@ fn absolutely_placed_right_to_left_characters_sit_on_their_own_x() { assert!(close(left, want, 0.05), "{body}: the chunk {bytes:?} spans {left}..{right}, so it does not start at {want}"); } } - // A left-to-right character between right-to-left ones is drawn right next to the one after - // it, with no kerning between them: that one keeps its place in the line, and a warning says so. - let (d, w) = import_with_report(&svg(r#"אbג"#)).unwrap(); - assert!(unplaced(&w), "{w:?}"); - let (left, right) = chunk_edges(only_text(&d), 2..3); - assert!(close(right, 160.0, 0.05), "b spans {left}..{right}"); +} + +/// The document-space edges of character `ch`, in whichever text of `d` holds it (as +/// [`chunk_edges`] measures them), and the y it is drawn at (its baseline moved by its baseline +/// shift). +fn char_edges(d: &Document, ch: char) -> (f64, f64, f64) { + let t = texts(d).into_iter().find(|t| t.plain_text().contains(ch)).unwrap_or_else(|| panic!("no text holds {ch}")); + let at = t.plain_text().find(ch).unwrap(); + let (left, right) = chunk_edges(t, at..at + ch.len_utf8()); + let shift = t.runs.iter().find(|r| r.text.contains(ch)).unwrap().style.baseline_shift; + let y = layout(FontDb::global(), t).glyphs.iter().find(|g| g.byte == at).map(|g| (t.xf * g.origin).y).unwrap() - shift; + (left, right, y) +} + +/// SVG 2 › Text (https://www.w3.org/TR/SVG2/text.html): each absolute position starts a chunk, +/// and bidi reordering happens only within a chunk. A left-to-right character drawn right before a +/// right-to-left one has no kerning between them in one text object, so such a text imports as a +/// group of point type objects, each character on its own x. +#[test] +fn absolutely_placed_characters_one_object_cannot_place_import_as_a_group() { + // (markup, the characters of its objects in order, each character with the x its right edge + // sits on and its baseline) + type Case = (&'static str, &'static str, Vec<(char, f64, f64)>); + let cases: Vec = vec![ + ( + r#"אbג"#, + "אbג", + vec![('א', 100.0, 80.0), ('b', 160.0, 80.0), ('ג', 220.0, 80.0)], + ), + ( + r#"אbגd"#, + "אbגd", + vec![('א', 100.0, 80.0), ('b', 160.0, 80.0), ('ג', 220.0, 80.0), ('d', 280.0, 80.0)], + ), + // x values that decrease. + ( + r#"אbג"#, + "אbג", + vec![('א', 220.0, 80.0), ('b', 160.0, 80.0), ('ג', 100.0, 80.0)], + ), + // On a second line, and with a baseline of its own. + ( + r#"אבגbד"#, + "אבגbד", + vec![('א', 40.0, 40.0), ('ג', 100.0, 80.0), ('b', 160.0, 80.0), ('ד', 220.0, 90.0)], + ), + ]; + for (body, text, chars) in cases { + let (d, w) = import_with_report(&svg(body)).unwrap(); + assert!(w.iter().any(|w| w.contains("point type objects in a group")), "{body}: {w:?}"); + let top = d.layers[0].children().unwrap(); + assert_eq!(top.len(), 1, "{body}: {top:?}"); + assert_eq!(top[0].name.as_deref(), Some("t"), "{body}: the group takes the element's id"); + let NodeKind::Group { children, clip: false } = &top[0].kind else { panic!("{body}: {:?}", top[0].kind) }; + assert!(children.len() > 1 && children.iter().all(|c| matches!(c.kind, NodeKind::Text(_))), "{body}: {children:?}"); + let all: String = texts(&d).iter().map(|t| t.plain_text().replace('\n', "")).collect(); + assert_eq!(all, text, "{body}: every character once, in order"); + for (ch, x, y) in chars { + let (left, right, base) = char_edges(&d, ch); + assert!(close(right, x, 0.05), "{body}: {ch} spans {left}..{right}, not ending at {x}"); + assert!(close(base, y, 1e-6), "{body}: {ch} sits on {base}, not {y}"); + } + } + // Placed characters one object can place stay one object, also when their x values decrease. + for (body, chars) in [ + (r#"אbc"#, [('א', 100.0), ('b', 160.0), ('c', 220.0)]), + (r#"אבג"#, [('א', 220.0), ('ב', 160.0), ('ג', 100.0)]), + ] { + let (d, w) = import_with_report(&svg(body)).unwrap(); + assert!(!w.iter().any(|w| w.contains("point type objects")), "{body}: {w:?}"); + only_text(&d); + for (ch, x) in chars { + let (left, right, _) = char_edges(&d, ch); + assert!(close(right, x, 0.05), "{body}: {ch} spans {left}..{right}, not ending at {x}"); + } + } } #[test] 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 005a03e0fa..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}; @@ -299,6 +300,109 @@ fn a_stained_instance_with_a_geometry_effect_keeps_its_stain() { } } +/// Symbol "Moved": a red square whose Transform effect moves it `dx` pt right. +fn add_moved_symbol(d: &mut Document, square: Rect, dx: f64) { + let mut art = Node::path(d.alloc_id(), shapes::rectangle(square), Appearance::basic(Paint::solid(Color::rgb8(255, 0, 0)), Paint::None, 0.0)); + art.appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": dx}), visible: true }); + d.symbols.push(Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(art) }); +} + +/// Instances of a symbol whose art has a geometry effect are written as their art placed by the +/// instance and then baked, where the canvas draws it: moved by the instance, doubled in width +/// (the effect still moves it 100 pt, not 200 pt) and turned. They use no ``, while the +/// instances of a symbol without effects still share one. +#[test] +fn symbol_art_effects_are_written_where_the_canvas_draws_them() { + let mut d = symbol_doc(0.0, &[Affine::translate((30.0, 100.0)), Affine::translate((60.0, 100.0))]); + add_moved_symbol(&mut d, Rect::new(10.0, 10.0, 20.0, 20.0), 100.0); + instance(&mut d, "Moved", Affine::IDENTITY); + instance(&mut d, "Moved", Affine::translate((0.0, 20.0)) * Affine::scale_non_uniform(2.0, 1.0)); + instance(&mut d, "Moved", Affine::translate((-60.0, 40.0)) * Affine::rotate(0.5)); + let svg = export(&d, &ExportOptions::default()); + assert_eq!((svg.matches("