diff --git a/.github/workflows/freebsd.yml b/.github/workflows/freebsd.yml index 007fcfec09..c74a3e83ab 100644 --- a/.github/workflows/freebsd.yml +++ b/.github/workflows/freebsd.yml @@ -31,3 +31,8 @@ jobs: require-craft-fonts: true craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 run-package-check: true + # The test builds of this workspace's largest crates (engine, ui-egui) need more than the + # VM's 12 GB when two compile at once: the build was killed (exit 137) every night with + # four jobs and again with two. One rustc at a time; it still uses every core. + cargo-build-extra-args: "-j 1" + cargo-test-extra-args: "-j 1" diff --git a/Cargo.lock b/Cargo.lock index 476af0dc89..d780911c11 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,143 @@ 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=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +dependencies = [ + "encoding_rs", + "image", + "kurbo 0.13.1", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-mime" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +dependencies = [ + "chrono", + "craft-codepage", + "encoding_rs", +] + [[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=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1054,10 +1224,18 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-plotter" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=9101c4fc226f5f111b5a890a6c5c19bf3991fd76#9101c4fc226f5f111b5a890a6c5c19bf3991fd76" +dependencies = [ + "thiserror 2.0.21", +] + [[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", @@ -1071,7 +1249,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", @@ -1080,13 +1258,48 @@ dependencies = [ ] [[package]] -name = "craft-svg" +name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2" +source = "git+https://github.com/storytold/craft-libs?rev=a80c0f25f1c4767374a27a444fbf95e3e8162e14#a80c0f25f1c4767374a27a444fbf95e3e8162e14" dependencies = [ - "craft-xml", "flate2", "kurbo 0.13.1", +] + +[[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=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" +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=431f704478962677ec47e512754464d372901830#431f704478962677ec47e512754464d372901830" +dependencies = [ + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830)", + "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", @@ -1094,10 +1307,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", @@ -1118,7 +1349,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", @@ -1145,7 +1376,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", @@ -1167,7 +1398,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", @@ -1178,7 +1409,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", ] @@ -1186,9 +1417,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", ] @@ -1666,7 +1908,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]] @@ -1704,6 +1946,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" @@ -2043,16 +2301,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" @@ -2286,7 +2534,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=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" dependencies = [ "brotli", "hayro-postscript", @@ -2295,7 +2543,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=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -2313,7 +2561,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=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -2331,12 +2579,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=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" [[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=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" dependencies = [ "flate2", "hayro-ccitt", @@ -2346,7 +2594,7 @@ dependencies = [ "rustc-hash 2.1.3", "smallvec", "stringprep", - "zune-jpeg 0.5.15", + "zune-jpeg", ] [[package]] @@ -2731,14 +2979,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]] @@ -2828,6 +3077,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" @@ -2991,7 +3246,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", @@ -3023,7 +3278,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", @@ -3129,13 +3384,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=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" dependencies = [ "base64 0.22.1", "bumpalo", "flate2", "float-cmp", - "gif 0.14.2", + "gif", "image-webp", "imagesize 0.14.0", "indexmap", @@ -3150,7 +3405,7 @@ dependencies = [ "tiny-skia-path 0.12.0", "xmp-writer", "yoke", - "zune-jpeg 0.5.15", + "zune-jpeg", ] [[package]] @@ -3189,6 +3444,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" @@ -3232,7 +3493,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=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -3388,6 +3649,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" @@ -3915,7 +4198,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]] @@ -4338,21 +4621,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" @@ -4437,7 +4720,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -4677,15 +4960,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]] @@ -4695,7 +4975,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", @@ -4703,7 +4983,7 @@ dependencies = [ "svgtypes 0.16.1", "tiny-skia 0.12.0", "usvg 0.48.1", - "zune-jpeg 0.5.15", + "zune-jpeg", ] [[package]] @@ -4815,7 +5095,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -4874,7 +5154,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5723,6 +6003,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" @@ -5733,7 +6019,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix 1.1.6", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5805,7 +6091,7 @@ dependencies = [ "half", "quick-error 2.0.1", "weezl 0.1.12", - "zune-jpeg 0.5.15", + "zune-jpeg", ] [[package]] @@ -6412,8 +6698,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", ] @@ -6441,6 +6727,8 @@ name = "vectorcraft-cad" version = "0.24.1" dependencies = [ "craft-dxf", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "craft-plotter", "image", "kurbo 0.13.1", "serde_json", @@ -6493,7 +6781,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", @@ -6504,16 +6794,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", @@ -6534,10 +6825,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", @@ -6547,7 +6842,6 @@ dependencies = [ "log", "proptest", "rayon", - "roxmltree 0.21.2", "rustix 1.1.6", "ruzstd", "same-file", @@ -6555,6 +6849,7 @@ dependencies = [ "serde_json", "skrifa 0.47.0", "thiserror 2.0.21", + "tiff", "vectorcraft-affinity", "vectorcraft-apischema", "vectorcraft-brush", @@ -6574,10 +6869,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", ] @@ -6586,11 +6882,13 @@ 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-ps", + "craft-stream-codecs", "encoding_rs", "fax", "flate2", - "hayro-ccitt", "image", "kurbo 0.13.1", "memchr", @@ -6614,6 +6912,7 @@ dependencies = [ name = "vectorcraft-format" version = "0.24.1" dependencies = [ + "craft-gzip", "craft-vectorcraft-format", "flate2", "proptest", @@ -6621,6 +6920,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", + "vectorcraft-brush", "vectorcraft-doc", "vectorcraft-geom 0.24.1", "vectorcraft-testkit", @@ -6662,6 +6962,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", @@ -6681,6 +6982,8 @@ 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", "vectorcraft-brush", @@ -6720,7 +7023,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", @@ -6731,7 +7037,6 @@ dependencies = [ "md-5", "objc2-core-foundation", "objc2-core-graphics", - "roxmltree 0.21.2", "serde", "serde_json", "sha2", @@ -6746,15 +7051,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", @@ -6772,16 +7076,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", @@ -6811,18 +7116,21 @@ 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-mime", "craft-svg", + "data-url", "flate2", "image", "kurbo 0.13.1", "proptest", - "resvg 0.45.1", "serde", "serde_json", "simplecss", "skrifa 0.47.0", "svgtypes 0.16.1", "thiserror 2.0.21", + "unicode-bidi", "usvg 0.48.1", "vectorcraft-brush", "vectorcraft-color", @@ -6838,8 +7146,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", @@ -6877,6 +7185,7 @@ dependencies = [ name = "vectorcraft-three-d" version = "0.24.1" dependencies = [ + "proptest", "vectorcraft-geom 0.24.1", "vectorcraft-pathops 0.24.1", ] @@ -6885,7 +7194,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", @@ -6902,6 +7211,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", @@ -6915,6 +7225,8 @@ name = "vectorcraft-ui-egui" 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", @@ -7591,7 +7903,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]] @@ -7869,7 +8181,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", @@ -7884,6 +8196,7 @@ dependencies = [ "windows", "windows-core", "windows-implement", + "windows-numerics", "xml", ] @@ -8343,12 +8656,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" @@ -8356,12 +8663,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]] @@ -8370,7 +8677,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]] @@ -8379,7 +8686,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 c7856d589e..891cce208d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,27 +11,40 @@ 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 = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e", default-features = false, features = ["interpret", "write"] } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd", features = ["serde"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } # 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"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } # 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-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "9101c4fc226f5f111b5a890a6c5c19bf3991fd76" } +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 = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "a80c0f25f1c4767374a27a444fbf95e3e8162e14", default-features = false, features = ["write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd", features = ["egui"] } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -89,10 +102,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. @@ -104,18 +119,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 @@ -128,6 +134,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" @@ -171,13 +184,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 = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" } 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/README.md b/README.md index 7e49943a31..b04c91e066 100644 --- a/README.md +++ b/README.md @@ -252,11 +252,12 @@ speaks English, German, Japanese, Korean, Vietnamese, Traditional and Simplified The scores are self-assessed from our code against public documentation; [target-app-parity.md](docs/target-app-parity.md#how-this-was-measured-2026-10-10) explains how far to trust them. +All 57 approximated Photoshop-style raster filters are available. The Effect Gallery includes filter thumbnails and an in-dialog preview. + **What's missing:** - reliable exchange of .ai files (layer structure in real files; the editing copy a save writes keeps live effects only on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (see [docs/file-format-parity.md](docs/file-format-parity.md)), leaves out other objects' effects other than geometry effects, and writes live objects as their art); - an interaction-fidelity pass covering every tool's modifiers and small behaviours; - 3D and Materials beyond the initial live Revolve (Extrude & Bevel, Inflate, Rotate, materials); -- filter thumbnails and a preview area inside the Effect Gallery (the gallery itself and all 57 Photoshop-style raster filters, approximated, are in); - CJK composition for vertical type (vertical type itself has initial support, with a Japanese interface); - scripting, and the rest of Variables (image and graph kinds, dataset import); - generative AI features. diff --git a/ROADMAP.md b/ROADMAP.md index 346c532277..4358817b60 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -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 @@ -124,12 +124,20 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-11-14: Built-in symbol library Weather Icons: adds a sixth procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Sun, Moon, Cloud, Rain, Thunder, Snow) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged. +- 2026-11-14: Built-in Tech Circuit brush library: Circuit Trace (chamfered art with 45-degree elbows and terminal pads), Bus Lines (parallel conductor pattern) and Terminal Nodes (repeating solder pads, test points and leads), all original geometry generated in code. Ten built-in brush libraries; G5 remaining estimate 3–13 h (estimated), headline numbers unchanged. + - 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged. - 2026-11-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`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. @@ -137,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. @@ -221,6 +232,8 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| +| 2026-11-15 | minor | Graphic Styles: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h). | +| 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. | | 2026-11-14 | minor | Gujarati (#6613): contributor proofreading completed for all 387 additions, with 11 wording corrections; 4,673 reviewed catalog rows. Status/error messages remain partial; web selection requires a bundled Gujarati face. Scores and estimates unchanged. | | 2026-11-10 | minor | Tidy-up, no content change: the unheaded change bullets at the top of the file and a revision row inside the headline-numbers table move to this table under their commit dates. Scores and estimates unchanged. | | 2026-11-10 | minor | Raster effects: Effect Gallery thumbnails and an in-dialog preview (an original drawing through each filter). Features-table Raster effects 85% → 88%, hours 1–2 → none. Headline numbers unchanged, so the progress log is 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-web/src/locks.rs b/apps/vectorcraft-web/src/locks.rs index 7eb2e6cdb7..dffd87868a 100644 --- a/apps/vectorcraft-web/src/locks.rs +++ b/apps/vectorcraft-web/src/locks.rs @@ -8,23 +8,40 @@ //! Pages that aren't secure (plain `http://` other than localhost) and older browsers have none: //! heartbeats alone decide there. +#[cfg(target_arch = "wasm32")] use std::cell::RefCell; +#[cfg(target_arch = "wasm32")] use std::collections::{BTreeMap, BTreeSet}; +#[cfg(target_arch = "wasm32")] use std::sync::{Arc, Mutex}; +#[cfg(target_arch = "wasm32")] use js_sys::{Function, Promise, Reflect}; +#[cfg(target_arch = "wasm32")] use vectorcraft_engine::cmd::recovery::Hold; +#[cfg(target_arch = "wasm32")] use wasm_bindgen::JsCast as _; +#[cfg(target_arch = "wasm32")] use wasm_bindgen::JsValue; +#[cfg(target_arch = "wasm32")] use wasm_bindgen::closure::Closure; /// How often the snapshot of the locks held is refreshed (ms). +#[cfg(target_arch = "wasm32")] const REFRESH_MS: i32 = 10_000; /// How old a snapshot may be and still be trusted (ms). A lock asked for after the snapshot was /// taken comes with a heartbeat, which stays fresh for at least three minutes, so anything under /// that is safe; an older snapshot counts every area as held. const FRESH_MS: f64 = 60_000.0; +/// Whether a snapshot asked for at `asked` can still be trusted at `now`, both in ms on +/// [`vectorcraft_ui_egui::now_ms`]'s clock: it is at most [`FRESH_MS`] old, and not stamped later +/// than `now`. +fn trusted(asked: f64, now: f64) -> bool { + (0.0..=FRESH_MS).contains(&(now - asked)) +} + +#[cfg(target_arch = "wasm32")] thread_local! { /// What releases each lock this tab holds, by name: it resolves the promise the lock is held /// by (wasm runs on one thread). @@ -32,26 +49,31 @@ thread_local! { } /// The locks of the page, named ``. +#[cfg(target_arch = "wasm32")] #[derive(Clone)] pub struct WebLocks { prefix: &'static str, - /// The areas whose locks were held at the last snapshot, and when it was asked for (ms since - /// the epoch). `navigator.locks.query()` is asynchronous, so the snapshot is refreshed every + /// The areas whose locks were held at the last snapshot, and when it was asked for (ms on + /// [`vectorcraft_ui_egui::now_ms`]'s monotonic clock, which a change to the system clock does + /// not move). `navigator.locks.query()` is asynchronous, so the snapshot is refreshed every /// [`REFRESH_MS`] and read from here. seen: Arc)>>, } /// `navigator.locks`, if the browser has it here. +#[cfg(target_arch = "wasm32")] fn manager() -> Option { let locks = Reflect::get(&web_sys::window()?.navigator(), &"locks".into()).ok()?; locks.is_object().then_some(locks) } /// Method `name` of `obj`. +#[cfg(target_arch = "wasm32")] fn method(obj: &JsValue, name: &str) -> Option { Reflect::get(obj, &name.into()).ok()?.dyn_into().ok() } +#[cfg(target_arch = "wasm32")] impl WebLocks { /// The page's Web Locks with a first snapshot of them, kept fresh from then on; `None` when /// the browser has none or won't say which are held (heartbeats alone decide then). @@ -75,7 +97,7 @@ impl WebLocks { /// Take a new snapshot of the locks held. async fn refresh(&self) -> Option<()> { let m = manager()?; - let asked = js_sys::Date::now(); + let asked = vectorcraft_ui_egui::now_ms(); let query: Promise = method(&m, "query")?.call0(&m).ok()?.dyn_into().ok()?; let snapshot = wasm_bindgen_futures::JsFuture::from(query).await.ok()?; let held = js_sys::Array::from(&Reflect::get(&snapshot, &"held".into()).ok()?); @@ -91,7 +113,7 @@ impl WebLocks { /// Does a tab hold `area`'s lock? Yes when the last snapshot is too old to tell. pub fn held(&self, area: &str) -> bool { let seen = self.seen.lock().unwrap_or_else(|e| e.into_inner()); - js_sys::Date::now() - seen.0 > FRESH_MS || seen.1.contains(area) + !trusted(seen.0, vectorcraft_ui_egui::now_ms()) || seen.1.contains(area) } /// Hold `area`'s lock until the returned hold is dropped (or the page goes). @@ -110,8 +132,10 @@ impl WebLocks { } /// A lock this tab holds (by name), released when dropped. +#[cfg(target_arch = "wasm32")] struct LockHold(String); +#[cfg(target_arch = "wasm32")] impl Drop for LockHold { fn drop(&mut self) { if let Some(resolve) = RELEASE.with(|r| r.borrow_mut().remove(&self.0)) { @@ -120,3 +144,24 @@ impl Drop for LockHold { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_snapshot_is_trusted_for_a_minute() { + assert!(trusted(1_000.0, 1_000.0)); + assert!(trusted(1_000.0, 1_000.0 + FRESH_MS)); + assert!(!trusted(1_000.0, 1_001.0 + FRESH_MS)); + // Before the first snapshot every area counts as held. + assert!(!trusted(f64::NEG_INFINITY, 0.0)); + } + + #[test] + fn a_snapshot_stamped_later_than_now_is_not_trusted() { + // A clock that went back reads an old snapshot as taken in the future. + assert!(!trusted(5_000_000.0, 1_000.0)); + assert!(!trusted(1_001.0, 1_000.0)); + } +} diff --git a/apps/vectorcraft-web/src/main.rs b/apps/vectorcraft-web/src/main.rs index 3808c281f9..457d8d4640 100644 --- a/apps/vectorcraft-web/src/main.rs +++ b/apps/vectorcraft-web/src/main.rs @@ -25,7 +25,7 @@ mod api; mod fonts; #[cfg(any(target_arch = "wasm32", test))] mod keys; -#[cfg(target_arch = "wasm32")] +#[cfg(any(target_arch = "wasm32", test))] mod locks; #[cfg(any(target_arch = "wasm32", test))] mod pencil; diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index 126b671877..dddaf0a91e 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -108,37 +108,14 @@ impl eframe::App for App { self.app.start_pending_update(); #[cfg(target_os = "macos")] super::mac_cursor::release(); + // Dropping the app can wait for the clipboard handles to let go: the windows leave the + // screen first (`quit_windows`). #[cfg(not(any(target_os = "macos", windows)))] - hide_before_teardown(self.winit_window.as_deref()); + super::quit_windows::before_teardown(self.winit_window.as_deref()); end_before_teardown(self.frames); } } -/// The main window as [`hide_before_teardown`] sees it. -#[cfg(not(any(target_os = "macos", windows)))] -pub(crate) trait QuittingWindow { - fn hide(&self); -} - -#[cfg(not(any(target_os = "macos", windows)))] -impl QuittingWindow for winit::window::Window { - fn hide(&self) { - self.set_visible(false); - } -} - -/// On Linux and the BSDs, hide the main window before eframe drops the app. Dropping the app waits -/// up to [`vectorcraft_ui_egui::CLIPBOARD_PROBE_STOP_WAIT`] for the clipboard handles to let go, and -/// the window would stay on screen for that time. The window is hidden, not closed: the Wayland -/// clipboard reads text on the window's connection. winit hides X11 windows (XWayland included) and -/// cannot hide a Wayland window. -#[cfg(not(any(target_os = "macos", windows)))] -pub(crate) fn hide_before_teardown(window: Option<&W>) { - if let Some(window) = window { - window.hide(); - } -} - impl App { /// The frame's times for the hang report, and its last stage ([`hang_beacon::after_frame`]): a /// focused, shown window whose windows had input waits for the renderer and the next frame, diff --git a/apps/vectorcraft/src/clipboard.rs b/apps/vectorcraft/src/clipboard.rs index 17b9327956..3568b4683e 100644 --- a/apps/vectorcraft/src/clipboard.rs +++ b/apps/vectorcraft/src/clipboard.rs @@ -11,13 +11,14 @@ //! backend reads the compositor's clipboard (X11 through XWayland only sees what X11 apps //! copied), falling back to X11 where the compositor lacks the protocol, and where there is no //! X11 either (a Flatpak on GNOME) to the compositor's core protocol on the window's connection: -//! Copy offers SVG (`image/svg+xml`), PNG (`image/png`) and text together, and Paste reads SVG, -//! text and PNG. A clipboard that can't be opened is tried again after a wait that grows to a -//! minute, not each time Paste asks. On Linux and the BSDs a read waits 2 s at most for the app +//! Copy offers SVG (`image/svg+xml`), PNG (`image/png`) and text together, and Paste reads copied +//! files (`text/uri-list`), SVG, text and PNG. A clipboard that can't be opened is tried again +//! after a wait that grows to a minute, not each time Paste asks. On Linux and the BSDs a read waits 2 s at most for the app //! that copied to send its data (a bitmap 10 s), and until that app answers, later reads fail at //! once; a paste then waits for that read's answer off the UI thread. //! - Everywhere: files copied in a file manager paste as the first one that is art (SVG, PDF, EPS, -//! a metafile or a bitmap), before the clipboard's other formats (the files' paths as text). +//! a metafile or a bitmap), before the clipboard's other formats (the files' paths as text). A +//! file of more than 64 MiB is skipped before it is read. use std::io::{Cursor, Read}; use std::path::PathBuf; @@ -144,9 +145,28 @@ fn dib_image(dib: &[u8]) -> Option { Some(img) } +/// The most bytes a paste takes from another app (untrusted data), VectorCraft's own limit: a copied +/// file of more is skipped, and on Wayland a read of more fails. +const MAX_BYTES: usize = 64 << 20; + /// The first of `paths` (files copied in a file manager) that pastes as one of `mimes`, read -/// whole. Only its first bytes are read to tell, so other files cost little. +/// whole, at most [`MAX_BYTES`]. Only its first bytes are read to tell, so other files cost little. 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() { @@ -164,22 +184,164 @@ fn copied_file(paths: Vec, mimes: &[&'static str]) -> Option { if !std::fs::metadata(&path).ok()?.is_file() { return None; } + let mut file = std::fs::File::open(&path).ok()?; + // The file opened may not be the one looked at: its size is checked before any read. + let meta = file.metadata().ok()?; + if !meta.is_file() || meta.len() > limit as u64 { + return None; + } let mut head = Vec::with_capacity(FILE_HEAD); - std::fs::File::open(&path).ok()?.take(FILE_HEAD as u64).read_to_end(&mut head).ok()?; + (&mut file).take(FILE_HEAD as u64).read_to_end(&mut head).ok()?; let mime = file_flavour(&path.to_string_lossy(), &head, mimes)?; - let data = std::fs::read(&path).ok()?; + let data = read_rest(file, head, limit)?; (!data.is_empty()).then_some(Flavour { mime, data }) }) } +/// `data` (the first bytes read of `file`) followed by the rest of `file`, or `None` when they come +/// to more than `limit` bytes, as when the file grew after its size was checked. At most one byte +/// past `limit` is read. +fn read_rest(file: impl Read, mut data: Vec, limit: usize) -> Option> { + let more = (limit + 1).saturating_sub(data.len()); + file.take(more as u64).read_to_end(&mut data).ok()?; + (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; + +/// The local files a `text/uri-list` names, in order ([`file_uri_path`]). Each line holds one URI +/// and a line that starts with `#` is a comment (RFC 2483, section 5); lines end in CRLF or LF. +/// Lines that are not UTF-8 and URIs that don't name a local file are skipped. A list of more than +/// [`MAX_URIS`] URIs names none. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn uri_list_paths(list: &[u8]) -> Vec { + let uris: Vec<&[u8]> = list + .split(|&b| b == b'\n') + .map(|line| line.strip_suffix(b"\r").unwrap_or(line)) + .filter(|line| !line.is_empty() && !line.starts_with(b"#")) + .take(MAX_URIS + 1) + .collect(); + if uris.len() > MAX_URIS { + return vec![]; + } + uris.into_iter().filter_map(|uri| file_uri_path(std::str::from_utf8(uri).ok()?)).collect() +} + +/// The local files GNOME Files' `x-special/gnome-copied-files` names: a first line of `copy` or +/// `cut`, then one URI a line, read as [`uri_list_paths`] reads them. A paste places the files' +/// art either way and leaves the files where they are. No files when the first line is neither. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn gnome_copied_paths(list: &[u8]) -> Vec { + let (action, uris) = match list.iter().position(|&b| b == b'\n') { + Some(end) => (list.get(..end).unwrap_or_default(), list.get(end + 1..).unwrap_or_default()), + None => (list, &[][..]), + }; + match action.strip_suffix(b"\r").unwrap_or(action) { + b"copy" | b"cut" => uri_list_paths(uris), + _ => vec![], + } +} + +/// The absolute path a `file:` URI names on this machine: `file:/path`, `file:///path` or +/// `file://localhost/path` (RFC 8089, section 2; scheme and host in any letter case), its percent +/// escapes decoded once (RFC 3986, section 2.1) and a fragment (`#…`) left out. None for another +/// scheme, another host, a relative path, a query (`?…`), a bad escape, an escaped NUL or a path +/// that is not UTF-8 once decoded. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn file_uri_path(uri: &str) -> Option { + let uri = uri.trim_matches(|c: char| c.is_ascii_whitespace()); + let uri = uri.split_once('#').map_or(uri, |(before, _)| before); + if uri.contains('?') { + return None; + } + let scheme = uri.get(..5).filter(|s| s.eq_ignore_ascii_case("file:"))?; + let rest = uri.get(scheme.len()..)?; + let path = match rest.strip_prefix("//") { + Some(authority_and_path) => { + let slash = authority_and_path.find('/')?; + let host = authority_and_path.get(..slash)?; + if !host.is_empty() && !host.eq_ignore_ascii_case("localhost") { + return None; + } + authority_and_path.get(slash..)? + } + None => rest.starts_with('/').then_some(rest)?, + }; + let mut bytes = Vec::with_capacity(path.len()); + let mut it = path.bytes(); + while let Some(b) = it.next() { + if b == b'%' { + let hex = |d: Option| char::from(d?).to_digit(16); + let (hi, lo) = (hex(it.next())?, hex(it.next())?); + bytes.push(u8::try_from(hi * 16 + lo).ok()?); + } else { + bytes.push(b); + } + } + if bytes.contains(&0) { + return None; + } + String::from_utf8(bytes).ok().map(PathBuf::from) +} + #[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 @@ -266,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(|| { @@ -286,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 @@ -623,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)] @@ -637,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, @@ -709,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 { @@ -1094,7 +1292,9 @@ mod portable { } } - /// Files copied in a file manager (none where the backend can't read a file list). + /// Files copied in a file manager, read through arboard. The Wayland core protocol reads + /// its file list with the rest of a paste + /// ([`DataClipboard::read`](super::wayland::DataClipboard::read)). fn file_list(&mut self) -> Vec { match self { Self::Arboard(cb) => cb.read(Request::Files).files(), @@ -1233,8 +1433,9 @@ mod portable { } /// Text and copied files are read here, and work that reads arboard's image comes back. On - /// the Wayland core protocol the first of `mimes` the clipboard offers is read: text here, - /// SVG and PNG by the work that comes back, which waits [`IMAGE_WAIT`] at most. + /// the Wayland core protocol the copied files, else the first of `mimes` the clipboard + /// offers, is read: text here, file lists, SVG and PNG by the work that comes back, which + /// waits [`IMAGE_WAIT`] at most. fn read_now_or_later(&mut self, mimes: &[&'static str]) -> Option { let cb = self.cb(Asker::User).ok()?; #[cfg(target_os = "linux")] @@ -1334,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 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. + /// 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 or copied files. fn has(&mut self, mimes: &[&'static str]) -> bool { #[cfg(target_os = "macos")] if super::mac::has(mimes) { @@ -1348,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) } } @@ -1512,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() { @@ -1784,12 +2020,13 @@ mod portable { /// window's own Wayland connection: what Copy and Paste use where the compositor lacks the /// data-control protocol arboard needs (GNOME) and there is no X11 to fall back on (the Flatpak on /// a Wayland session). A Copy offers its SVG as `image/svg+xml`, its PNG as `image/png` and its -/// text under each of [`TEXT_TYPES`]; Paste reads the clipboard's SVG, text and PNG, and the paste -/// check looks at the types offered without reading any data. The protocol gives the clipboard to -/// the window with the keyboard focus only. A worker thread handles the protocol's events and -/// starts a thread for each paste of a Copy's data by another app ([`MAX_SENDS`] at once). Reads -/// run on another worker and take [`MAX_BYTES`] at most; text waits [`LOAD_WAIT`] at most, SVG and -/// PNG as long as a paste's bitmap from arboard. A read that gets no answer in its wait is kept for +/// text under each of [`TEXT_TYPES`]; Paste reads the files a file manager copied +/// ([`FILE_LISTS`]), then the clipboard's SVG, text and PNG, and the paste check looks at the types +/// offered without reading any data. The protocol gives the clipboard to the window with the +/// keyboard focus only. A worker thread handles the protocol's events and starts a thread for each +/// paste of a Copy's data by another app ([`MAX_SENDS`] at once). Reads run on another worker and +/// take [`MAX_BYTES`] at most; text waits [`LOAD_WAIT`] at most, file lists, SVG and PNG as long as +/// a paste's bitmap from arboard. A read that gets no answer in its wait is kept for /// a paste to wait for off the UI thread, as arboard's are. A read or send whose pipe moves no data /// for [`IDLE_WAIT`] fails and closes the pipe, which frees its worker or thread. #[cfg(target_os = "linux")] @@ -1817,14 +2054,17 @@ 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, PNG, SVG, TEXT}; + 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`. const TEXT_TYPES: [&str; 3] = ["text/plain;charset=utf-8", "UTF8_STRING", "text/plain"]; - /// The most bytes a read takes from the app that copied (untrusted data), VectorCraft's own - /// limit: a read of more fails. - const MAX_BYTES: usize = 64 << 20; + /// What reads the files a file list names. + type PathsOf = fn(&[u8]) -> Vec; + /// The types files copied in a file manager are offered under, each with what reads its files, + /// best first: `text/uri-list` (RFC 2483), and GNOME Files' own list, read only when the first + /// names no file. + const FILE_LISTS: [(&str, PathsOf); 2] = [("text/uri-list", uri_list_paths), ("x-special/gnome-copied-files", gnome_copied_paths)]; /// The most pastes of a Copy's data that are sent at once; a paste beyond them gets nothing. const MAX_SENDS: usize = 8; /// The most types of an offer that are kept (untrusted data). @@ -1905,6 +2145,30 @@ mod wayland { Some(first) } + /// 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) + } + + /// The first file a file manager copied that pastes as one of `mimes` ([`copied_file`]), from + /// the first of [`FILE_LISTS`] among `offered` that names a file, `read` reading each list. + fn copied(offered: &[String], mimes: &[&'static str], mut read: impl FnMut(&str) -> Option>) -> Option { + if !takes_files(mimes) { + return None; + } + let paths = FILE_LISTS.iter().find_map(|(list, paths_of)| { + let wire = offered.iter().find(|o| o.eq_ignore_ascii_case(list))?; + Some(paths_of(&read(wire)?)).filter(|paths| !paths.is_empty()) + })?; + copied_file(paths, mimes) + } + + /// What a paste of one of `mimes` takes: the first copied file that is art ([`copied`]), else + /// what [`pick`] takes. + fn pick_pasted(offered: &[String], mimes: &[&'static str], mut read: impl FnMut(&str) -> Option>) -> Option { + copied(offered, mimes, &mut read).or_else(|| pick(offered, mimes, read)) + } + /// The time `idle` from now; None when that is past the clock's range (no limit). fn idle_until(idle: Duration) -> Option { Instant::now().checked_add(idle) @@ -2089,9 +2353,9 @@ mod wayland { impl Unanswered { /// What a paste of one of `mimes` takes once this read's answer comes, waiting for it until - /// `limit` after the read was sent: the clipboard read again as [`pick`] reads it, each read - /// waiting as long, [`LOAD_WAIT`] at least, since the app that answers late may have lost the - /// clipboard meanwhile. None when the answer doesn't come or the clipboard holds this + /// `limit` after the read was sent: the clipboard read again as [`pick_pasted`] reads it, + /// each read waiting as long, [`LOAD_WAIT`] at least, since the app that answers late may + /// have lost the clipboard meanwhile. None when the answer doesn't come or the clipboard holds this /// connection's Copy. pub(super) fn paste(self, mimes: &[&'static str], limit: Duration) -> Option { let left = |now: Instant| (self.sent + limit).saturating_duration_since(now); @@ -2103,7 +2367,9 @@ mod wayland { } seen.offered.clone() }; - pick(&offered, mimes, |wire| wait_for_answer(&self.reads.ask(wire.to_string()).ok()?, LOAD_WAIT.max(left(Instant::now()))).ok()?.ok()) + pick_pasted(&offered, mimes, |wire| { + wait_for_answer(&self.reads.ask(wire.to_string()).ok()?, LOAD_WAIT.max(left(Instant::now()))).ok()?.ok() + }) } } @@ -2136,12 +2402,36 @@ mod wayland { } } - /// What a paste of one of `mimes` reads: the first the clipboard offers. Text is read here, - /// [`LOAD_WAIT`] at most, and pasted unless it is empty; SVG and PNG are asked for here and - /// waited for, `wait` at most, by the work that comes back. When that read fails or is - /// empty, the work reads the rest of `mimes` as [`pick`] does, each read waiting until - /// `wait` after the first was sent, [`LOAD_WAIT`] at least. + /// What a paste of one of `mimes` reads: the files a file manager copied, else the first of + /// `mimes` the clipboard offers. A file list is asked for here and read, with the files, + /// by the work that comes back, which pastes the first file that is art ([`copied`]) and + /// else reads `mimes` as [`pick`] does. Text is read here, [`LOAD_WAIT`] at most, and + /// pasted unless it is empty; SVG and PNG are asked for here and waited for, `wait` at most, + /// by the work that comes back. When that read fails or is empty, the work reads the rest + /// of `mimes` as [`pick`] does. Each read the work makes after the first waits until `wait` + /// after the first was sent, [`LOAD_WAIT`] at least. pub(super) fn read(&mut self, mimes: &[&'static str], wait: Duration) -> Option { + if takes_files(mimes) { + let offered = lock(&self.seen).offered.clone(); + if let Some(list) = file_list_type(&offered).map(str::to_string) { + let sent = Instant::now(); + let answer = self.loads.ask(list.clone()).ok()?; + self.unanswered = None; + let (reads, mimes) = (self.loads.asker(), mimes.to_vec()); + return Some(ClipboardRead::Later(Box::new(move || { + let left = || LOAD_WAIT.max((sent + wait).saturating_duration_since(Instant::now())); + // The list asked for here is read from its answer, every other type anew. + let mut first = Some((list, answer)); + pick_pasted(&offered, &mimes, |wire| { + let answer = match first.take_if(|(list, _)| list.as_str() == wire) { + Some((_, answer)) => answer, + None => reads.ask(wire.to_string()).ok()?, + }; + wait_for_answer(&answer, left()).ok()?.ok() + }) + }))); + } + } mimes.iter().enumerate().find_map(|(i, &mime)| { let wire = self.wire(mime)?; if mime == TEXT { @@ -2163,10 +2453,11 @@ mod wayland { }) } - /// Whether the clipboard offers one of `mimes`; nothing is read. + /// Whether the clipboard offers one of `mimes`, or files a file manager copied when a paste + /// of `mimes` can take a file; nothing is read. pub(super) fn has(&self, mimes: &[&'static str]) -> bool { let seen = lock(&self.seen); - mimes.iter().any(|m| wire_type(m, &seen.offered).is_some()) + (takes_files(mimes) && file_list_type(&seen.offered).is_some()) || mimes.iter().any(|m| wire_type(m, &seen.offered).is_some()) } /// Whether the clipboard holds this connection's last Copy. @@ -2835,6 +3126,85 @@ mod wayland { let Some(ClipboardRead::Later(work)) = reads.read(&[BITMAP], Duration::from_secs(600)) else { panic!("the PNG is asked for") }; assert!(work().is_none()); } + + /// Reads of a clipboard holding `data` by type, answered at once. + fn reads_holding(data: Vec<(String, Vec)>) -> Reads { + let types: Vec = data.iter().map(|(t, _)| t.clone()).collect(); + let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| { + data.iter().find(|(t, _)| *t == wire).map(|(_, d)| d.clone()).ok_or_else(|| "not offered".to_string()) + }) + .unwrap(); + let types: Vec<&str> = types.iter().map(String::as_str).collect(); + Reads::new(loads, Arc::new(Mutex::new(Seen::offering(&types)))) + } + + /// The `file:` URI of `path`, its spaces escaped. + fn file_uri(path: &std::path::Path) -> String { + format!("file://{}", path.display().to_string().replace(' ', "%20")) + } + + /// What a paste of `mimes` takes from `reads`. + fn paste(reads: &mut Reads, mimes: &[&'static str]) -> Option<(&'static str, Vec)> { + match reads.read(mimes, Duration::from_secs(600))? { + ClipboardRead::Now(f) => Some((f.mime, f.data)), + ClipboardRead::Later(work) => work().map(|f| (f.mime, f.data)), + } + } + + #[test] + fn files_copied_in_a_file_manager_paste_as_their_art() { + use vectorcraft_engine::cmd::clipboard::PASTE_ORDER; + let d = tempfile::Builder::new().prefix("vectorcraft-wayland-files-").tempdir().unwrap(); + let (notes, red) = (d.path().join("notes.txt"), d.path().join("red image.png")); + let mut png = vec![]; + image::RgbaImage::new(2, 2).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + std::fs::write(¬es, "not art").unwrap(); + std::fs::write(&red, &png).unwrap(); + let list = |paths: &[&std::path::Path]| paths.iter().map(|p| file_uri(p) + "\r\n").collect::().into_bytes(); + let held = |types: &[(&str, Vec)]| reads_holding(types.iter().map(|(t, d)| (t.to_string(), d.clone())).collect()); + let text = ("text/plain;charset=utf-8", b"the files' paths".to_vec()); + // A file list alone enables Paste and pastes the first file that is art. + let mut reads = held(&[("text/uri-list", list(&[¬es, &red]))]); + assert!(reads.has(&PASTE_ORDER) && reads.has(&[BITMAP])); + assert_eq!(paste(&mut reads, &PASTE_ORDER), Some((PNG, png.clone()))); + // A paste of text alone takes no file. + assert!(!reads.has(&[TEXT])); + assert_eq!(paste(&mut reads, &[TEXT]), None); + // The files come before the other types offered, as on the other platforms; the type in + // any letter case. + let mut reads = held(&[(SVG, b"".to_vec()), text.clone(), ("Text/URI-List", list(&[&red]))]); + assert_eq!(paste(&mut reads, &PASTE_ORDER), Some((PNG, png.clone()))); + assert_eq!(paste(&mut reads, &[TEXT]), Some((TEXT, text.1.clone()))); + // With no file that is art, the paste takes the other types. + let mut reads = held(&[("text/uri-list", list(&[¬es, &d.path().join("gone.png")])), text.clone()]); + assert_eq!(paste(&mut reads, &PASTE_ORDER), Some((TEXT, text.1.clone()))); + let mut reads = held(&[("text/uri-list", b"https://example.com/art.png\r\n".to_vec())]); + assert_eq!(paste(&mut reads, &PASTE_ORDER), None); + // GNOME Files' own list, alone or when the URI list names no local file. + let gnome = [b"copy\n".to_vec(), file_uri(&red).into_bytes()].concat(); + let mut reads = held(&[("x-special/gnome-copied-files", gnome.clone())]); + assert!(reads.has(&PASTE_ORDER)); + assert_eq!(paste(&mut reads, &PASTE_ORDER), Some((PNG, png.clone()))); + let mut reads = held(&[("text/uri-list", b"file://server/art.png\r\n".to_vec()), ("x-special/gnome-copied-files", gnome)]); + assert_eq!(paste(&mut reads, &PASTE_ORDER), Some((PNG, png.clone()))); + // KDE's cut marker is not a file list. + let mut reads = held(&[("application/x-kde-cutselection", b"1".to_vec())]); + assert!(!reads.has(&PASTE_ORDER)); + assert_eq!(paste(&mut reads, &PASTE_ORDER), None); + } + + #[test] + fn a_file_list_that_cant_be_read_gives_way_to_the_other_types() { + use vectorcraft_engine::cmd::clipboard::PASTE_ORDER; + let offered = offered(&["text/uri-list", "text/plain"]); + let mut asked = vec![]; + let f = pick_pasted(&offered, &PASTE_ORDER, |wire| { + asked.push(wire.to_string()); + (wire == "text/plain").then(|| b"words".to_vec()) + }); + assert_eq!(f.map(|f| (f.mime, f.data)), Some((TEXT, b"words".to_vec()))); + assert_eq!(asked, ["text/uri-list", "text/plain"]); + } } } @@ -2846,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 { @@ -2857,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 }) }) }) } @@ -2952,6 +3325,211 @@ mod tests { assert_eq!(copied_file(vec![with_cr], &PASTE_ORDER).map(|f| f.mime), Some(PNG)); } + /// A copied file of more than 64 MiB is skipped before it is read, and the next one pastes. + #[test] + fn an_oversized_copied_file_is_skipped_before_it_is_read() { + let d = dir("oversized"); + let (big, small) = (d.path().join("big.png"), d.path().join("small.png")); + std::fs::write(&big, png(2, 2)).unwrap(); + // Sparse where the file system allows: no 64 MiB is written. + std::fs::OpenOptions::new().write(true).open(&big).unwrap().set_len(MAX_BYTES as u64 + 1).unwrap(); + std::fs::write(&small, png(3, 2)).unwrap(); + assert!(copied_file(vec![big.clone()], &PASTE_ORDER).is_none()); + let f = copied_file(vec![big, small], &PASTE_ORDER).unwrap(); + assert_eq!((f.mime, f.data), (PNG, png(3, 2))); + } + + /// A copied file of exactly the limit pastes; one byte more and it is skipped. + #[test] + fn a_copied_file_pastes_up_to_the_limit() { + let d = dir("limit"); + let art = d.path().join("art.svg"); + let svg = ""; + std::fs::write(&art, svg).unwrap(); + let read = |limit| copied_file_within(vec![art.clone()], &PASTE_ORDER, limit).map(|f| f.data); + assert_eq!(read(svg.len()), Some(svg.as_bytes().to_vec())); + assert_eq!(read(svg.len() - 1), None); + } + + /// A file that grows past the limit after its size was checked is read to one byte past the + /// limit and refused. + #[test] + fn the_rest_of_a_file_is_read_to_the_limit_at_most() { + let read = |len: usize, head: usize| { + let bytes = vec![7u8; len]; + let mut file = Cursor::new(bytes); + let mut first = vec![0; head]; + file.read_exact(&mut first).unwrap(); + (read_rest(&mut file, first, 16).map(|d| d.len()), file.position()) + }; + assert_eq!(read(16, 4), (Some(16), 16)); + assert_eq!(read(0, 0), (Some(0), 0)); + assert_eq!(read(17, 4), (None, 17)); + assert_eq!(read(1000, 4), (None, 17)); + // First bytes already past the limit: nothing more is read. + assert_eq!(read(1000, 20), (None, 20)); + } + + fn uri_paths(list: &[u8]) -> Vec { + uri_list_paths(list).into_iter().map(|p| p.to_string_lossy().into_owned()).collect() + } + + #[test] + fn a_uri_list_names_the_local_files_of_its_lines() { + // CRLF or LF, comment lines and blank lines. + assert_eq!(uri_paths(b"# copied\r\nfile:///home/a/one.svg\r\n\r\nfile:///home/a/two.png\n"), ["/home/a/one.svg", "/home/a/two.png"]); + assert_eq!(uri_paths(b"file:///a.svg"), ["/a.svg"]); + // Percent escapes are decoded once; `+` and an escaped `#` are part of the name. + assert_eq!(uri_paths(b"file:///home/a/red%20image.png"), ["/home/a/red image.png"]); + assert_eq!(uri_paths(b"file:///home/a/caf%C3%A9.svg\nfile:///home/a/caf\xC3\xA9.svg"), ["/home/a/café.svg", "/home/a/café.svg"]); + assert_eq!(uri_paths(b"file:///a/%231+2.svg"), ["/a/#1+2.svg"]); + assert_eq!(uri_paths(b"file:///a/100%2525.svg"), ["/a/100%25.svg"]); + // No host, `localhost` in any case, and the short form name this machine; a fragment is + // left out. + assert_eq!( + uri_paths(b"file://localhost/a.svg\nFILE://LocalHost/b.svg\nfile:/c.svg\nfile:///d.svg#page=2"), + ["/a.svg", "/b.svg", "/c.svg", "/d.svg"] + ); + // Other hosts and schemes, relative paths, queries, bad escapes, an escaped NUL, a name + // that is not UTF-8 once decoded and a line that is not UTF-8 name no file. + for uri in [ + &b"file://server/a.svg"[..], + b"https://example.com/a.svg", + b"file:a.svg", + b"file://", + b"file://localhost", + b"file:///a.svg?x=1", + b"file:///a%2", + b"file:///a%zz.svg", + b"file:///a%00b.svg", + b"file:///a%FF.svg", + b"file:///a\xFF.svg", + b"/home/a/one.svg", + b"#file:///a.svg", + ] { + assert!(uri_list_paths(uri).is_empty(), "{}", String::from_utf8_lossy(uri)); + } + // The files beside a URI that names none are kept. + assert_eq!(uri_paths(b"https://example.com/a.svg\r\nfile:///b.svg\r\n"), ["/b.svg"]); + assert!(uri_list_paths(b"").is_empty()); + } + + #[test] + fn a_uri_list_longer_than_the_limit_names_no_file() { + assert_eq!(MAX_URIS, 1024); + let list = |n: usize| (0..n).map(|i| format!("# file {i}\r\nfile:///f{i}.svg\r\n")).collect::(); + // Comment lines don't count. + assert_eq!(uri_list_paths(list(MAX_URIS).as_bytes()).len(), MAX_URIS); + 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::>(); + assert_eq!(paths(b"copy\nfile:///a.svg\nfile:///b%20c.png"), ["/a.svg", "/b c.png"]); + assert_eq!(paths(b"cut\r\nfile:///a.svg\r\n"), ["/a.svg"]); + // Another first line, none, or no files. + for list in [&b"move\nfile:///a.svg"[..], b"file:///a.svg\nfile:///b.svg", b"copy", b"", b"Copy\nfile:///a.svg"] { + assert!(gnome_copied_paths(list).is_empty(), "{}", String::from_utf8_lossy(list)); + } + } + /// A DIB of `w`×`h` pixels (top row first when `h` is negative): a `header`-byte header (40, /// or 124 for a BITMAPV5HEADER with BGRA masks), `extra` (the masks after a 40-byte header, a /// colour table), then `rows`, each padded to 4 bytes. @@ -2994,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/host_services.rs b/apps/vectorcraft/src/host_services.rs index 94419b1049..2ed939245f 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -1,5 +1,7 @@ #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] use super::portal_save; +#[cfg(windows)] +use super::windows_screen_color; #[cfg(all(windows, not(target_vendor = "win7")))] use super::windows_stylus; use super::{ClipboardProbeFactory, FilePick, PickRequest, Services, clipboard, cursor_theme, fileio, printing}; @@ -354,7 +356,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { .is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_))); let (clip, clip_probe) = (parent.clone(), parent.clone()); let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent); - #[cfg(any(target_os = "macos", target_os = "linux"))] + #[cfg(any(target_os = "macos", target_os = "linux", windows))] let sampled_ui = ui.clone(); #[cfg(target_os = "linux")] let sampled_parent = p1.clone(); @@ -413,6 +415,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { screen_color: Some(mac_screen_color::sampler(sampled_ui)), #[cfg(target_os = "linux")] screen_color: Some(linux_screen_color::sampler(sampled_ui, sampled_parent)), + #[cfg(windows)] + screen_color: Some(windows_screen_color::sampler(sampled_ui)), // File → Print: the system's printers and print queue. print: Some(Box::new(printing::SystemPrint)), ..Default::default() diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 3397ada7a5..adc52f9d8c 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,7 +63,10 @@ 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; #[cfg(not(target_os = "macos"))] mod single_instance; #[cfg(windows)] @@ -70,6 +77,7 @@ mod window_frame; mod windows_alt_codes; #[cfg(windows)] mod windows_cores; +mod windows_screen_color; mod windows_stylus; mod xwayland; @@ -90,8 +98,6 @@ mod titlebar; use app::bring_window_forward; use app::native_input_hook; use app::open_or_hold; -#[cfg(all(test, not(any(target_os = "macos", windows))))] -use app::{QuittingWindow, hide_before_teardown}; use host_services::services; #[cfg(all(test, feature = "wgpu"))] use prefs::{KEEP_UI_PREFS, decode_saved_prefs, keep_prefs_copy, prefs_bytes}; @@ -122,7 +128,7 @@ struct App { /// Keeps the custom title bar's window borderless (Windows, #1758). window_frame: Option, /// The main window; used to read and set maximized state the UI layer does not see on Linux (#3635), - /// and to hide the window on quit before the clipboard handles let go (`app::hide_before_teardown`). + /// and to take the window off screen on quit before the clipboard handles let go (`quit_windows`). winit_window: Option>, /// A saved or fitted geometry asked for maximize once the window is mapped (Linux). pending_maximize: bool, @@ -158,6 +164,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 +191,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 +213,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 +256,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 +282,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 +305,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), } @@ -418,12 +449,19 @@ fn main() -> std::process::ExitCode { })); options }; + // Quitting takes the X11 windows of floating panels and documents off screen with the main + // window, so eframe's windows are recorded as it makes and drops them (`quit_windows`). + #[cfg(target_os = "linux")] + let options = eframe::NativeOptions { viewport_hooks: Some(std::sync::Arc::new(quit_windows::Hooks)), ..options }; #[cfg(feature = "wgpu")] let options = { 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())); @@ -454,6 +492,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")] @@ -494,6 +536,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/portal_save.rs b/apps/vectorcraft/src/portal_save.rs index 6d1a8734b2..65970c87f7 100644 --- a/apps/vectorcraft/src/portal_save.rs +++ b/apps/vectorcraft/src/portal_save.rs @@ -242,7 +242,7 @@ fn parent(window: &winit::window::Window) -> (String, Option<()>) { /// (), made as rfd's `window_identifier` /// makes it. #[cfg(target_os = "linux")] -mod wayland { +pub(crate) mod wayland { use wayland_client::globals::{GlobalListContents, registry_queue_init}; use wayland_client::protocol::wl_registry::{self, WlRegistry}; use wayland_client::protocol::wl_surface::WlSurface; @@ -308,9 +308,10 @@ mod wayland { } } - /// `window`'s Wayland connection and surface, from its raw handles. + /// `window`'s Wayland connection and surface, from its raw handles. The caller holds `window` + /// while it uses them (`quit_windows` unmaps the main window's surface through them). #[allow(unsafe_code)] - fn surface(window: &winit::window::Window) -> Option<(Connection, WlSurface)> { + pub(crate) fn surface(window: &winit::window::Window) -> Option<(Connection, WlSurface)> { use wayland_backend::sys::client::{Backend, ObjectId}; use winit::raw_window_handle::{HasDisplayHandle as _, HasWindowHandle as _, RawDisplayHandle, RawWindowHandle}; let (RawWindowHandle::Wayland(w), RawDisplayHandle::Wayland(d)) = @@ -319,8 +320,8 @@ mod wayland { return None; }; // SAFETY: the display is winit's open `wl_display`, which outlives `window` (the caller - // holds it until the export is dropped); a backend made from a foreign display does not - // close it when dropped. + // holds it while it uses the connection, and the export holds it until it is dropped); a + // backend made from a foreign display does not close it when dropped. let backend = unsafe { Backend::from_foreign_display(d.display.as_ptr().cast()) }; let conn = Connection::from_backend(backend); // SAFETY: the pointer is the window's live `wl_surface` proxy on that display. 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/src/quit_windows.rs b/apps/vectorcraft/src/quit_windows.rs new file mode 100644 index 0000000000..36497f4f4f --- /dev/null +++ b/apps/vectorcraft/src/quit_windows.rs @@ -0,0 +1,280 @@ +//! Takes the app's windows off screen when it quits on Linux and the BSDs, before eframe drops the +//! app. Dropping the app waits up to [`vectorcraft_ui_egui::CLIPBOARD_PROBE_STOP_WAIT`] for the +//! clipboard handles to let go, and eframe closes the windows only after that wait. +//! +//! The main window is hidden on X11 (XWayland included). winit cannot hide a Wayland window, so on +//! Linux a Wayland main window is unmapped instead: its surface gets no buffer, and the window stays +//! open with the connection the Wayland clipboard copies and reads on. On Linux the X11 windows of +//! floating panels and documents are recorded as eframe creates and drops them ([`Hooks`]), and +//! quitting unmaps them through an X11 connection of its own. On native Wayland, floating panels and +//! documents are normally drawn inside the main window. + +#[cfg(target_os = "linux")] +use std::collections::HashMap; +#[cfg(target_os = "linux")] +use std::sync::{LazyLock, Mutex, MutexGuard, PoisonError}; + +#[cfg(target_os = "linux")] +use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle}; + +/// The main window as quitting sees it. +pub(crate) trait QuittingWindow { + /// The window is a Wayland surface. + fn is_wayland(&self) -> bool; + /// Hides an X11 window. + fn hide(&self); + /// Takes a Wayland window off screen and keeps it open. + fn unmap(&self); +} + +impl QuittingWindow for winit::window::Window { + #[cfg(target_os = "linux")] + fn is_wayland(&self) -> bool { + matches!(self.window_handle().map(|h| h.as_raw()), Ok(RawWindowHandle::Wayland(_))) + } + + /// The BSDs have no Wayland unmap: their windows are hidden through winit. + #[cfg(not(target_os = "linux"))] + fn is_wayland(&self) -> bool { + false + } + + fn hide(&self) { + self.set_visible(false); + } + + #[cfg(target_os = "linux")] + fn unmap(&self) { + unmap_wayland(self); + } + + #[cfg(not(target_os = "linux"))] + fn unmap(&self) { + self.set_visible(false); + } +} + +/// Takes the main window and the floating windows `x11` lists off screen: a Wayland main window is +/// unmapped and any other main window hidden, and `unmap_x11` unmaps the floating windows. +pub(crate) fn off_screen(main: Option<&W>, x11: &[u32], unmap_x11: impl FnOnce(&[u32])) { + if let Some(window) = main { + if window.is_wayland() { + window.unmap(); + } else { + window.hide(); + } + } + if !x11.is_empty() { + unmap_x11(x11); + } +} + +/// [`off_screen`] with the running app's main window and the floating windows [`Hooks`] recorded. +/// Runs on quit, before eframe drops the app. +pub(crate) fn before_teardown(main: Option<&winit::window::Window>) { + #[cfg(target_os = "linux")] + off_screen(main, &CHILD_WINDOWS.x11(), unmap_x11); + #[cfg(not(target_os = "linux"))] + off_screen(main, &[], |_| {}); +} + +/// The X11 windows of floating panels and documents, by viewport, while eframe holds them. +#[cfg(target_os = "linux")] +#[derive(Default)] +pub(crate) struct ChildWindows(Mutex>); + +#[cfg(target_os = "linux")] +impl ChildWindows { + /// eframe made `viewport`'s window, with `handle`. The main window, and windows of other window + /// systems, are not recorded; a window made again for the same viewport replaces its record. + pub(crate) fn created(&self, viewport: egui::ViewportId, handle: Option) { + let mut windows = self.lock(); + match handle.and_then(x11_window) { + Some(id) if viewport != egui::ViewportId::ROOT => windows.insert(viewport, id), + _ => windows.remove(&viewport), + }; + } + + /// eframe dropped `viewport`'s window. + pub(crate) fn destroyed(&self, viewport: egui::ViewportId) { + self.lock().remove(&viewport); + } + + /// The recorded windows, in id order. + pub(crate) fn x11(&self) -> Vec { + let mut ids: Vec = self.lock().values().copied().collect(); + ids.sort_unstable(); + ids.dedup(); + ids + } + + fn lock(&self) -> MutexGuard<'_, HashMap> { + self.0.lock().unwrap_or_else(PoisonError::into_inner) + } +} + +/// The X11 window id of `handle`, None for another window system. +#[cfg(target_os = "linux")] +fn x11_window(handle: RawWindowHandle) -> Option { + match handle { + RawWindowHandle::Xlib(h) => u32::try_from(h.window).ok(), + RawWindowHandle::Xcb(h) => Some(h.window.get()), + _ => None, + } +} + +/// The running app's floating windows, which [`Hooks`] records. +#[cfg(target_os = "linux")] +static CHILD_WINDOWS: LazyLock = LazyLock::new(ChildWindows::default); + +/// Records the windows eframe creates and drops in [`CHILD_WINDOWS`]; set as +/// [`eframe::NativeOptions::viewport_hooks`]. +#[cfg(target_os = "linux")] +pub(crate) struct Hooks; + +#[cfg(target_os = "linux")] +impl eframe::ViewportHooks for Hooks { + fn window_created(&self, viewport: egui::ViewportId, window: &winit::window::Window) { + CHILD_WINDOWS.created(viewport, window.window_handle().ok().map(|h| h.as_raw())); + } + + fn window_destroyed(&self, viewport: egui::ViewportId) { + CHILD_WINDOWS.destroyed(viewport); + } +} + +/// Unmaps the X11 `windows` through a connection of its own, and waits until the server has done so. +/// An id whose window is gone gets an error, which is ignored. +#[cfg(target_os = "linux")] +fn unmap_x11(windows: &[u32]) { + use x11rb::protocol::xproto::ConnectionExt as _; + let conn = match x11rb::connect(None) { + Ok((conn, _)) => conn, + Err(e) => { + log::warn!("couldn't reach the X server to hide the floating windows on quit: {e}"); + return; + } + }; + for &window in windows { + if let Ok(cookie) = conn.unmap_window(window) { + cookie.ignore_error(); + } + } + // The server answers once it has handled the requests before this one. + if let Ok(cookie) = conn.get_input_focus() { + let _ = cookie.reply(); + } +} + +/// Attaches no buffer to `window`'s Wayland surface and commits it, which unmaps the window: the +/// compositor stops showing it, and the window and its connection stay open. +#[cfg(target_os = "linux")] +fn unmap_wayland(window: &winit::window::Window) { + let Some((conn, surface)) = super::portal_save::wayland::surface(window) else { return }; + surface.attach(None, 0, 0); + surface.commit(); + if let Err(e) = conn.flush() { + log::warn!("couldn't reach the compositor to hide the window on quit: {e}"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::RefCell; + + /// A main window that records what quitting did to it. + struct Window<'a> { + wayland: bool, + done: &'a RefCell>, + } + + impl QuittingWindow for Window<'_> { + fn is_wayland(&self) -> bool { + self.wayland + } + fn hide(&self) { + self.done.borrow_mut().push("hide".into()); + } + fn unmap(&self) { + self.done.borrow_mut().push("unmap".into()); + } + } + + fn quit(wayland: Option, x11: &[u32]) -> Vec { + let done = RefCell::new(Vec::new()); + let window = wayland.map(|wayland| Window { wayland, done: &done }); + off_screen(window.as_ref(), x11, |ids| done.borrow_mut().push(format!("unmap x11 {ids:?}"))); + done.into_inner() + } + + /// winit cannot hide a Wayland window: quitting unmaps it, and never only asks winit to hide it. + #[test] + fn quitting_unmaps_a_wayland_main_window() { + assert_eq!(quit(Some(true), &[]), ["unmap"]); + } + + /// An X11 main window (XWayland included) is hidden, and the floating panels' and documents' X11 + /// windows are unmapped with it. + #[test] + fn quitting_hides_an_x11_main_window_and_its_floating_windows() { + assert_eq!(quit(Some(false), &[]), ["hide"]); + assert_eq!(quit(Some(false), &[7, 9]), ["hide", "unmap x11 [7, 9]"]); + } + + /// Without a main window (none was made), the floating windows still go, and with none at all + /// nothing is done. + #[test] + fn quitting_without_a_main_window() { + assert_eq!(quit(None, &[3]), ["unmap x11 [3]"]); + assert!(quit(None, &[]).is_empty()); + } + + #[cfg(target_os = "linux")] + fn xlib(id: std::os::raw::c_ulong) -> Option { + Some(RawWindowHandle::Xlib(winit::raw_window_handle::XlibWindowHandle::new(id))) + } + + #[cfg(target_os = "linux")] + fn viewport(name: &str) -> egui::ViewportId { + egui::ViewportId::from_hash_of(name) + } + + /// The floating windows eframe made are recorded until it drops them; the main window, which + /// quitting reaches through winit, is not. + #[cfg(target_os = "linux")] + #[test] + fn floating_x11_windows_are_recorded_while_they_exist() { + let windows = ChildWindows::default(); + windows.created(egui::ViewportId::ROOT, xlib(1)); + windows.created(viewport("Layers"), xlib(9)); + let xcb = winit::raw_window_handle::XcbWindowHandle::new(std::num::NonZeroU32::new(5).expect("not zero")); + windows.created(viewport("Untitled-2"), Some(RawWindowHandle::Xcb(xcb))); + windows.created(viewport("Color"), xlib(7)); + assert_eq!(windows.x11(), [5, 7, 9]); + windows.destroyed(viewport("Color")); + assert_eq!(windows.x11(), [5, 9]); + // A viewport that eframe has already dropped, or never made, is no error. + windows.destroyed(viewport("Color")); + windows.destroyed(viewport("Swatches")); + assert_eq!(windows.x11(), [5, 9]); + } + + /// A window made again for a viewport replaces its record, and one of another window system, or + /// one whose handle could not be read, removes it. + #[cfg(target_os = "linux")] + #[test] + fn a_window_made_again_replaces_its_record() { + let windows = ChildWindows::default(); + windows.created(viewport("Layers"), xlib(9)); + windows.created(viewport("Layers"), xlib(11)); + assert_eq!(windows.x11(), [11]); + let surface = std::ptr::NonNull::::dangling(); + let wayland = winit::raw_window_handle::WaylandWindowHandle::new(surface); + windows.created(viewport("Layers"), Some(RawWindowHandle::Wayland(wayland))); + assert!(windows.x11().is_empty()); + windows.created(viewport("Layers"), xlib(11)); + windows.created(viewport("Layers"), None); + assert!(windows.x11().is_empty()); + } +} diff --git a/apps/vectorcraft/src/tests.rs b/apps/vectorcraft/src/tests.rs index 1994569c0c..54fa01da03 100644 --- a/apps/vectorcraft/src/tests.rs +++ b/apps/vectorcraft/src/tests.rs @@ -515,21 +515,3 @@ fn the_linux_desktop_entry_opens_every_readable_format() { } } } - -/// On Linux and the BSDs, quitting hides the main window before eframe drops the app, whose -/// clipboard handles may take up to `CLIPBOARD_PROBE_STOP_WAIT` to let go. -#[cfg(not(any(target_os = "macos", windows)))] -#[test] -fn quitting_hides_the_window_before_the_clipboards_let_go() { - struct Window(std::cell::Cell); - impl QuittingWindow for Window { - fn hide(&self) { - self.0.set(self.0.get() + 1); - } - } - let window = Window(std::cell::Cell::new(0)); - hide_before_teardown(Some(&window)); - assert_eq!(window.0.get(), 1, "the window was not hidden"); - // Without a window (none was made), there is nothing to hide. - hide_before_teardown::(None); -} diff --git a/apps/vectorcraft/src/windows_screen_color.rs b/apps/vectorcraft/src/windows_screen_color.rs new file mode 100644 index 0000000000..56ea45eb7d --- /dev/null +++ b/apps/vectorcraft/src/windows_screen_color.rs @@ -0,0 +1,655 @@ +//! Windows: Sample Color from Screen (`vectorcraft_ui_egui::screen_color`). Windows has no system +//! color sampler, so a thread of its own copies the virtual screen, the bounding rectangle of all +//! the monitors (), +//! into a bitmap with `BitBlt` from the screen's device context +//! (), then covers +//! the virtual screen with a borderless topmost window that shows that copy under a crosshair +//! cursor. The window has its own message loop on that thread, so the UI keeps drawing. +//! +//! A left click answers the copied pixel under the pointer as sRGB; Escape, a click of any other +//! button, closing the window, and the window losing the keyboard focus or the mouse capture answer +//! `None`. Each +//! click is answered when its button is released, so the release does not reach the window +//! underneath. The color comes from the copy taken before the window was shown, so the window +//! never samples itself, and moving content shows the frame it had when the copy was taken. +//! +//! The pixels are 8-bit GDI colors, read as sRGB: GDI content is taken to be sRGB when the display +//! does not use Advanced Color +//! (). The colors +//! of HDR and wide-gamut displays are not converted. +//! +//! winit makes the process per-monitor DPI aware, so the virtual screen, the pointer and the copy +//! are in physical pixels on every monitor, whatever its scale, and a monitor left of or above the +//! main one has negative coordinates +//! (). +//! +//! The Win32 calls have no safe binding; [`overlay`] allows `unsafe_code`. +#![cfg_attr(not(windows), allow(dead_code))] + +/// The status message for every failure; the details go to the log. +const FAILED: &str = "the screen color sampler failed"; + +/// The largest copy of the virtual screen, in bytes of 32-bit pixels: 1 GiB, eight 7680 × 4320 +/// monitors. VectorCraft's own limit. +const MAX_SNAPSHOT_BYTES: u64 = 1 << 30; + +/// `CLR_INVALID` (`wingdi.h`): what `GetPixel` answers for a pixel it can't read. +const CLR_INVALID: u32 = 0xFFFF_FFFF; + +/// The virtual screen in physical pixels: its top-left corner (negative when a monitor is left of +/// or above the main one) and its size. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct VirtualScreen { + left: i32, + top: i32, + width: i32, + height: i32, +} + +impl VirtualScreen { + /// The virtual screen `GetSystemMetrics` reports, checked before any memory is taken for its + /// copy: an error when it is empty, larger than [`MAX_SNAPSHOT_BYTES`], or reaches past the + /// coordinates Windows can address. + fn new(left: i32, top: i32, width: i32, height: i32) -> Result { + if width <= 0 || height <= 0 { + return Err(format!("the virtual screen is {width} × {height} pixels")); + } + let bytes = u64::from(width.unsigned_abs()).saturating_mul(u64::from(height.unsigned_abs())).saturating_mul(4); + if bytes > MAX_SNAPSHOT_BYTES { + return Err(format!("the virtual screen ({width} × {height} pixels) is larger than the {MAX_SNAPSHOT_BYTES}-byte limit")); + } + if left.checked_add(width).is_none() || top.checked_add(height).is_none() { + return Err(format!("the virtual screen at ({left}, {top}) reaches past the coordinate range")); + } + Ok(Self { left, top, width, height }) + } + + /// The pixel of the copy at the screen point (`x`, `y`), or `None` when the point is outside the + /// virtual screen. + fn pixel(&self, x: i32, y: i32) -> Option<(i32, i32)> { + let (px, py) = (x.checked_sub(self.left)?, y.checked_sub(self.top)?); + ((0..self.width).contains(&px) && (0..self.height).contains(&py)).then_some((px, py)) + } +} + +/// The sRGB components (0 to 1) of a `COLORREF` (`0x00bbggrr`), or `None` for `CLR_INVALID` or any +/// other value with its high byte set. +fn srgb(colorref: u32) -> Option<[f32; 3]> { + if colorref == CLR_INVALID { + return None; + } + let [r, g, b, high] = colorref.to_le_bytes(); + (high == 0).then(|| [r, g, b].map(|v| f32::from(v) / 255.0)) +} + +/// The client point of a mouse message. Its `lParam` holds each coordinate as a signed 16-bit +/// value (`GET_X_LPARAM` and `GET_Y_LPARAM`, +/// ), so a coordinate past +/// 32,767 pixels in a wide virtual screen loses its high bits. Each coordinate becomes the value +/// with the same low 16 bits nearest to `near`, the message's own pointer position (`MSG.pt`, +/// ) in client +/// coordinates. +fn message_point(lparam: isize, near: (i32, i32)) -> (i32, i32) { + let widen = |low: i16, near: i32| near.saturating_add(i32::from(i32::from(low).wrapping_sub(near) as i16)); + (widen(lparam as i16, near.0), widen((lparam >> 16) as i16, near.1)) +} + +/// A mouse button: the left one picks, and any other one cancels. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Button { + Left, + Right, + /// The middle button or a side button. + Other, +} + +/// What the person did in the sampler's window. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Input { + Down(Button), + Up(Button), + Escape, + /// The window became the active window. + Activated, + /// The window stopped being the active window. + Deactivated, + /// Another window took the mouse capture. + CaptureLost, + /// The window was asked to close (Alt+F4). + Closed, +} + +/// What the sampler does next. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Step { + Wait, + Pick, + Cancel, +} + +/// The mouse button last pressed in the window, and whether the window has been active. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct Press { + down: Option) -> std::ops::ControlFlow { + f(self)?; + if let Some(ch) = self.children() { + for c in ch { + c.try_walk(f)?; + } + } + std::ops::ControlFlow::Continue(()) + } + /// Count of nodes in this subtree, ruler guides left out. pub fn count(&self) -> usize { let mut n = 0; @@ -823,11 +870,11 @@ impl Node { /// The ruler guides a layer holds: its children that are one, by index in order (each with /// nothing inside), and its sublayers holding one (with what they hold). #[derive(Debug, Default)] -pub(super) struct HeldGuides(Vec<(usize, HeldGuides)>); +pub(crate) struct HeldGuides(Vec<(usize, HeldGuides)>); /// The ruler guides, by `is_guide`, that `n` holds if it is a layer, or `None` when it holds /// none. `is_guide` looks at each child of `n` and of its sublayers once. -pub(super) fn held_guides(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option { +pub(crate) fn held_guides(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option { if !n.is_layer() { return None; } @@ -843,7 +890,7 @@ pub(super) fn held_guides(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option /// Remove the ruler guides of `layer` and of its sublayers that [`held_guides`] found (`held`). /// Only the sublayers holding one are copied, and only those are visited. -pub(super) fn strip_held(layer: &mut Node, held: HeldGuides) { +pub(crate) fn strip_held(layer: &mut Node, held: HeldGuides) { let Some(ch) = layer.children_mut() else { return }; let mut held = held.0.into_iter().peekable(); let mut next = 0; @@ -863,7 +910,7 @@ pub(super) fn strip_held(layer: &mut Node, held: HeldGuides) { /// Call `f` (whether it is vertical, its position) on each ruler guide of `layer` and of its /// sublayers that [`held_guides`] found (`held`), in the order they lie in. Only the sublayers /// holding one, and the guides, are copied, and only those sublayers are visited. -pub(super) fn map_held(layer: &mut Node, held: HeldGuides, f: &mut impl FnMut(bool, &mut f64)) { +pub(crate) fn map_held(layer: &mut Node, held: HeldGuides, f: &mut impl FnMut(bool, &mut f64)) { let Some(ch) = layer.children_mut() else { return }; for (i, inner) in held.0 { let Some(c) = ch.get_mut(i) else { continue }; diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index 06e68a79d0..789e0f66b2 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -24,6 +24,7 @@ fn extras_are_written_flat_in_order() { e.envelope_edit_margin = Some([0.5, 0.5, 0.25, 0.25]); e.pixel_aligned = true; e.warp_piece = true; + e.clip_pieces = true; } /// The top-level keys of a JSON object, in the order written. struct Keys(Vec); @@ -71,11 +72,13 @@ fn extras_are_written_flat_in_order() { "envelope_edit_margin", "pixel_aligned", "warp_piece", + "clip_pieces", ]; assert_eq!(keys, order); assert_eq!(v["shape_mode"], "exclude"); assert_eq!(v["pixel_aligned"], true); assert_eq!(v["warp_piece"], true); + assert_eq!(v["clip_pieces"], true); assert_eq!(serde_json::from_value::(v).unwrap(), n); let plain = Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 4.0, 2.0)), Appearance::default_art()); let back: Node = serde_json::from_value(serde_json::to_value(&plain).unwrap()).unwrap(); @@ -802,3 +805,31 @@ fn mapping_ruler_guide_positions_looks_at_each_child_of_nested_layers_once() { assert!(Arc::ptr_eq(&group.children().unwrap()[0], &twice)); assert_eq!(calls, 0); } + +/// `try_walk` visits in `walk`'s order and visits nothing after the node that breaks it: not its +/// children, its later siblings or its ancestors' later siblings. +#[test] +fn try_walk_ends_at_the_break() { + use std::ops::ControlFlow; + let leaf = |id| Arc::new(Node::group(NodeId(id), vec![])); + let inner = Node::group(NodeId(2), vec![leaf(3), leaf(4), leaf(5)]); + let root = Node::group(NodeId(1), vec![Arc::new(inner), leaf(6), leaf(7)]); + let mut all = vec![]; + root.walk(&mut |n| all.push(n.id)); + let mut seen = vec![]; + assert_eq!( + root.try_walk(&mut |n| { + seen.push(n.id); + ControlFlow::<()>::Continue(()) + }), + ControlFlow::Continue(()) + ); + assert_eq!(seen, all, "without a break it visits what walk visits, in the same order"); + seen.clear(); + let flow = root.try_walk(&mut |n| { + seen.push(n.id); + if n.id == NodeId(3) { ControlFlow::Break(n.id) } else { ControlFlow::Continue(()) } + }); + assert_eq!(flow, ControlFlow::Break(NodeId(3))); + assert_eq!(seen, [NodeId(1), NodeId(2), NodeId(3)]); +} diff --git a/crates/doc/src/node/wire.rs b/crates/doc/src/node/wire.rs index 885f9a5853..c47097b8cc 100644 --- a/crates/doc/src/node/wire.rs +++ b/crates/doc/src/node/wire.rs @@ -57,6 +57,7 @@ impl Serialize for Node { is_default(&e.pixel_aligned), e.color_mask.is_none(), is_default(&e.warp_piece), + is_default(&e.clip_pieces), ]; let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?; let mut skip = skips.into_iter(); @@ -102,6 +103,7 @@ impl Serialize for Node { field!("pixel_aligned", &e.pixel_aligned); field!("color_mask", &e.color_mask); field!("warp_piece", &e.warp_piece); + field!("clip_pieces", &e.clip_pieces); st.end() } } @@ -249,6 +251,8 @@ pub(super) struct NodeWire { color_mask: Option>, #[serde(default)] warp_piece: bool, + #[serde(default)] + clip_pieces: bool, } impl From for Node { @@ -279,6 +283,7 @@ impl From for Node { pixel_aligned: w.pixel_aligned, color_mask: w.color_mask, warp_piece: w.warp_piece, + clip_pieces: w.clip_pieces, }; Node { id: w.id, diff --git a/crates/doc/src/objects_on_path.rs b/crates/doc/src/objects_on_path.rs index 35de7cce73..7362f324ea 100644 --- a/crates/doc/src/objects_on_path.rs +++ b/crates/doc/src/objects_on_path.rs @@ -234,8 +234,14 @@ pub fn is_objects_on_path(n: &Node) -> bool { /// The path of `n` if it is a path object an Objects on Path group can attach objects to: a path /// (not a guide) whose first subpath has a length ([`path_length`]). pub fn attachable_path(n: &Node) -> Option<&PathData> { + attachable(n).map(|(path, _)| path) +} + +/// [`attachable_path`] with the path measured ([`Measured`]), from the one flattening that checks +/// its length. +pub fn attachable(n: &Node) -> Option<(&PathData, Measured)> { match &n.kind { - NodeKind::Path { path, guide: false, .. } if path_length(path).is_some() => Some(path), + NodeKind::Path { path, guide: false, .. } => Some((path, Measured::new(path)?)), _ => None, } } @@ -301,20 +307,51 @@ pub fn path_length(path: &PathData) -> Option<(f64, bool)> { /// A path's first subpath flattened ([`Spine`]), with its length and whether it is closed, so that /// one flattening serves both measuring the path and finding points along it. -struct Measured { +pub struct Measured { spine: Spine, len: f64, closed: bool, } +impl std::fmt::Debug for Measured { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Measured").field("len", &self.len).field("closed", &self.closed).finish_non_exhaustive() + } +} + impl Measured { /// `None` for a path without length, or with a length too large to be finite. - fn new(path: &PathData) -> Option { + pub fn new(path: &PathData) -> Option { let spine = Spine::new(path)?; let len = spine.length(); let closed = path.subpaths.first().is_some_and(|s| s.closed); (len.is_finite() && len > 1e-9).then_some(Self { spine, len, closed }) } + /// The flattened first subpath, to measure along. + pub fn spine(&self) -> &Spine { + &self.spine + } + /// The length of the first subpath (points), as [`path_length`] gives it. + pub fn length(&self) -> f64 { + self.len + } + /// Is the first subpath closed? + pub fn closed(&self) -> bool { + self.closed + } + /// [`stops`] on this path. + pub fn stops(&self, n: usize, spacing: Option, start: f64) -> Vec<(Point, f64)> { + let (start, gap) = layout(self.len, self.closed, n, spacing, start); + (0..n).map(|i| self.spine.at_length(nth_length(self.len, self.closed, start, gap, i))).collect() + } + /// [`stop`] on this path: `None` for an `i` of `n` or more. + pub fn stop(&self, n: usize, spacing: Option, start: f64, i: usize) -> Option<(Point, f64)> { + if i >= n { + return None; + } + let (start, gap) = layout(self.len, self.closed, n, spacing, start); + Some(self.spine.at_length(nth_length(self.len, self.closed, start, gap, i))) + } } /// Where the first of `n` objects attaches along a path of length `len` (closed or not), and the @@ -359,9 +396,7 @@ fn wrap(s: f64, len: f64) -> f64 { /// (radians, as `atan2` gives in the document's axes). They go along it as [`layout`] spaces them /// for Space `spacing` (`None`: Auto) from `start`. `None` for a path without length. pub fn stops(path: &PathData, n: usize, spacing: Option, start: f64) -> Option> { - let Measured { spine, len, closed } = Measured::new(path)?; - let (start, gap) = layout(len, closed, n, spacing, start); - Some((0..n).map(|i| spine.at_length(nth_length(len, closed, start, gap, i))).collect()) + Some(Measured::new(path)?.stops(n, spacing, start)) } /// Where object `i` of `n` attaches along `path`, as [`stops`] places it, without the others. @@ -370,9 +405,7 @@ pub fn stop(path: &PathData, n: usize, spacing: Option, start: f64, i: usiz if i >= n { return None; } - let Measured { spine, len, closed } = Measured::new(path)?; - let (start, gap) = layout(len, closed, n, spacing, start); - Some(spine.at_length(nth_length(len, closed, start, gap, i))) + Measured::new(path)?.stop(n, spacing, start, i) } /// The distance along a path of length `len` (closed or not) to object `i`, from `start` and diff --git a/crates/doc/src/overprint.rs b/crates/doc/src/overprint.rs index 056c8c888f..58f6b5abc2 100644 --- a/crates/doc/src/overprint.rs +++ b/crates/doc/src/overprint.rs @@ -4,7 +4,7 @@ use std::sync::Arc; -use vectorcraft_color::{BlendMode, Color, Paint}; +use vectorcraft_color::{BlendMode, Color, GradientKind, Paint}; use crate::{Document, Node, NodeId, NodeKind}; @@ -46,14 +46,21 @@ impl Default for OverprintBlack { } impl OverprintBlack { - /// Whether `p` is black: a solid colour (linked to one of the spot swatches `spots` only with - /// [`Self::spot`]), or a gradient whose every stop is. + /// Whether `p` is black: a solid color (linked to one of the spot swatches `spots` only with + /// [`Self::spot`]), a gradient whose every stop is, or a freeform gradient with color points + /// whose every point is (it draws from its points, not its stops). fn black(&self, p: &Paint, spots: &[String]) -> bool { + let ink = |color: &Color, swatch: &Option| { + (self.spot || !swatch.as_ref().is_some_and(|s| spots.contains(s))) && is_black_ink(color, self.min_k, self.rich) + }; match p { - Paint::Solid { color, swatch, .. } => { - (self.spot || !swatch.as_ref().is_some_and(|s| spots.contains(s))) && is_black_ink(color, self.min_k, self.rich) - } - Paint::Gradient(g) => !g.gradient.stops.is_empty() && g.gradient.stops.iter().all(|s| is_black_ink(&s.color, self.min_k, self.rich)), + Paint::Solid { color, swatch, .. } => ink(color, swatch), + // Only a freeform gradient draws its points; another kind draws its stops whatever it holds. + Paint::Gradient(g) => match g.freeform.as_ref().filter(|f| g.gradient.kind == GradientKind::Freeform && !f.points.is_empty()) { + Some(f) => f.points.iter().all(|pt| is_black_ink(&pt.color, self.min_k, self.rich)), + // Without points of its own a freeform gradient places them from its stops. + None => !g.gradient.stops.is_empty() && g.gradient.stops.iter().all(|s| ink(&s.color, &s.swatch)), + }, _ => false, } } @@ -85,6 +92,52 @@ impl OverprintBlack { } changed } + + /// [`Self::apply`] to every node of `a`'s subtree, copying only the nodes on the way to those + /// that change. Returns whether anything changed. + pub fn apply_deep(&self, a: &mut Arc, spots: &[String]) -> bool { + match self.marked(a, spots) { + Some(n) => { + *a = n; + true + } + None => false, + } + } + + /// `n`'s subtree with [`Self::apply`] done to each node, when that changes anything (`None` + /// otherwise). Each node is visited once, and only the nodes on the way to a change are copied. + fn marked(&self, n: &Arc, spots: &[String]) -> Option> { + let members: Vec<(usize, Arc)> = + n.children().into_iter().flatten().enumerate().filter_map(|(i, c)| Some((i, self.marked(c, spots)?))).collect(); + if members.is_empty() && !self.changes(n, spots) { + return None; + } + let mut copy = Arc::clone(n); + let m = Arc::make_mut(&mut copy); + self.apply(m, spots); + if let Some(children) = m.children_mut() { + for (i, c) in members { + if let Some(slot) = children.get_mut(i) { + *slot = c; + } + } + } + Some(copy) + } + + /// Whether [`Self::apply`] changes a fill, stroke or character of `n` itself. + fn changes(&self, n: &Node, spots: &[String]) -> bool { + let on = !self.remove; + let item = |it: &crate::AppearanceItem| { + it.overprint() != on && (if it.is_fill() { self.fill } else { self.stroke }) && self.black(it.paint(), spots) + }; + let run = |r: &crate::TextRun| { + (self.fill && r.style.overprint_fill != on && self.black(&r.style.fill, spots)) + || (self.stroke && r.style.overprint_stroke != on && self.black(&r.style.stroke, spots)) + }; + n.appearance.items.iter().any(item) || matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(run)) + } } impl Node { @@ -236,6 +289,65 @@ mod tests { assert!(tx.runs[0].style.overprint_fill); } + #[test] + fn a_freeform_gradient_is_black_when_every_point_is() { + use vectorcraft_color::freeform::{Freeform, FreeformPoint}; + let k = Color::cmyk(0.0, 0.0, 0.0, 1.0); + let mut g = vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient { kind: GradientKind::Freeform, ..Default::default() }); + for s in &mut g.gradient.stops { + s.color = k; + } + let points = vec![FreeformPoint::new(Point::ZERO, k), FreeformPoint::new(Point::new(10.0, 0.0), Color::cmyk(1.0, 0.0, 0.0, 0.0))]; + g.freeform = Some(Freeform { points, ..Default::default() }); + let fill = |g: &vectorcraft_color::GradientPaint| Appearance::basic(Paint::Gradient(Box::new(g.clone())), Paint::None, 0.0); + let mut n = Node::path(NodeId(1), Default::default(), fill(&g)); + assert!(!OverprintBlack::default().apply(&mut n, &[]), "a cyan point is drawn, whatever the stops"); + // Another kind of gradient draws its black stops, not the points it still holds. + let mut linear = g.clone(); + linear.gradient.kind = GradientKind::Linear; + let mut n = Node::path(NodeId(1), Default::default(), fill(&linear)); + assert!(OverprintBlack::default().apply(&mut n, &[]), "a linear gradient is judged by its stops"); + if let Some(f) = &mut g.freeform { + f.points[1].color = Color::gray(1.0); + } + let mut n = Node::path(NodeId(1), Default::default(), fill(&g)); + assert!(OverprintBlack::default().apply(&mut n, &[]), "every point black"); + g.freeform = Some(Freeform::default()); + let mut n = Node::path(NodeId(1), Default::default(), fill(&g)); + assert!(OverprintBlack::default().apply(&mut n, &[]), "no points: placed from the black stops"); + } + + #[test] + fn a_gradient_with_a_spot_linked_stop_is_black_only_with_spot() { + let mut g = vectorcraft_color::GradientPaint::new(Default::default()); + for s in &mut g.gradient.stops { + s.color = Color::cmyk(0.0, 0.0, 0.0, 1.0); + } + g.gradient.stops[0].swatch = Some("Ink".into()); + let k = Paint::Gradient(Box::new(g)); + let mut n = Node::path(NodeId(1), Default::default(), Appearance::basic(k, Paint::None, 0.0)); + let spots = ["Ink".to_string()]; + assert!(!OverprintBlack::default().apply(&mut n, &spots), "a stop linked to a spot swatch is not process black"); + assert!(OverprintBlack { spot: true, ..Default::default() }.apply(&mut n, &spots), "Include Spot Blacks takes it"); + } + + #[test] + fn apply_deep_copies_only_the_nodes_that_change() { + let k = cmyk(0.0, 0.0, 0.0, 1.0); + let black = Arc::new(Node::path(NodeId(2), Default::default(), Appearance::basic(k, Paint::None, 0.0))); + let cyan = Arc::new(Node::path(NodeId(3), Default::default(), Appearance::basic(cmyk(1.0, 0.0, 0.0, 0.0), Paint::None, 0.0))); + let mut group = Arc::new(Node::group(NodeId(1), vec![black.clone(), cyan.clone()])); + let before = group.clone(); + assert!(OverprintBlack::default().apply_deep(&mut group, &[])); + let members = group.children().unwrap(); + assert!(members[0].appearance.fill().unwrap().overprint && !black.has_overprint(), "the copy is marked, not the original"); + assert!(Arc::ptr_eq(&members[1], &cyan), "the cyan member is shared, not copied"); + assert!(!before.has_overprint()); + let marked = group.clone(); + assert!(!OverprintBlack::default().apply_deep(&mut group, &[]), "nothing left to change"); + assert!(Arc::ptr_eq(&group, &marked), "and nothing is copied"); + } + #[test] fn legacy_overprint_black_list_migrates() { let mut d = Document::new(100.0, 100.0); diff --git a/crates/doc/src/pattern.rs b/crates/doc/src/pattern.rs index d1333bef0b..b2c00d8ab3 100644 --- a/crates/doc/src/pattern.rs +++ b/crates/doc/src/pattern.rs @@ -173,6 +173,10 @@ pub struct PatternDef { /// Size Tile to Art: the tile is the art bounds grown by the spacing. #[serde(default)] pub size_tile_to_art: bool, + /// Move Tile with Art: in pattern editing mode, a move of all of the tile art moves the tile by + /// the same offset. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub move_tile_with_art: bool, #[serde(default)] pub h_spacing: f64, #[serde(default)] @@ -202,6 +206,7 @@ impl PatternDef { art, overlap: Overlap::default(), size_tile_to_art: false, + move_tile_with_art: false, h_spacing: 0.0, v_spacing: 0.0, copies: 5, 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/placed_document.rs b/crates/doc/src/placed_document.rs index 86f7f6134c..1d6b3e4f11 100644 --- a/crates/doc/src/placed_document.rs +++ b/crates/doc/src/placed_document.rs @@ -1,5 +1,5 @@ -//! Placed documents: another VectorCraft file, or a page of a PDF or `.ai` file, placed linked -//! ([`PlacedDocument`]). +//! Placed documents: another VectorCraft file, a page of a PDF or `.ai` file, or an EPS file, +//! placed linked ([`PlacedDocument`]). //! //! The object keeps the link to the file and the file's bytes, stored like image data in //! [`Document::images`] (with a small preview a save writes instead, as for linked images), so the @@ -7,9 +7,9 @@ //! joins the object tree, so editing can't reach it: it is locked by design. Drawing and exporting //! expand it like a live object ([`crate::live::expanded`]). //! -//! The file is read by the engine's loader (native documents, PDF and `.ai` pages), which lives -//! above this crate and registers itself ([`set_loader`]); the art read is kept in a small cache -//! by content. Before exporting, +//! The file is read by the engine's loader (native documents, PDF and `.ai` pages, EPS files), +//! which lives above this crate and registers itself ([`set_loader`]); the art read is kept in a +//! small cache by content. Before exporting, //! every exporter calls [`Document::with_placed_art`], which adds the resources the art uses //! (images, symbols, patterns) under names of their own ([`RESOURCE_PREFIX`]) to a temporary copy //! of the document, so they never meet the user's or show in panels. Placed documents inside a @@ -27,8 +27,8 @@ use vectorcraft_color::Paint; use crate::{AppearanceItem, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind, PatternDef, PlacementOptions, Symbol}; -/// A placed document: an artboard of another VectorCraft file, or a page of a PDF or `.ai` file, -/// shown as one locked object. +/// A placed document: an artboard of another VectorCraft file, a page of a PDF or `.ai` file, or +/// an EPS file's art, shown as one locked object. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PlacedDocument { /// The file (its `page` is the artboard or page shown, 1-based). @@ -166,13 +166,15 @@ fn walk_all<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) { } } -/// The roots of `d`'s art: layers, symbol definitions and pattern swatches. +/// The roots of `d`'s art: layers, symbol definitions, pattern swatches and +/// [`Document::mounted_art`]. fn roots(d: &Document) -> impl Iterator> { d.layers .iter() .chain(d.symbols.iter().map(|s| &s.art)) .chain(d.graph_designs.iter().map(|g| &g.art)) .chain(d.patterns.iter().flat_map(|p| &p.art)) + .chain(d.mounted_art.iter().map(|(n, _)| n)) } fn roots_mut(d: &mut Document) -> impl Iterator> { @@ -181,6 +183,7 @@ fn roots_mut(d: &mut Document) -> impl Iterator> { .chain(d.symbols.iter_mut().map(|s| &mut s.art)) .chain(d.graph_designs.iter_mut().map(|g| &mut g.art)) .chain(d.patterns.iter_mut().flat_map(|p| &mut p.art)) + .chain(d.mounted_art.iter_mut().map(|(n, _)| n)) } impl Document { diff --git a/crates/doc/src/ppi.rs b/crates/doc/src/ppi.rs new file mode 100644 index 0000000000..5c3bd24b53 --- /dev/null +++ b/crates/doc/src/ppi.rs @@ -0,0 +1,287 @@ +//! Image resolution metadata (pixels per inch) in the formats the image decoder reads: PNG `pHYs`, +//! JPEG JFIF density or EXIF, TIFF and WebP EXIF resolution tags, and BMP pixels per metre. An image +//! converted to PNG keeps it as a `pHYs` chunk ([`with_png_resolution`]). + +const INCH_M: f64 = 0.0254; +const INCH_CM: f64 = 2.54; + +/// Is `bytes` a PNG, JPEG, TIFF, WebP or BMP file, the formats [`resolution`] reads? +pub fn reads(bytes: &[u8]) -> bool { + bytes.starts_with(b"\x89PNG\r\n\x1a\n") + || bytes.starts_with(&[0xff, 0xd8]) + || bytes.starts_with(b"II*\0") + || bytes.starts_with(b"MM\0*") + || (bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP") + || bytes.starts_with(b"BM") +} + +/// The resolution a PNG, JPEG, TIFF, WebP or BMP file declares as (horizontal, vertical) ppi, each +/// from 1 to 100,000; `None` when it declares none (or only an aspect ratio), and for other files. +pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> { + let r = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { + png(bytes) + } else if bytes.starts_with(&[0xff, 0xd8]) { + jpeg(bytes) + } else if bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*") { + tiff(bytes) + } else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { + webp(bytes) + } else if bytes.starts_with(b"BM") { + bmp(bytes) + } else { + None + }; + r.filter(|(x, y)| [*x, *y].iter().all(|v| v.is_finite() && (1.0..=100_000.0).contains(v))) +} + +/// `n` bytes at `at` (`None` past the end; offsets come from the file, so no overflow either). +fn slice(b: &[u8], at: usize, n: usize) -> Option<&[u8]> { + b.get(at..at.checked_add(n)?) +} +fn bytes(b: &[u8], at: usize) -> Option<[u8; N]> { + slice(b, at, N)?.try_into().ok() +} +fn be16(b: &[u8], at: usize) -> Option { + bytes(b, at).map(u16::from_be_bytes) +} +fn be32(b: &[u8], at: usize) -> Option { + bytes(b, at).map(u32::from_be_bytes) +} +fn le32(b: &[u8], at: usize) -> Option { + bytes(b, at).map(u32::from_le_bytes) +} + +/// Pixels per inch from the whole pixels per metre PNG and BMP store: a whole number of ppi when +/// the metre value is that rounded (300 ppi is stored as 11811 per metre, 299.9994 ppi). +fn per_metre(ppm: u32) -> f64 { + let v = ppm as f64 * INCH_M; + let whole = v.round(); + if (v - whole).abs() <= INCH_M / 2.0 + 1e-9 { whole } else { v } +} + +/// PNG chunks after the signature: (type, data). +pub fn png_chunks(b: &[u8]) -> impl Iterator { + let mut at = 8; + std::iter::from_fn(move || { + let len = be32(b, at)? as usize; + let ty = slice(b, at + 4, 4)?; + let data = slice(b, at + 8, len)?; + at = at.checked_add(12 + len)?; + Some((ty, data)) + }) +} + +fn png(b: &[u8]) -> Option<(f64, f64)> { + let (_, d) = png_chunks(b).take_while(|(ty, _)| *ty != b"IDAT").find(|(ty, _)| *ty == b"pHYs")?; + // Unit 1 = metre; 0 only gives the pixel aspect ratio. + (d.get(8) == Some(&1)).then(|| (per_metre(be32(d, 0).unwrap_or(0)), per_metre(be32(d, 4).unwrap_or(0)))) +} + +fn jpeg(b: &[u8]) -> Option<(f64, f64)> { + let (mut jfif, mut exif) = (None, None); + let mut at = 2; + while at + 4 <= b.len() && b[at] == 0xff { + let marker = b[at + 1]; + // 0xff fill bytes pad between segments. + if marker == 0xff { + at += 1; + continue; + } + if marker == 0xd8 || marker == 0x01 || (0xd0..=0xd7).contains(&marker) { + at += 2; + continue; + } + // Start of scan or end of image: no more metadata. + if marker == 0xda || marker == 0xd9 { + break; + } + let len = be16(b, at + 2)? as usize; + let seg = slice(b, at + 4, len.checked_sub(2)?)?; + match marker { + 0xe0 if seg.starts_with(b"JFIF\0") && seg.len() >= 12 => { + let (x, y) = (be16(seg, 8)? as f64, be16(seg, 10)? as f64); + jfif = match seg[7] { + 1 => Some((x, y)), + 2 => Some((x * INCH_CM, y * INCH_CM)), + _ => None, + }; + } + 0xe1 if seg.starts_with(b"Exif\0\0") => exif = tiff(&seg[6..]), + _ => {} + } + at += 2 + len; + } + jfif.or(exif) +} + +/// TIFF (or EXIF) IFD0 XResolution / YResolution / ResolutionUnit, as (horizontal, vertical) ppi +/// in the stored pixels' axes, unchecked; `None` without an absolute unit. +pub fn tiff(b: &[u8]) -> Option<(f64, f64)> { + let le = b.starts_with(b"II"); + let u16_at = |at: usize| bytes(b, at).map(if le { u16::from_le_bytes } else { u16::from_be_bytes }); + let u32_at = |at: usize| bytes(b, at).map(if le { u32::from_le_bytes } else { u32::from_be_bytes }); + let ifd = u32_at(4)? as usize; + let (mut x, mut y, mut unit) = (None, None, 2); + for i in 0..u16_at(ifd)? as usize { + let e = ifd.checked_add(2 + i * 12)?; + let rational = || -> Option { + let at = u32_at(e + 8)? as usize; + let (n, d) = (u32_at(at)?, u32_at(at.checked_add(4)?)?); + (d != 0).then(|| n as f64 / d as f64) + }; + match u16_at(e)? { + 282 => x = rational(), + 283 => y = rational(), + 296 => unit = u16_at(e + 8)?, + _ => {} + } + } + let k = match unit { + 2 => 1.0, + 3 => INCH_CM, + _ => return None, + }; + let x = x?; + Some((x * k, y.unwrap_or(x) * k)) +} + +fn webp(b: &[u8]) -> Option<(f64, f64)> { + let mut at = 12; + while at + 8 <= b.len() { + let len = le32(b, at + 4)? as usize; + let data = slice(b, at + 8, len)?; + if &b[at..at + 4] == b"EXIF" { + return tiff(data.strip_prefix(b"Exif\0\0").unwrap_or(data)); + } + at += 8 + len + (len & 1); + } + None +} + +fn bmp(b: &[u8]) -> Option<(f64, f64)> { + // BITMAPINFOHEADER (40 bytes or longer) at 14: pixels per metre at +24 and +28. + if le32(b, 14)? < 40 { + return None; + } + let ppm = |at| le32(b, at).filter(|v| (1..=i32::MAX as u32).contains(v)).map(per_metre); + Some((ppm(38)?, ppm(42)?)) +} + +/// Pixels per metre for a resolution in pixels per inch (the unit `pHYs` stores). +pub fn pixels_per_metre(ppi: f64) -> u32 { + (ppi / INCH_M).round().clamp(1.0, u32::MAX as f64) as u32 +} + +/// PNG CRC-32 (the polynomial ZIP uses) of `parts` read one after another. +fn crc32(parts: &[&[u8]]) -> u32 { + let mut crc = !0u32; + for &b in parts.iter().flat_map(|p| p.iter()) { + crc ^= u32::from(b); + for _ in 0..8 { + crc = (crc >> 1) ^ (0xEDB8_8320 & u32::from(crc & 1 != 0).wrapping_neg()); + } + } + !crc +} + +/// A whole `pHYs` chunk (length, type, data, CRC) declaring `x` × `y` pixels per inch. +pub fn phys_chunk(x: f64, y: f64) -> Vec { + let [x, y] = [x, y].map(|v| pixels_per_metre(v).to_be_bytes()); + // x, y, unit 1 = metre. + let data = [x.as_slice(), y.as_slice(), &[1]].concat(); + let mut out = Vec::with_capacity(21); + out.extend_from_slice(&9u32.to_be_bytes()); + out.extend_from_slice(b"pHYs"); + out.extend_from_slice(&data); + out.extend_from_slice(&crc32(&[b"pHYs", &data]).to_be_bytes()); + out +} + +/// `png` with a `pHYs` chunk declaring `ppi` right after the header (any existing one is replaced). +pub fn with_png_resolution(png: &[u8], (x, y): (f64, f64)) -> Vec { + let Some(head) = be32(png, 8).and_then(|len| slice(png, 0, 20usize.checked_add(len as usize)?)) else { return png.to_vec() }; + let chunk = phys_chunk(x, y); + let mut out = Vec::with_capacity(png.len() + chunk.len()); + out.extend_from_slice(head); + out.extend_from_slice(&chunk); + let mut at = head.len(); + while let Some(chunk) = be32(png, at).and_then(|len| slice(png, at, 12usize.checked_add(len as usize)?)) { + if chunk.get(4..8) != Some(b"pHYs") { + out.extend_from_slice(chunk); + } + at += chunk.len(); + } + out.extend_from_slice(png.get(at..).unwrap_or_default()); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + 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(); + out + } + + /// The `pHYs` chunk carries the CRC a PNG reader checks, and replaces the one already there. + #[test] + fn a_png_takes_its_resolution_and_still_decodes() { + let png = png_of(4, 3); + assert_eq!(resolution(&png), None); + let tagged = with_png_resolution(&png, (300.0, 150.0)); + assert_eq!(resolution(&tagged), Some((300.0, 150.0))); + let again = with_png_resolution(&tagged, (72.0, 72.0)); + assert_eq!(resolution(&again), Some((72.0, 72.0)), "replaced, not duplicated"); + assert_eq!(again.len(), tagged.len()); + let img = image::load_from_memory(&again).unwrap(); + assert_eq!((img.width(), img.height()), (4, 3)); + // Every PNG ends with this IEND chunk CRC. + assert_eq!(crc32(&[b"IEND"]), 0xAE42_6082); + } + + /// RIFF chunk `ty` holding `data`, padded to an even length. + fn riff_chunk(ty: &[u8; 4], len: u32, data: &[u8]) -> Vec { + let mut out = [ty.as_slice(), &len.to_le_bytes(), data].concat(); + if data.len() % 2 == 1 { + out.push(0); + } + out + } + + fn webp_of(chunks: &[Vec]) -> Vec { + let body = chunks.concat(); + let size = u32::try_from(body.len() + 4).unwrap(); + [b"RIFF".as_slice(), &size.to_le_bytes(), b"WEBP", &body].concat() + } + + /// A WebP's EXIF chunk is found past an odd-length chunk and its padding byte, and a chunk whose + /// length runs past the end of the file (up to `u32::MAX`, more than a 32-bit `usize` can add to + /// an offset) gives no resolution. + #[test] + fn a_webp_reads_its_exif_and_rejects_a_chunk_past_the_end() { + // Little-endian TIFF: two IFD0 entries, XResolution 300/1 at offset 38 and ResolutionUnit inch. + let mut tiff = b"II*\0".to_vec(); + tiff.extend_from_slice(&8u32.to_le_bytes()); + tiff.extend_from_slice(&2u16.to_le_bytes()); + for (tag, ty, value) in [(282u16, 5u16, 38u32), (296, 3, 2)] { + tiff.extend_from_slice(&tag.to_le_bytes()); + tiff.extend_from_slice(&ty.to_le_bytes()); + tiff.extend_from_slice(&1u32.to_le_bytes()); + tiff.extend_from_slice(&value.to_le_bytes()); + } + tiff.extend_from_slice(&0u32.to_le_bytes()); + tiff.extend_from_slice(&300u32.to_le_bytes()); + tiff.extend_from_slice(&1u32.to_le_bytes()); + let exif = [b"Exif\0\0".as_slice(), &tiff].concat(); + let exif_len = u32::try_from(exif.len()).unwrap(); + let ok = webp_of(&[riff_chunk(b"VP8X", 3, &[0, 0, 0]), riff_chunk(b"EXIF", exif_len, &exif)]); + assert_eq!(resolution(&ok), Some((300.0, 300.0))); + + for len in [u32::MAX, u32::MAX - 7, 1_000] { + let bad = webp_of(&[riff_chunk(b"VP8X", len, &[0; 10])]); + assert_eq!(resolution(&bad), None, "chunk length {len}"); + } + } +} 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/resample.rs b/crates/doc/src/resample.rs new file mode 100644 index 0000000000..bc72cce1db --- /dev/null +++ b/crates/doc/src/resample.rs @@ -0,0 +1,259 @@ +//! Scaling images whose pixels carry straight (not premultiplied) alpha. +//! +//! `image`'s filtered resampling filters each channel on its own, which is correct only for +//! premultiplied pixels, and its thumbnail averages each channel on its own too, so on +//! straight-alpha pixels the color under clear pixels bleeds into the opaque ones next to them +//! (clear black darkens a cut-out's edge). [`resized`], [`fitted`] and [`averaged`] weight each +//! pixel's color by its alpha while scaling, as the streaming shrink in the renderer does. + +use image::imageops::FilterType; +use image::{DynamicImage, RgbaImage}; + +/// How [`resized`] makes each new pixel from the old ones. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Resample { + /// `image`'s filtered resampling with this filter. + Filter(FilterType), + /// The mean of the old pixels each new one covers ([`averaged`]). + Average, +} + +/// `img` scaled to `w` × `h` pixels as `how` says, each pixel's color weighted by its alpha. +/// Filtered or averaged, an image with clear or partly clear pixels comes back as 8-bit RGBA +/// whatever its own pixel format, and a pixel that ends up wholly clear is transparent black. An +/// image without clear pixels is scaled as `image` scales it, in its own pixel format. +/// Nearest-neighbor picking leaves the pixels as they are, in their own format, and is not +/// weighted. Filtered, the colors keep the precision of premultiplied 8-bit pixels, and an 8-bit +/// RGBA image is premultiplied in place. +pub fn resized(img: DynamicImage, w: u32, h: u32, how: Resample) -> DynamicImage { + if (w, h) == (img.width(), img.height()) { + return img; + } + let f = match how { + Resample::Average => return averaged(&img, w, h), + Resample::Filter(f) => f, + }; + if f == FilterType::Nearest || opaque(&img) { + return img.resize_exact(w, h, f); + } + let mut rgba = img.into_rgba8(); + for p in rgba.pixels_mut() { + let [r, g, b, a] = &mut p.0; + for c in [r, g, b] { + *c = times_alpha(*c, *a); + } + } + let mut out = image::imageops::resize(&rgba, w, h, f); + for p in out.pixels_mut() { + let [r, g, b, a] = &mut p.0; + for c in [r, g, b] { + *c = over_alpha(*c, *a); + } + } + DynamicImage::ImageRgba8(out) +} + +/// [`resized`] to the largest size that fits `w` × `h` pixels and keeps `img`'s proportions, the +/// size `image`'s own `resize` and `thumbnail` pick. +pub fn fitted(img: DynamicImage, w: u32, h: u32, how: Resample) -> DynamicImage { + let (nw, nh) = fit_size(img.width(), img.height(), w, h); + resized(img, nw, nh, how) +} + +/// `img` scaled to `w` × `h` pixels, each new pixel the mean of the old pixels it covers, each old +/// pixel counted by the area of it covered and its color weighted by its alpha. `img` is read one +/// row at a time, so besides the result this takes one row of 8-bit RGBA at most. An image +/// without clear pixels is scaled as `image`'s thumbnail scales it. +pub fn averaged(img: &DynamicImage, w: u32, h: u32) -> DynamicImage { + let (sw, sh) = (img.width(), img.height()); + if opaque(img) || w == 0 || h == 0 || sw == 0 || sh == 0 { + return img.thumbnail_exact(w, h); + } + // Per new pixel of the row being made: red, green and blue times alpha, alpha (all times the + // area covered), and the area covered. + let mut sums = vec![([0f64; 4], 0f64); w as usize]; + let mut out = Vec::with_capacity(w as usize * h as usize * 4); + for ty in 0..h { + for (y, wy) in covered(ty, sh, h) { + let row = rgba_row(img, y as u32); + for ((s, area), tx) in sums.iter_mut().zip(0..w) { + for (x, wx) in covered(tx, sw, w) { + let Some(p) = row.get(x * 4..x * 4 + 4) else { continue }; + let k = wx * wy; + let a = f64::from(p[3]) * k; + s[0] += f64::from(p[0]) * a; + s[1] += f64::from(p[1]) * a; + s[2] += f64::from(p[2]) * a; + s[3] += a; + *area += k; + } + } + } + let byte = |v: f64| v.round().clamp(0.0, 255.0) as u8; + for (s, area) in &mut sums { + out.extend(if s[3] <= 0.0 { [0; 4] } else { [byte(s[0] / s[3]), byte(s[1] / s[3]), byte(s[2] / s[3]), byte(s[3] / *area)] }); + (*s, *area) = ([0.0; 4], 0.0); + } + } + RgbaImage::from_raw(w, h, out).map_or_else(|| img.thumbnail_exact(w, h), DynamicImage::ImageRgba8) +} + +/// Row `y` of `img` as 8-bit RGBA: borrowed from an 8-bit RGBA image, converted from others. +fn rgba_row(img: &DynamicImage, y: u32) -> std::borrow::Cow<'_, [u8]> { + let n = img.width() as usize * 4; + match img { + DynamicImage::ImageRgba8(b) => std::borrow::Cow::Borrowed(b.as_raw().get(y as usize * n..(y as usize + 1) * n).unwrap_or_default()), + other => std::borrow::Cow::Owned(other.crop_imm(0, y, other.width(), 1).into_rgba8().into_raw()), + } +} + +/// The old pixels that new pixel `t` of `tn` covers along a side of `n` old pixels, each with the +/// length of it covered (in old pixels), worked out as they are read so that nothing is stored. +fn covered(t: u32, n: u32, tn: u32) -> impl Iterator { + let scale = f64::from(n) / f64::from(tn); + let (a, b) = (f64::from(t) * scale, (f64::from(t) + 1.0) * scale); + let (first, end) = (a.floor() as u32, (b.ceil() as u32).min(n)); + (first..end.max(first + 1).min(n)).filter_map(move |i| { + let len = b.min(f64::from(i) + 1.0) - a.max(f64::from(i)); + (len > 0.0).then_some((i as usize, len)) + }) +} + +/// Each 4-channel pixel of `px` with all four channels multiplied by its value in `alpha` (one +/// sample a pixel, 0 to 255): ink amounts or colors made ready for scaling beside a separate alpha +/// channel. Pixels past the end of `alpha` are left as they are. +pub fn premultiply(px: &mut [u8], alpha: &[u8]) { + for (p, &a) in px.as_chunks_mut::<4>().0.iter_mut().zip(alpha) { + for c in p { + *c = times_alpha(*c, a); + } + } +} + +/// [`premultiply`] undone after scaling: each 4-channel pixel of `px` divided by its value in the +/// scaled `alpha`, and 0 where that is 0. +pub fn unpremultiply(px: &mut [u8], alpha: &[u8]) { + for (p, &a) in px.as_chunks_mut::<4>().0.iter_mut().zip(alpha) { + for c in p { + *c = over_alpha(*c, a); + } + } +} + +/// Does `img` have no alpha channel, or is every pixel of it opaque? +fn opaque(img: &DynamicImage) -> bool { + match img { + DynamicImage::ImageRgba8(b) => b.pixels().all(|p| p[3] == u8::MAX), + DynamicImage::ImageLumaA8(b) => b.pixels().all(|p| p[1] == u8::MAX), + DynamicImage::ImageRgba16(b) => b.pixels().all(|p| p[3] == u16::MAX), + DynamicImage::ImageLumaA16(b) => b.pixels().all(|p| p[1] == u16::MAX), + DynamicImage::ImageRgba32F(b) => b.pixels().all(|p| p[3] >= 1.0), + other => !other.color().has_alpha(), + } +} + +/// Channel `c` times alpha `a`, both 0 to 255. +fn times_alpha(c: u8, a: u8) -> u8 { + ((u16::from(c) * u16::from(a) + 127) / 255) as u8 +} + +/// Premultiplied channel `c` divided by alpha `a` (0 when `a` is 0). +fn over_alpha(c: u8, a: u8) -> u8 { + if a == 0 { + return 0; + } + let a = u32::from(a); + ((u32::from(c) * 255 + a / 2) / a).min(255) as u8 +} + +/// The largest size of at most `nw` × `nh` with the proportions of `w` × `h`, at least a pixel a +/// side. +pub fn fit_size(w: u32, h: u32, nw: u32, nh: u32) -> (u32, u32) { + if w == 0 || h == 0 { + return (nw.max(1), nh.max(1)); + } + let ratio = (f64::from(nw) / f64::from(w)).min(f64::from(nh) / f64::from(h)); + let side = |n: u32| ((f64::from(n) * ratio).round() as u32).max(1); + (side(w), side(h)) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A 4 × 2 image whose left half is opaque red and whose right half is clear black. + fn half_clear() -> DynamicImage { + DynamicImage::ImageRgba8(RgbaImage::from_fn(4, 2, |x, _| if x < 2 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([0, 0, 0, 0]) })) + } + + /// Is the color of `p`, premultiplied by its alpha, within a step of `rgb` premultiplied by the + /// same alpha (the precision of premultiplied 8-bit pixels)? + fn close(p: [u8; 4], rgb: [u8; 3]) -> bool { + p[..3].iter().zip(rgb).all(|(&c, want)| times_alpha(c, p[3]).abs_diff(times_alpha(want, p[3])) <= 1) + } + + #[test] + fn averaging_keeps_the_color_of_the_opaque_pixels() { + let p = resized(half_clear(), 1, 1, Resample::Average).into_rgba8().get_pixel(0, 0).0; + assert!(close(p, [200, 30, 30]) && p[3].abs_diff(128) <= 1, "{p:?}"); + } + + /// Three pixels averaged into two: each new pixel takes one old pixel whole and half of the + /// clear one in the middle. + #[test] + fn averaging_counts_the_part_of_a_pixel_covered() { + let img = RgbaImage::from_fn(3, 1, |x, _| if x == 1 { image::Rgba([0, 0, 0, 0]) } else { image::Rgba([200, 30, 30, 255]) }); + let out = averaged(&DynamicImage::ImageRgba8(img), 2, 1).into_rgba8(); + assert_eq!(out.into_raw(), [[200, 30, 30, 170], [200, 30, 30, 170]].concat()); + // Gray with alpha is read the same way. + let gray = image::GrayAlphaImage::from_fn(3, 1, |x, _| image::LumaA(if x == 1 { [0, 0] } else { [200, 255] })); + let out = averaged(&DynamicImage::ImageLumaA8(gray), 2, 1).into_rgba8(); + assert_eq!(out.into_raw(), [[200, 200, 200, 170], [200, 200, 200, 170]].concat()); + } + + #[test] + fn filtering_keeps_the_color_of_the_opaque_pixels() { + for f in [FilterType::Triangle, FilterType::CatmullRom, FilterType::Lanczos3] { + let out = resized(half_clear(), 2, 1, Resample::Filter(f)).into_rgba8(); + for x in 0..2 { + let p = out.get_pixel(x, 0).0; + assert!(p[3] == 0 || close(p, [200, 30, 30]), "{f:?} pixel {x}: {p:?}"); + } + } + } + + #[test] + fn fitted_keeps_proportions() { + let img = DynamicImage::ImageRgba8(RgbaImage::new(400, 100)); + let out = fitted(img, 64, 64, Resample::Average); + assert_eq!((out.width(), out.height()), (64, 16)); + } + + #[test] + fn opaque_and_alpha_free_images_scale_as_image_scales_them() { + let rgb = DynamicImage::ImageRgb8(image::RgbImage::from_fn(5, 3, |x, y| image::Rgb([x as u8 * 40, y as u8 * 60, 7]))); + let ours = resized(rgb.clone(), 2, 2, Resample::Filter(FilterType::Triangle)); + assert_eq!(ours, rgb.resize_exact(2, 2, FilterType::Triangle)); + let opaque = DynamicImage::ImageRgba8(rgb.to_rgba8()); + assert_eq!(resized(opaque.clone(), 2, 2, Resample::Average), opaque.thumbnail_exact(2, 2)); + } + + #[test] + fn a_wholly_clear_result_is_transparent_black() { + let img = DynamicImage::ImageRgba8(RgbaImage::from_pixel(4, 4, image::Rgba([90, 90, 90, 0]))); + assert_eq!(resized(img, 1, 1, Resample::Average).into_rgba8().get_pixel(0, 0).0, [0, 0, 0, 0]); + } + + #[test] + fn premultiply_and_unpremultiply_scale_beside_a_separate_alpha() { + // Two pixels of inks, the second clear: averaged, the first one's inks remain. + let mut px = vec![40, 80, 120, 160, 0, 0, 0, 0]; + premultiply(&mut px, &[255, 0]); + let img = RgbaImage::from_raw(2, 1, px).unwrap(); + let mut out = image::imageops::thumbnail(&img, 1, 1).into_raw(); + let alpha = image::imageops::thumbnail(&image::GrayImage::from_raw(2, 1, vec![255, 0]).unwrap(), 1, 1).into_raw(); + unpremultiply(&mut out, &alpha); + let want = [40, 80, 120, 160]; + assert!(out.iter().zip(want).all(|(&c, w)| times_alpha(c, alpha[0]).abs_diff(times_alpha(w, alpha[0])) <= 1), "{out:?} {alpha:?}"); + } +} diff --git a/crates/doc/src/selection.rs b/crates/doc/src/selection.rs index 4ef6446247..e97a4b0cc1 100644 --- a/crates/doc/src/selection.rs +++ b/crates/doc/src/selection.rs @@ -49,6 +49,13 @@ pub struct Selection { /// it when no object is selected to align to it. #[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, + /// 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 /// ([`Document::new_art`]). Undo, Redo and a failed batch restore it with the selection, and /// the engine then sets the document's from it. Editing state, never saved. @@ -98,6 +105,7 @@ impl Selection { self.slices.clear(); self.guides.clear(); self.key_guide = None; + self.key_anchor = None; self.symbol_part = None; self.on_path_member = None; } @@ -113,9 +121,15 @@ impl Selection { self.set([instance]); self.symbol_part = Some(SymbolPart { instance, path }); } - /// Is there a key for Align: an object or a guide? + /// Is there a key for Align: an object, a guide or an anchor point? pub fn has_key(&self) -> bool { - self.key.is_some() || self.key_guide.is_some() + self.key.is_some() || self.key_guide.is_some() || self.key_anchor.is_some() + } + /// Where the key anchor ([`Self::key_anchor`]) is. `None` without one, or when the point is + /// gone from its path. + pub fn key_anchor_point(&self, doc: &Document) -> Option { + let (id, (si, ai)) = self.key_anchor?; + Some(doc.node(id)?.path_data()?.subpaths.get(si)?.anchors.get(ai)?.p) } pub fn set(&mut self, ids: impl IntoIterator) { self.clear(); @@ -143,6 +157,9 @@ impl Selection { if self.key == Some(id) { self.key = None; } + if self.key_anchor.is_some_and(|(k, _)| k == id) { + self.key_anchor = None; + } } /// [`Self::remove`] for each of `ids`, going through the selected objects once. pub fn remove_all(&mut self, ids: impl IntoIterator) { @@ -162,6 +179,9 @@ impl Selection { if self.key.is_some_and(|k| ids.contains(&k)) { self.key = None; } + if self.key_anchor.is_some_and(|(k, _)| ids.contains(&k)) { + self.key_anchor = None; + } } /// Select slices `ids` (see [`Selection::slices`]) and nothing else. pub fn set_slices(&mut self, ids: impl IntoIterator) { @@ -271,6 +291,40 @@ impl Selection { if self.key.is_some() || self.objects.is_empty() || self.key_guide.is_some_and(|k| !self.guides.contains(&k)) { self.key_guide = None; } + // A key anchor needs its point on its path and selected as an anchor point (not as a + // selected segment's end), with another point selected too: another anchor, or a path + // selected whole (Align and Distribute act on path points only). It takes the place of a + // key object or key guide. + let path_of = |o: &NodeId| found.get(o).and_then(|p| doc.node_at(p)).and_then(|n| n.path_data()); + let whole_path = |o: &NodeId| !self.anchors.contains_key(o) && path_of(o).is_some_and(|path| path.anchors().next().is_some()); + // Selected anchor points that are on their paths, counted up to two. + let points = || { + self.anchors + .iter() + .flat_map(|(o, set)| { + let path = path_of(o); + set.iter().filter(move |&&(si, ai)| path.is_some_and(|p| p.subpaths.get(si).is_some_and(|sp| ai < sp.anchors.len()))) + }) + .take(2) + .count() + }; + 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.contains_key(&id)) + && found + .get(&id) + .and_then(|p| doc.node_at(p)) + .and_then(|n| n.path_data()) + .is_some_and(|path| path.subpaths.get(si).is_some_and(|sp| ai < sp.anchors.len())) + && (points() >= 2 || self.objects.iter().any(whole_path)) + }); + if anchor_kept { + self.key = None; + self.key_guide = None; + } else { + self.key_anchor = None; + } // A selected part needs its instance selected alone, with no guides, its symbol dynamic // and the object still in the symbol's art as a path, compound path or type, where neither // it nor a group or layer around it is hidden, locked or a template. @@ -348,6 +402,9 @@ impl Selection { if self.key.is_some_and(|k| gone.contains(&k)) { self.key = None; } + if self.key_anchor.is_some_and(|(k, _)| gone.contains(&k)) { + self.key_anchor = None; + } } /// Target `id` (see [`Selection::target`]): a layer gets its visible, unlocked art selected /// (the art of its sublayers too), anything else is selected itself. diff --git a/crates/doc/src/selection/tests.rs b/crates/doc/src/selection/tests.rs index b6090f8993..db8e6f930c 100644 --- a/crates/doc/src/selection/tests.rs +++ b/crates/doc/src/selection/tests.rs @@ -45,6 +45,32 @@ fn remove_all_does_what_removing_each_does() { assert_eq!(none, s); } +#[test] +fn remove_all_does_what_removing_each_does_to_a_key_anchor_and_symbol_part() { + for kept in [false, true] { + let mut s = Selection::default(); + for i in 1..=4 { + s.add(NodeId(i)); + } + s.anchors.insert(NodeId(2), BTreeSet::from([(0, 0), (0, 1)])); + s.anchors.insert(NodeId(3), BTreeSet::from([(0, 2)])); + s.key_anchor = Some((NodeId(2), (0, 0))); + s.symbol_part = Some(SymbolPart { instance: NodeId(1), path: vec![0] }); + s.guides = vec![NodeId(10)]; + s.key_guide = Some(NodeId(10)); + let ids = if kept { [NodeId(3), NodeId(8), NodeId(3)] } else { [NodeId(2), NodeId(8), NodeId(2)] }; + let mut one_by_one = s.clone(); + for id in ids { + one_by_one.remove(id); + } + let mut all = s.clone(); + all.remove_all(ids); + assert_eq!(all, one_by_one); + assert_eq!(all.key_anchor.is_some(), kept); + assert_eq!((all.symbol_part.clone(), all.guides.clone(), all.key_guide), (None, vec![NodeId(10)], Some(NodeId(10)))); + } +} + #[test] fn guides_are_selected_on_their_own() { let mut s = Selection::default(); 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/stored_art.rs b/crates/doc/src/stored_art.rs index e623e0ed0e..cc0832b733 100644 --- a/crates/doc/src/stored_art.rs +++ b/crates/doc/src/stored_art.rs @@ -20,6 +20,8 @@ pub enum StoredRoot { GraphDesign(usize), /// Object `art` of pattern swatch `pattern` of [`Document::patterns`]. Pattern { pattern: usize, art: usize }, + /// Root `index` of [`Document::mounted_art`]. + Mounted(usize), } /// Where a stored object is: its root and, inside opacity-mask art, the object that mask belongs @@ -170,10 +172,12 @@ impl Document { .iter() .enumerate() .flat_map(|(p, def)| def.art.iter().enumerate().map(move |(a, n)| (n, StoredRoot::Pattern { pattern: p, art: a }))); - symbols.chain(designs).chain(patterns) + let mounted = self.mounted_art.iter().enumerate().map(|(i, (n, _))| (n, StoredRoot::Mounted(i))); + symbols.chain(designs).chain(patterns).chain(mounted) } - /// Every root of stored art: the layers, then the art of symbols, graph designs and patterns. + /// Every root of stored art: the layers, then the art of symbols, graph designs and patterns, + /// then [`Document::mounted_art`]. fn stored_roots(&self) -> impl Iterator, StoredRoot)> { self.layers.iter().enumerate().map(|(i, l)| (l, StoredRoot::Layer(i))).chain(self.definition_roots()) } @@ -185,12 +189,13 @@ impl Document { StoredRoot::Symbol(i) => self.symbols.get_mut(i).map(|s| &mut s.art), StoredRoot::GraphDesign(i) => self.graph_designs.get_mut(i).map(|g| &mut g.art), StoredRoot::Pattern { pattern, art } => self.patterns.get_mut(pattern)?.art.get_mut(art), + StoredRoot::Mounted(i) => self.mounted_art.get_mut(i).map(|(n, _)| n), } } /// Visit every stored object with its place: the layer tree with the opacity-mask art of its /// objects, then the art of symbols, graph designs and pattern swatches (their definitions, - /// once each, never the copies instances and tiles draw). + /// once each, never the copies instances and tiles draw), then [`Document::mounted_art`]. pub fn visit_stored<'a>(&'a self, mut f: impl FnMut(&'a Node, StoredPlace)) { self.visit_stored_arcs(|n, place| f(n, place)); } @@ -238,6 +243,29 @@ impl Document { /// visited before them (the layer tree's own objects first) a new id, so every stored object /// can be named by its id. Returns how many changed; the id counter then stands above them. pub(crate) fn renumber_stored_duplicates(&mut self) -> usize { + self.renumber_duplicates_in(|_| true) + } + + /// Raises the id counter above the ids of [`Document::mounted_art`]'s objects, then gives those + /// objects whose id is 0, past the id range, or already taken by an object visited before them + /// (every other stored object first) a new id, as [`Self::renumber_stored_duplicates`] gives + /// them. Returns how many changed. + pub fn number_mounted_art(&mut self) -> usize { + let mut max = 0; + for (i, (root, _)) in self.mounted_art.iter().enumerate() { + visit(root, StoredPlace { root: StoredRoot::Mounted(i), mask_of: None }, &mut |n, _| { + if n.id.0 < MAX_NEXT_ID { + max = max.max(n.id.0); + } + }); + } + self.raise_next_id(max.saturating_add(1)); + self.renumber_duplicates_in(|r| matches!(r, StoredRoot::Mounted(_))) + } + + /// [`Self::renumber_stored_duplicates`] for the roots `pick` holds for only; the objects of the + /// others still count as taken. + fn renumber_duplicates_in(&mut self, pick: impl Fn(StoredRoot) -> bool) -> usize { let mut seen: HashSet = HashSet::new(); for l in &self.layers { l.walk(&mut |n| { @@ -250,9 +278,9 @@ impl Document { // Per root, the visiting indices of the nodes that take a new id. let mut fresh: Vec<(StoredRoot, HashSet)> = vec![]; for (root, r) in self.stored_roots() { - let (mut i, mut here) = (0, HashSet::new()); + let (mut i, mut here, take) = (0, HashSet::new(), pick(r)); visit(root, StoredPlace { root: r, mask_of: None }, &mut |n, place| { - if !place.in_layers() && (n.id.0 == 0 || n.id.0 >= MAX_NEXT_ID || !seen.insert(n.id)) { + if !place.in_layers() && (n.id.0 == 0 || n.id.0 >= MAX_NEXT_ID || !seen.insert(n.id)) && take { here.insert(i); } i += 1; @@ -355,6 +383,30 @@ mod tests { assert_eq!(d, again); } + /// Mounted art is found and changed by id after the other stored art, and numbering it gives + /// its objects that repeat another stored object's id, or have none, new ids above the counter, + /// leaving every other object's id and its own unique ones as they are. + #[test] + fn mounted_art_is_found_and_numbered_after_the_rest() { + let mut d = doc([12, 13, 14]); + let owner = serde_json::json!({ "kind": "brush" }); + d.mounted_art = vec![(Arc::new(masked(10, rect(0))), owner.clone()), (Arc::new(rect(15)), owner)]; + assert_eq!(d.stored_node(NodeId(15)).map(|(_, p)| p.root), Some(StoredRoot::Mounted(1))); + let before = d.clone(); + assert_eq!(d.number_mounted_art(), 2); + let mut ids = vec![]; + d.visit_stored(|n, _| ids.push(n.id.0)); + let unique: HashSet = ids.iter().copied().collect(); + assert_eq!(unique.len(), ids.len(), "{ids:?}"); + assert_eq!(&ids[..6], &[d.layers[0].id.0, 10, 11, 12, 13, 14], "the other art keeps its ids"); + assert_eq!(ids[8], 15, "a unique id is kept"); + assert!(ids.iter().all(|id| *id < d.peek_next_id()), "{ids:?} {}", d.peek_next_id()); + assert!(Arc::ptr_eq(&d.symbols[0].art, &before.symbols[0].art) && Arc::ptr_eq(&d.mounted_art[1].0, &before.mounted_art[1].0)); + d.stored_node_mut(NodeId(15)).unwrap().name = Some("changed".into()); + assert_eq!(d.mounted_art[1].0.name.as_deref(), Some("changed")); + assert_eq!(d.number_mounted_art(), 0, "a second pass changes nothing"); + } + #[test] fn renumbered_objects_on_path_keep_their_path_and_members() { // A symbol's Objects on Path group whose path repeats the layer's object 10 and whose diff --git a/crates/doc/src/style_libs.rs b/crates/doc/src/style_libs.rs index 1952060663..34faf1f9c4 100644 --- a/crates/doc/src/style_libs.rs +++ b/crates/doc/src/style_libs.rs @@ -162,6 +162,7 @@ pub const STYLE_LIBRARIES: &[BuiltinStyleLibrary] = &[ BuiltinStyleLibrary { id: "blends-transparency", name: "Blends and Transparency", make: blends_transparency }, BuiltinStyleLibrary { id: "game-hud", name: "Game HUD", make: game_hud }, BuiltinStyleLibrary { id: "status-effects", name: "Status Effects", make: status_effects }, + BuiltinStyleLibrary { id: "neon-glow", name: "Neon & Glow", make: neon_glow }, ]; /// Built-in library `id`, made once. @@ -619,6 +620,44 @@ fn status_effects() -> Vec { ] } +/// Neon & Glow: original multi-layer procedural styles with neon tubes, laser beams, and glowing halos. +fn neon_glow() -> Vec { + vec![ + style( + "Cyan Neon", + vec![S(StrokeLayer { opacity: 0.7, ..round("#00e5ff", 6.0) }), S(round("#ffffff", 1.5))], + vec![fx("stylize.dropShadow", json!({"mode": "screen", "opacity": 85.0, "x": 0.0, "y": 0.0, "blur": 8.0, "color": "#00e5ff"}))], + ), + GraphicStyle { + blend: BlendMode::Screen, + ..style( + "Magenta Laser", + vec![S(StrokeLayer { blend: BlendMode::Screen, ..round("#ff007f", 5.0) }), S(round("#ffffff", 1.5))], + vec![fx("stylize.outerGlow", json!({"mode": "screen", "opacity": 90.0, "blur": 8.0, "color": "#ff007f"}))], + ) + }, + style( + "Amber Tube", + vec![S(StrokeLayer { opacity: 0.8, ..round("#ff8c00", 6.0) }), S(round("#ffea00", 1.5))], + vec![fx("stylize.outerGlow", json!({"mode": "screen", "opacity": 85.0, "blur": 8.0, "color": "#ff8c00"}))], + ), + style( + "Electric Lime", + vec![S(StrokeLayer { opacity: 0.75, ..round("#39ff14", 6.0) }), S(round("#ffffff", 1.5))], + vec![fx("stylize.outerGlow", json!({"mode": "screen", "opacity": 90.0, "blur": 8.0, "color": "#39ff14"}))], + ), + style( + "Pulse Violet", + vec![S(StrokeLayer { opacity: 0.75, ..round("#7b2cbf", 5.0) }), S(round("#e0aaff", 1.5))], + vec![ + fx("stylize.innerGlow", json!({"mode": "screen", "opacity": 75.0, "blur": 6.0, "color": "#c77dff", "source": "edge"})), + fx("stylize.outerGlow", json!({"mode": "screen", "opacity": 85.0, "blur": 8.0, "color": "#7b2cbf"})), + ], + ), + style("Cobalt Phosphor", vec![S(round("#0047ab", 6.0)), S(round("#ffffff", 1.5))], vec![fx("blur.gaussian", json!({"radius": 2.0}))]), + ] +} + #[cfg(test)] mod tests { use super::*; @@ -750,4 +789,36 @@ mod tests { let Paint::Gradient(gp) = g.appearance.fill_paint() else { panic!("a gradient") }; assert!(gp.swatch.is_none() && gp.gradient.stops.iter().all(|s| s.swatch.is_none() && s.tint == 1.0)); } + + #[test] + fn neon_and_glow_styles_are_defined_with_multi_strokes_and_effects() { + let lib = builtin_style_library("neon-glow").expect("neon-glow library exists"); + assert_eq!(lib.name, "Neon & Glow"); + assert_eq!(lib.len(), 6); + let names: Vec<&str> = lib.styles.iter().map(|g| g.name.as_str()).collect(); + assert_eq!(names, ["Cyan Neon", "Magenta Laser", "Amber Tube", "Electric Lime", "Pulse Violet", "Cobalt Phosphor"]); + for g in &lib.styles { + let strokes = g.appearance.items.iter().filter(|i| matches!(i, AppearanceItem::Stroke(_))).count(); + assert!(strokes >= 2, "{} has {} strokes, expected >= 2", g.name, strokes); + assert!(!g.appearance.effects.is_empty(), "{} has effects", g.name); + } + let cyan = lib.style("Cyan Neon").unwrap(); + assert_eq!(cyan.appearance.effects[0].id, "stylize.dropShadow"); + let magenta = lib.style("Magenta Laser").unwrap(); + assert_eq!(magenta.blend, BlendMode::Screen); + let pulse = lib.style("Pulse Violet").unwrap(); + let pulse_fx: Vec<&str> = pulse.appearance.effects.iter().map(|e| e.id.as_str()).collect(); + assert_eq!(pulse_fx, ["stylize.innerGlow", "stylize.outerGlow"]); + let cobalt = lib.style("Cobalt Phosphor").unwrap(); + assert_eq!(cobalt.appearance.effects[0].id, "blur.gaussian"); + } + + #[test] + fn neon_glow_round_trips_through_vcstyles() { + let lib = builtin_style_library("neon-glow").unwrap(); + let text = write(&lib); + assert!(sniff(&text)); + let read_back = read(&text, "Fallback").unwrap(); + assert_eq!(*lib, read_back); + } } diff --git a/crates/doc/src/swatches.rs b/crates/doc/src/swatches.rs index 844aa8c810..9c25427846 100644 --- a/crates/doc/src/swatches.rs +++ b/crates/doc/src/swatches.rs @@ -8,6 +8,7 @@ //! change; [`Document::map_paints`] replaces whole paints of any kind in the same places. use std::collections::{HashMap, HashSet}; +use std::ops::ControlFlow; use std::sync::Arc; use vectorcraft_color::swatch::REGISTRATION; @@ -206,11 +207,13 @@ impl Document { impl Document { /// Visit every paint held by the art (opacity masks included), symbol definitions, pattern /// tiles and graphic styles (fills, strokes and text runs), and the colour of every - /// gradient-mesh point as a solid paint. + /// gradient-mesh point as a solid paint. A graph's default black legend fill is left out. pub fn visit_paints(&self, f: &mut dyn FnMut(&Paint)) { let mut tree = |n: &Node| { walk_with_masks(n, &mut |m| { - node_paints(m).chain(override_paints(m)).chain(graph_paints(m)).for_each(&mut *f); + node_paints(m).chain(override_paints(m)).for_each(&mut *f); + let default_legend = default_legend_fill(m); + graph_paints(m).enumerate().filter(|(i, _)| Some(*i) != default_legend).for_each(|(_, p)| f(p)); if let NodeKind::Mesh(mesh) = &m.kind { mesh.points.iter().for_each(|p| f(&Paint::solid(p.color))); } @@ -338,18 +341,39 @@ fn map_style_paint(attrs: &mut serde_json::Map, key: /// and gradient stops (with their link), a dynamic symbol instance's own paints /// ([`override_paints`]), then mesh points (unlinked), in paint order. pub fn node_colors(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) { - n.walk(&mut |m| { + let _ = try_node_colors::<()>(n, &mut |c, s| { + f(c, s); + ControlFlow::Continue(()) + }); +} + +/// Whether the subtree of `n` holds any color [`node_colors`] visits. It stops at the first one. +pub fn node_has_colors(n: &Node) -> bool { + try_node_colors(n, &mut |_, _| ControlFlow::Break(())).is_break() +} + +/// [`node_colors`] that ends at the first color for which `f` returns [`ControlFlow::Break`]: no +/// paint or node after it is visited. +fn try_node_colors(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>) -> ControlFlow) -> ControlFlow { + n.try_walk(&mut |m| { for p in node_paints(m).chain(override_paints(m)) { match p { - Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref()), - Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| f(&s.color, s.swatch.as_deref())), + Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref())?, + Paint::Gradient(g) => { + for s in &g.gradient.stops { + f(&s.color, s.swatch.as_deref())?; + } + } _ => {} } } if let NodeKind::Mesh(mesh) = &m.kind { - mesh.points.iter().for_each(|p| f(&p.color, None)); + for p in &mesh.points { + f(&p.color, None)?; + } } - }); + ControlFlow::Continue(()) + }) } fn item_paint(it: &AppearanceItem) -> &Paint { @@ -382,14 +406,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()) } @@ -398,12 +422,25 @@ fn graph_paints_mut(g: &mut crate::graph::GraphSpec) -> impl Iterator Option { + let g = n.extras().graph.as_deref()?; + let l = &g.label_styles; + if l.legend.is_none() || !g.picks_legend_fill() { + return None; + } + let series: usize = g.series_paints.iter().map(|s| usize::from(s.fill.is_some()) + usize::from(s.stroke.is_some())).sum(); + Some(series + 2 * (usize::from(l.values.is_some()) + usize::from(l.categories.is_some()))) +} + /// Mutable [`node_paints`], in the same order. pub fn node_paints_mut(n: &mut Node) -> impl Iterator { let runs = match &mut n.kind { @@ -446,11 +483,16 @@ fn map_node(n: &Node, f: &mut PaintFn) -> Option<(Node, usize)> { } } // A graph's series and label paints, which its marks and labels take when it is drawn again. - let graph: Vec<(usize, Paint)> = graph_paints(n).enumerate().filter_map(|(i, p)| f(p).map(|q| (i, q))).collect(); + // The default black legend fill, which is not the legend labels' own, stays black. + let default_legend = default_legend_fill(n); + let graph: Vec<(usize, Paint)> = + graph_paints(n).enumerate().filter(|(i, _)| Some(*i) != default_legend).filter_map(|(i, p)| f(p).map(|q| (i, q))).collect(); if !graph.is_empty() { count += graph.len(); let m = out.get_or_insert_with(|| n.clone()); if let Some(spec) = m.extras_if_any().and_then(|e| e.graph.as_deref_mut()) { + // A legend fill of the labels' own stays theirs when the change makes it black. + spec.label_styles.mark_own_legend_fill(); let mut graph = graph.into_iter().peekable(); for (i, p) in graph_paints_mut(spec).enumerate() { if graph.peek().is_some_and(|c| c.0 == i) @@ -698,6 +740,14 @@ mod tests { paint: crate::SeriesPaint { fill: Some(red.clone()), ..Default::default() }, ..Default::default() }), + axis_rows: Some(crate::LabelRows { + paint: crate::SeriesPaint { stroke: Some(red.clone()), ..Default::default() }, + ..Default::default() + }), + ring_rows: Some(crate::LabelRows { + paint: crate::SeriesPaint { stroke: Some(red.clone()), ..Default::default() }, + ..Default::default() + }), ..Default::default() }, ..Default::default() @@ -705,21 +755,79 @@ mod tests { d.node_mut(a).unwrap().extras_mut().graph = Some(Box::new(spec)); let mut seen = 0; d.visit_paints(&mut |p| seen += usize::from(*p == red)); - assert_eq!(seen, 5, "the fill and the graph's series fill, series stroke, legend fill and value label fill row"); + assert_eq!(seen, 7, "the fill and the graph's series fill, series stroke, legend fill, value label fill row and axis and ring stroke rows"); let blue = Color::rgb(0.0, 0.0, 1.0); let mut to_blue = |c: &mut Color, s: &mut Option, _: &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)); } + #[test] + fn a_legend_fill_mapped_to_black_stays_the_labels_own() { + let (mut d, a, _) = doc(); + let red = linked(Color::rgb(1.0, 0.0, 0.0), "Brand"); + let spec = crate::graph::GraphSpec { + label_styles: crate::graph::LabelStyles { legend: Some(crate::CharStyle { fill: red, ..Default::default() }), ..Default::default() }, + ..Default::default() + }; + assert!(spec.label_styles.legend_fill_is_own() && !spec.label_styles.legend_fill_set, "not black, saved without the mark"); + d.node_mut(a).unwrap().extras_mut().graph = Some(Box::new(spec)); + let mut to_black = |c: &mut Color, s: &mut Option, _: &mut f32| { + s.as_deref() == Some("Brand") && { + *c = Color::BLACK; + *s = None; + true + } + }; + assert_eq!(d.map_solid_paints(&mut to_black), 2, "the rectangle's fill and the legend fill"); + let styles = d.node(a).unwrap().extras().graph.clone().unwrap().label_styles; + assert_eq!(styles.legend.unwrap().fill, Paint::solid(Color::BLACK)); + assert!(styles.legend_fill_set, "the black fill is still the labels' own"); + } + + #[test] + fn the_default_black_legend_fill_is_left_as_it_is() { + use crate::graph::GraphKind; + // Only a pie with Legends in Wedges picks its legend labels' fill; the other graphs draw the kept black. + for (kind, in_wedges, picks) in [(GraphKind::Pie, true, true), (GraphKind::Pie, false, false), (GraphKind::Column, true, false)] { + let (mut d, a, _) = doc(); + let black = || crate::CharStyle { fill: Paint::solid(Color::BLACK), size: 11.0, ..Default::default() }; + let spec = crate::graph::GraphSpec { + kind, + legend: true, + pie_legend_in_wedges: in_wedges, + series_paints: vec![crate::SeriesPaint { fill: Some(Paint::solid(Color::BLACK)), ..Default::default() }], + label_styles: crate::graph::LabelStyles { values: Some(black()), legend: Some(black()), ..Default::default() }, + ..Default::default() + }; + let blacks = |d: &Document| { + let mut seen = 0; + d.visit_paints(&mut |p| seen += usize::from(*p == Paint::solid(Color::BLACK))); + seen + }; + let before = blacks(&d); + d.node_mut(a).unwrap().extras_mut().graph = Some(Box::new(spec)); + let want = if picks { 2 } else { 3 }; + assert_eq!(blacks(&d) - before, want, "{kind:?}, in wedges {in_wedges}: the series, value labels' and legend fills visited"); + let mut link_black = |c: &mut Color, s: &mut Option, _: &mut f32| *c == Color::BLACK && s.replace("Black".into()).is_none(); + assert_eq!(d.map_solid_paints_in(&[a], &mut link_black), want, "{kind:?}, in wedges {in_wedges}"); + let styles = d.node(a).unwrap().extras().graph.clone().unwrap().label_styles; + let legend = if picks { Paint::solid(Color::BLACK) } else { linked(Color::BLACK, "Black") }; + assert_eq!(styles.legend.unwrap().fill, legend, "{kind:?}, in wedges {in_wedges}: linked unless the pie picks the fill"); + assert_eq!(styles.values.unwrap().fill, linked(Color::BLACK, "Black")); + } + } + #[test] fn mapping_within_ids_visits_each_paint_once() { let (mut d, a, b) = doc(); @@ -735,4 +843,216 @@ mod tests { node_colors(d.node(b).unwrap(), &mut |c, s| colors.push((*c, s.map(str::to_string)))); assert_eq!(colors, [(Color::rgb(1.0, 0.0, 0.0), None)]); } + + /// The colors [`node_colors`] visits, in its order, by a [`Node::walk`] that reads the whole subtree. + fn full_walk(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) { + n.walk(&mut |m| { + for p in node_paints(m).chain(override_paints(m)) { + match p { + Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref()), + Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| f(&s.color, s.swatch.as_deref())), + _ => {} + } + } + if let NodeKind::Mesh(mesh) = &m.kind { + mesh.points.iter().for_each(|p| f(&p.color, None)); + } + }); + } + + /// Whether [`full_walk`] finds a color in `n`. + fn full_walk_has_colors(n: &Node) -> bool { + let mut found = false; + full_walk(n, &mut |_, _| found = true); + found + } + + /// The colors of `n` by [`full_walk`], in order. + fn full_walk_colors(n: &Node) -> Vec<(Color, Option)> { + let mut out = vec![]; + full_walk(n, &mut |c, s| out.push((*c, s.map(str::to_string)))); + out + } + + fn square(id: u64, fill: Paint, stroke: Paint) -> Node { + Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(fill, stroke, 1.0)) + } + + fn holder(id: u64, kind: fn(Vec>) -> NodeKind, children: Vec) -> Node { + Node::new(NodeId(id), kind(children.into_iter().map(Arc::new).collect())) + } + + /// One node of each kind of paint [`node_colors`] reads or skips, with whether it shows a color. + fn color_cases() -> Vec<(&'static str, Node, bool)> { + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let gradient = |stops: usize| { + let mut g = vectorcraft_color::Gradient::default(); + g.stops.truncate(stops); + Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(g))) + }; + let pattern = Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::IDENTITY }; + let area = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); + let mesh = crate::GradientMesh::for_path_with(&area, 2, 2, &|_| (Color::BLACK, 1.0)).unwrap(); + let mut empty_mesh = mesh.clone(); + empty_mesh.points.clear(); + let text = |fill: Paint| { + let style = crate::CharStyle { fill, stroke: Paint::None, ..Default::default() }; + let mut n = + Node::new(NodeId(20), NodeKind::Text(Box::new(crate::TextObject::point(vectorcraft_geom::Point::new(0.0, 0.0), "Hi", style)))); + n.appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into(); + n + }; + let image = |colorize: Option| { + let im = crate::ImageObject { + key: "k".into(), + width: 2, + height: 2, + xf: vectorcraft_geom::Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + }; + let mut n = Node::new(NodeId(21), NodeKind::Image(Box::new(im))); + n.appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into(); + n.extras_mut().colorize = colorize.map(Box::new); + n + }; + let overridden = |fill: Option| { + let mut n = square(22, Paint::None, Paint::None); + n.extras_mut().symbol_overrides = vec![crate::SymbolOverride { path: vec![0], fill, ..Default::default() }]; + n + }; + let masked = { + let mut n = square(23, Paint::None, Paint::None); + n.extras_mut().mask = Some(Box::new(crate::OpacityMask::new(square(24, red.clone(), Paint::None), true))); + n + }; + let group = |children| NodeKind::Group { children, clip: false }; + let clip = |children| NodeKind::Group { children, clip: true }; + let compound = |children| NodeKind::Compound { children, rule: Default::default() }; + let blend = |children| NodeKind::Blend { children, spec: Default::default() }; + let blank = |id| square(id, Paint::None, Paint::None); + vec![ + ("no paint", blank(1), false), + ("solid fill", square(2, red.clone(), Paint::None), true), + ("solid stroke", square(3, Paint::None, red.clone()), true), + ("pattern only", square(4, pattern.clone(), pattern.clone()), false), + ("gradient without stops", square(5, gradient(0), Paint::None), false), + ("gradient with stops", square(6, gradient(2), Paint::None), true), + ("mesh with points", Node::new(NodeId(7), NodeKind::Mesh(mesh)), true), + ("mesh without points", Node::new(NodeId(8), NodeKind::Mesh(empty_mesh)), false), + ("text run fill", text(red.clone()), true), + ("text without paint", text(Paint::None), false), + ("image colorize", image(Some(red.clone())), true), + ("image without colorize", image(None), false), + ("image with a pattern colorize", image(Some(pattern.clone())), false), + ("symbol override fill", overridden(Some(red.clone())), true), + ("symbol override without paint", overridden(None), false), + ("color only in the opacity mask", masked, false), + ("group, color first", holder(30, group, vec![square(31, red.clone(), Paint::None), blank(32), blank(33)]), true), + ("group, color last", holder(34, group, vec![blank(35), blank(36), square(37, red.clone(), Paint::None)]), true), + ("group without color", holder(38, group, vec![blank(39), blank(40)]), false), + ("clip group", holder(41, clip, vec![blank(42), square(43, red.clone(), Paint::None)]), true), + ("compound shape", holder(44, compound, vec![blank(45), square(46, gradient(3), Paint::None)]), true), + ("blend", holder(47, blend, vec![blank(48), blank(49)]), false), + ( + "nested groups, color deepest", + holder(50, group, vec![blank(51), holder(52, group, vec![holder(53, group, vec![blank(54), square(55, red.clone(), Paint::None)])])]), + true, + ), + ] + } + + #[test] + fn has_colors_matches_the_full_walk() { + for (label, n, expected) in color_cases() { + let all = full_walk_colors(&n); + assert_eq!(node_has_colors(&n), full_walk_has_colors(&n), "{label}"); + assert_eq!(full_walk_has_colors(&n), !all.is_empty(), "{label}"); + assert_eq!(node_has_colors(&n), expected, "{label}"); + let mut listed = vec![]; + node_colors(&n, &mut |c, s| listed.push((*c, s.map(str::to_string)))); + assert_eq!(listed, all, "{label}: node_colors lists the same colors in the same order"); + } + } + + #[test] + fn has_colors_stops_at_the_first_color() { + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let mut stops = vectorcraft_color::Gradient::default(); + stops.stops.push(stops.stops[0].clone()); + let gradient = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(stops))); + let mut later = vec![square(2, gradient, red.clone())]; + later.extend((3..100).map(|id| square(id, red.clone(), red.clone()))); + let n = holder(1, |children| NodeKind::Group { children, clip: false }, later); + let (mut colors, mut nodes) = (0, 0); + let flow = try_node_colors(&n, &mut |_, _| { + colors += 1; + ControlFlow::Break(()) + }); + assert!(flow.is_break()); + assert_eq!(colors, 1, "the first gradient stop ends the walk: no later stop, stroke or object is read"); + let flow = n.try_walk(&mut |m| { + nodes += 1; + if node_paints(m).next().is_some() { ControlFlow::Break(()) } else { ControlFlow::Continue(()) } + }); + assert!(flow.is_break()); + assert_eq!(nodes, 2, "the group, then its first member: none of the 97 after it"); + } + + /// Times [`node_has_colors`] against the full walk it replaces on one group of 100,000 paths, alternating the two in + /// one process: `cargo test --release -p vectorcraft-doc --lib -- --ignored --nocapture has_colors_timing`. + #[test] + #[ignore = "a timing, not a check"] + fn has_colors_timing() { + /// This thread's CPU time in nanoseconds on Linux; the elapsed time since `start` elsewhere. + fn clock(start: std::time::Instant) -> u128 { + let cpu = std::fs::read_to_string("/proc/thread-self/schedstat").ok(); + cpu.and_then(|s| s.split_whitespace().next()?.parse().ok()).unwrap_or_else(|| start.elapsed().as_nanos()) + } + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let count = 100_000u64; + let group = |colored: &dyn Fn(u64) -> bool| { + let children = + (0..count).map(|i| if colored(i) { square(i + 1, red.clone(), Paint::None) } else { square(i + 1, Paint::None, Paint::None) }); + holder(0, |children| NodeKind::Group { children, clip: false }, children.collect()) + }; + let cases = [ + ("every path filled", group(&|_| true)), + ("only the last path filled", group(&|i| i == count - 1)), + ("no path filled", group(&|_| false)), + ]; + let start = std::time::Instant::now(); + println!("clock: {}", if std::fs::metadata("/proc/thread-self/schedstat").is_ok() { "thread CPU time" } else { "wall clock" }); + // The time per call of `f` on `n`: batches of calls double until one takes at least 100 ms. + let per_call = |f: fn(&Node) -> bool, n: &Node| { + let mut calls = 1u32; + loop { + let t = clock(start); + for _ in 0..calls { + std::hint::black_box(f(std::hint::black_box(n))); + } + let spent = clock(start) - t; + if spent >= 100_000_000 || calls >= 1 << 30 { + return (spent as f64 / f64::from(calls), calls); + } + calls *= 2; + } + }; + for (label, n) in &cases { + assert_eq!(full_walk_has_colors(n), node_has_colors(n), "{label}"); + let (mut old, mut new) = (vec![], vec![]); + for _ in 0..7 { + old.push(per_call(full_walk_has_colors, n)); + new.push(per_call(node_has_colors, n)); + } + old.sort_by(|a, b| a.0.total_cmp(&b.0)); + new.sort_by(|a, b| a.0.total_cmp(&b.0)); + let (o, nw) = (old[3], new[3]); + println!( + "{label}: full walk {:.1} ns per call ({} calls), node_has_colors {:.1} ns per call ({} calls), median of 7 runs", + o.0, o.1, nw.0, nw.1 + ); + } + } } diff --git a/crates/doc/src/symbol_nine_slice.rs b/crates/doc/src/symbol_nine_slice.rs index 3c8c1b324d..4877ee7b57 100644 --- a/crates/doc/src/symbol_nine_slice.rs +++ b/crates/doc/src/symbol_nine_slice.rs @@ -463,8 +463,13 @@ impl NineSliceMap { /// /// Strokes keep their weight, as they do for any instance. pub fn place(&self, art: &Node, doc: &Document) -> Node { - let boxes = doc.symbol_boxes().quick(); - self.place_at(art, &boxes, 0) + self.place_with(art, &doc.symbol_boxes().quick()) + } + + /// [`Self::place`] with the instances in `art` measured by `boxes`, quick boxes or boxes + /// measuring symbol art. + pub(crate) fn place_with(&self, art: &Node, boxes: &SymbolBoxes) -> Node { + self.place_at(art, boxes, 0) } /// [`Self::place`] without clip groups, for writers that do not apply clipping (DXF, WMF): @@ -480,16 +485,25 @@ impl NineSliceMap { /// object drawn in clip groups counts one group plus a clip path and a copy for each cell its /// box reaches. That is never more than [`MAX_SLICE_GROWTH`] for each object of `art`. pub fn most_placed(&self, art: &Node, doc: &Document) -> u64 { - let boxes = doc.symbol_boxes().quick(); - self.most_at(art, &boxes, 0) + self.most_placed_with(art, &doc.symbol_boxes().quick()) + } + + /// [`Self::most_placed`] with the instances in `art` measured by `boxes`, quick boxes or boxes + /// measuring symbol art. + pub(crate) fn most_placed_with(&self, art: &Node, boxes: &SymbolBoxes) -> u64 { + self.most_at(art, boxes, 0) } /// The affine map that [`Self::place`] and [`Self::place_unclipped`] move object `n` by as one /// piece, with everything in it: the map of the cell its box lies in, or of the cell at the /// origin when it has no box. `None` when its box crosses a guide. pub fn one_cell(&self, n: &Node, doc: &Document) -> Option { - let boxes = doc.symbol_boxes().quick(); - let Some(b) = n.geometric(Some(&boxes)).map(|b| self.natural.transform_rect_bbox(b)).filter(|b| finite(*b)) else { + self.one_cell_with(n, &doc.symbol_boxes().quick()) + } + + /// [`Self::one_cell`] with the instances in `n` measured by `boxes`. + pub(crate) fn one_cell_with(&self, n: &Node, boxes: &SymbolBoxes) -> Option { + let Some(b) = n.geometric(Some(boxes)).map(|b| self.natural.transform_rect_bbox(b)).filter(|b| finite(*b)) else { return Some(self.cell_at(Point::ZERO)); }; let (cols, rows) = (self.x.cells(b.x0, b.x1), self.y.cells(b.y0, b.y1)); @@ -501,6 +515,11 @@ impl NineSliceMap { Self { clips: false, ..*self }.most_placed(art, doc) } + /// This map placing without clip groups, as [`Self::place_unclipped`] does. + pub(crate) fn unclipped(&self) -> Self { + Self { clips: false, ..*self } + } + /// [`Self::most_placed`] for `n` at nesting depth `depth`, following [`Self::place_at`]. fn most_at(&self, n: &Node, boxes: &SymbolBoxes, depth: u32) -> u64 { let whole = n.count_with_masks() as u64; @@ -671,7 +690,7 @@ impl NineSliceMap { } /// `n` moved by `a`, its strokes at their own weight. -fn transformed(n: &Node, a: Affine) -> Node { +pub(crate) fn transformed(n: &Node, a: Affine) -> Node { let mut out = n.clone(); out.transform(a, false); out @@ -765,10 +784,7 @@ impl Document { /// `None` when the symbol has no guides or the instance is at its natural size. The guides cut /// the art's box with the instances in it measured by their own art. pub fn symbol_slice_map(&self, name: &str, xf: Affine) -> Option { - let guides = self.symbol_nine_slice(name)?; - let sym = self.symbols.iter().find(|s| s.name == name)?; - let art = self.symbol_boxes().quick().art_bounds(name).or_else(|| sym.art.geometric_bounds())?; - NineSliceMap::new(guides, art, self.symbol_natural_xf(name), xf) + self.symbol_boxes().quick().slice_map(name, xf) } /// [`Self::symbol_slice_map`] with the guides cutting `art`, the symbol's art box already @@ -782,9 +798,10 @@ impl Document { /// it has them ([`NineSliceMap::place`]), otherwise by `xf`. `None` when placing it through /// the guides could make more than [`MAX_SYMBOL_NODES`] objects ([`NineSliceMap::most_placed`]). pub fn place_symbol_art(&self, name: &str, art: &Node, xf: Affine) -> Option { - match self.symbol_slice_map(name, xf) { - Some(m) if m.most_placed(art, self) > MAX_SYMBOL_NODES => None, - Some(m) => Some(m.place(art, self)), + let boxes = self.symbol_boxes().quick(); + match boxes.slice_map(name, xf) { + Some(m) if m.most_placed_with(art, &boxes) > MAX_SYMBOL_NODES => None, + Some(m) => Some(m.place_with(art, &boxes)), None => Some(transformed(art, xf)), } } @@ -795,8 +812,8 @@ impl Document { pub fn edited_nine_slice(&self) -> Option { let se = self.symbol_edit.as_ref()?; let guides = self.symbol_nine_slice(&se.symbol)?; - let sym = self.symbols.iter().find(|s| s.name == se.symbol)?; - let art = self.symbol_boxes().quick().art_bounds(&se.symbol).or_else(|| sym.art.geometric_bounds())?; + let boxes = self.symbol_boxes().quick(); + let art = boxes.art_bounds(&se.symbol).or_else(|| boxes.symbol_art(&se.symbol)?.geometric_bounds())?; let natural = self.symbol_natural_xf(&se.symbol); let b = natural.transform_rect_bbox(art); if !finite(b) || b.width() <= 1e-9 || b.height() <= 1e-9 || natural.determinant().abs() < 1e-18 { @@ -811,8 +828,9 @@ impl Document { /// [`Self::place_symbol_art`] for writers that do not apply clipping /// ([`NineSliceMap::place_unclipped`]). pub fn place_symbol_art_unclipped(&self, name: &str, art: &Node, xf: Affine) -> Option { - match self.symbol_slice_map(name, xf) { - Some(m) => (m.most_placed_unclipped(art, self) <= MAX_SYMBOL_NODES).then(|| m.place_unclipped(art, self)), + let boxes = self.symbol_boxes().quick(); + match boxes.slice_map(name, xf).map(|m| m.unclipped()) { + Some(m) => (m.most_placed_with(art, &boxes) <= MAX_SYMBOL_NODES).then(|| m.place_with(art, &boxes)), None => Some(transformed(art, xf)), } } 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/symbols.rs b/crates/doc/src/symbols.rs index dde6621993..a1d34e6adb 100644 --- a/crates/doc/src/symbols.rs +++ b/crates/doc/src/symbols.rs @@ -2,13 +2,14 @@ //! the document and measures it once, and an instance's bounds are its art's box placed by the //! instance's transform ([`Node::geometric_bounds_with`]). -use std::cell::{Cell, RefCell}; +use std::cell::{Cell, OnceCell, RefCell}; use std::collections::{HashMap, HashSet}; use std::sync::Arc; use vectorcraft_geom::{Affine, Rect}; -use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, Node, NodeKind, SYMBOL_HALF}; +use crate::symbol_nine_slice::transformed; +use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, NineSliceMap, Node, NodeKind, SYMBOL_HALF}; /// The box a symbol instance is measured by when its symbol's art has no box /// ([`SymbolBoxes::art`]), and in [`Node::geometric_bounds`]: the 20 × 20 square around the origin @@ -26,6 +27,9 @@ const MAX_REACHES: usize = 4096; /// A symbol's name and the bits of the linear part of a transform that places its art. type Placing = (String, [u64; 4]); +/// Each symbol name of a document → the index of the first symbol of that name. +pub(crate) type SymbolNames = HashMap; + /// A symbol's art measured in symbol space. #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct ArtBox { @@ -43,6 +47,11 @@ pub(crate) struct ArtBox { /// Whether the art holds an instance of a symbol with 9-slice guides, or of a symbol whose art /// holds one at any depth. pub(crate) sliced: bool, + /// The box of the regions that the live geometry effects of the clipping paths in the art give + /// them ([`crate::hit::set_clip_region`]), and of the instances in the art whose art has such + /// regions, each measured by [`Node::reach_bounds_with`]. `None` when nothing in the art has + /// one. + pub(crate) reshaped: Option, } /// The art boxes of a document's symbols, which [`Node::geometric_bounds_with`], @@ -51,6 +60,10 @@ pub(crate) struct ArtBox { /// symbols change. pub struct SymbolBoxes<'a> { doc: &'a Document, + /// Each symbol name of the document → the index of the first symbol of that name (the one a + /// name finds), made the first time a name is looked up ([`Self::symbol_art`]) or given by + /// [`Self::with_names`]. + names: OnceCell>, /// The art boxes measured so far, by symbol name (`None` for a symbol whose instances are /// measured by [`SYMBOL_SQUARE`]). measured: RefCell>>, @@ -89,6 +102,137 @@ pub struct SymbolBoxes<'a> { sliced_most: u64, /// The widths [`Self::measured_width`] has measured, by kind and symbol name. widths: RefCell>>, + /// While [`Self::consulted`] runs: the symbols whose art boxes [`Self::art`] has given outside + /// the measuring of symbol art. + consulted: RefCell>>, +} + +/// What the art boxes and nesting depths of a document's symbols depend on: each symbol's name and +/// art, the symbols' 9-slice guides (which symbols' art holds instances placed through guides), and +/// the inputs of the live geometry effects of clipping paths ([`crate::hit::set_clip_region`]). +/// Symbol sizes only move art placed through guides, which is measured on each call. Each symbol's +/// art is held by a weak pointer. While a weak pointer to an art's allocation is held, nothing else +/// can be at that address, and the art can't be changed in place (`Arc::make_mut` moves it), so art +/// changed in any way no longer matches, as in the cache of `Document::inline_cycles`. +struct KeptKey { + symbols: Vec<(String, std::sync::Weak)>, + guides: Option, + inputs: (u64, bool), +} + +impl KeptKey { + /// The key of the document's 9-slice guides. + const GUIDES: &str = crate::symbol_nine_slice::SYMBOL_NINE_SLICE; + + fn of(doc: &Document, inputs: (u64, bool)) -> Self { + KeptKey { + symbols: doc.symbols.iter().map(|s| (s.name.clone(), Arc::downgrade(&s.art))).collect(), + guides: doc.unknown.get(Self::GUIDES).cloned(), + inputs, + } + } + + /// Does this describe `doc`'s symbols as they are now, with inputs `inputs`? + fn is_of(&self, doc: &Document, inputs: (u64, bool)) -> bool { + self.inputs == inputs + && self.symbols.len() == doc.symbols.len() + && self.symbols.iter().zip(&doc.symbols).all(|((name, art), s)| std::ptr::eq(art.as_ptr(), Arc::as_ptr(&s.art)) && *name == s.name) + && self.guides.as_ref() == doc.unknown.get(Self::GUIDES) + } + + fn same(&self, other: &KeptKey) -> bool { + self.inputs == other.inputs + && self.symbols.len() == other.symbols.len() + && self.symbols.iter().zip(&other.symbols).all(|((n, a), (m, b))| a.ptr_eq(b) && n == m) + && self.guides == other.guides + } +} + +/// Art boxes, nesting depths and the name index measured by boxes made by +/// [`Document::kept_symbol_boxes`], kept for the next ones made for the same symbols. +struct Kept { + key: KeptKey, + names: Option>, + measured: HashMap>, + depths: HashMap>, +} + +/// How many sets of symbols [`Document::kept_symbol_boxes`] keeps measurements for on each thread: +/// clicks can alternate between two open documents. +const KEPT_SETS: usize = 2; + +thread_local! { + /// The measurements [`Document::kept_symbol_boxes`] keeps, the latest first. + static KEPT: RefCell> = const { RefCell::new(Vec::new()) }; +} + +/// [`SymbolBoxes`] made by [`Document::kept_symbol_boxes`], which keep their measurements for the +/// next ones when dropped. +pub(crate) struct KeptBoxes<'a> { + boxes: SymbolBoxes<'a>, + /// What the measurements depend on, under which they are kept. + key: Option, + /// Other boxes of the same document whose measurements are kept with these + /// ([`Self::keeping`]). + also: Option<&'a SymbolBoxes<'a>>, +} + +impl<'a> std::ops::Deref for KeptBoxes<'a> { + type Target = SymbolBoxes<'a>; + + fn deref(&self) -> &SymbolBoxes<'a> { + &self.boxes + } +} + +impl<'a> KeptBoxes<'a> { + /// These boxes, which also keep the art boxes and nesting depths `other` has measured when + /// dropped. `other` measures the same document, as the boxes of + /// [`Document::locked_artboards_kept`] do. + pub(crate) fn keeping(mut self, other: &'a SymbolBoxes<'a>) -> Self { + self.also = Some(other); + self + } +} + +impl Drop for KeptBoxes<'_> { + /// Keeps the measurements, adding them to those kept for the same symbols by other boxes alive + /// at the same time. Art boxes of symbols whose art holds instances of symbols with 9-slice + /// guides are left out: measuring them places art within a budget the boxes share + /// ([`SymbolBoxes::sliced_visual`]). + fn drop(&mut self) { + let Some(key) = self.key.take() else { return }; + let b = &self.boxes; + let mut measured = b.measured.take(); + let mut depths = b.depths.take(); + if let Some(other) = self.also { + for (name, a) in other.measured.borrow().iter() { + measured.entry(name.clone()).or_insert(*a); + } + for (name, d) in other.depths.borrow().iter() { + depths.entry(name.clone()).or_insert(*d); + } + } + measured.retain(|_, a| a.is_none_or(|a| !a.sliced)); + let mut kept = Kept { key, names: b.names.get().cloned(), measured, depths }; + // Nothing is kept while the thread ends or the list is in use. + let _ = KEPT.try_with(|k| { + if let Ok(mut k) = k.try_borrow_mut() { + if let Some(i) = k.iter().position(|e| e.key.same(&kept.key)) { + let other = k.remove(i); + kept.names = kept.names.or(other.names); + for (name, a) in other.measured { + kept.measured.entry(name).or_insert(a); + } + for (name, d) in other.depths { + kept.depths.entry(name).or_insert(d); + } + } + k.insert(0, kept); + k.truncate(KEPT_SETS); + } + }); + } } impl Document { @@ -96,6 +240,7 @@ impl Document { pub fn symbol_boxes(&self) -> SymbolBoxes<'_> { SymbolBoxes { doc: self, + names: OnceCell::new(), measured: RefCell::default(), depths: RefCell::default(), quick: Cell::new(false), @@ -110,8 +255,79 @@ impl Document { sliced_placed: Cell::new(0), sliced_most: MAX_SYMBOL_NODES, widths: RefCell::default(), + consulted: RefCell::default(), } } + + /// [`Self::symbol_boxes`] that start with the art boxes, nesting depths and name index measured + /// by the last such boxes made on this thread for the same symbols, and keep theirs for the next + /// ones when dropped. The measurements are made again when a symbol's name or art, the symbols' + /// 9-slice guides, or the inputs of the live geometry effects of clipping paths have + /// changed since. Measurements for the last [`KEPT_SETS`] sets of symbols are kept. + pub(crate) fn kept_symbol_boxes(&self) -> KeptBoxes<'_> { + self.kept_boxes(false) + } + + /// [`Self::symbol_boxes`] that start with a copy of the measurements + /// [`Self::kept_symbol_boxes`] would start with, and keep nothing themselves. + pub(crate) fn symbol_boxes_from_kept(&self) -> SymbolBoxes<'_> { + let mut kept = self.kept_boxes(true); + kept.key = None; + std::mem::replace(&mut kept.boxes, self.symbol_boxes()) + } + + /// [`Self::kept_symbol_boxes`], taking the kept measurements, or with `copy` copying them. + fn kept_boxes(&self, copy: bool) -> KeptBoxes<'_> { + let mut boxes = self.symbol_boxes(); + let inputs = crate::hit::clip_region_inputs(); + let found = KEPT + .try_with(|k| { + let mut k = k.try_borrow_mut().ok()?; + let i = k.iter().position(|e| e.key.is_of(self, inputs))?; + if copy { + let e = k.get(i)?; + let key = KeptKey { symbols: e.key.symbols.clone(), guides: e.key.guides.clone(), inputs }; + Some(Kept { key, names: e.names.clone(), measured: e.measured.clone(), depths: e.depths.clone() }) + } else { + Some(k.remove(i)) + } + }) + .ok() + .flatten(); + let key = match found { + Some(e) => { + if let Some(names) = e.names { + // The boxes were just made, so no index is set yet. + let _ = boxes.names.set(names); + } + *boxes.measured.get_mut() = e.measured; + *boxes.depths.get_mut() = e.depths; + e.key + } + None => KeptKey::of(self, inputs), + }; + KeptBoxes { boxes, key: Some(key), also: None } + } + + /// Each symbol name of this document → the index of the first symbol of that name (the one a + /// name finds). + pub(crate) fn symbol_names(&self) -> SymbolNames { + #[cfg(test)] + SYMBOLS_READ.with(|c| c.set(c.get() + self.symbols.len())); + let mut names = HashMap::with_capacity(self.symbols.len()); + for (i, s) in self.symbols.iter().enumerate() { + names.entry(s.name.clone()).or_insert(i); + } + names + } +} + +#[cfg(test)] +thread_local! { + /// How many symbols [`Document::symbol_names`] has read on this thread. + pub(crate) static SYMBOLS_READ: Cell = const { Cell::new(0) }; + /// How many art boxes [`SymbolBoxes::art`] has measured on this thread. + static ART_BOXES_MEASURED: Cell = const { Cell::new(0) }; } impl<'a> SymbolBoxes<'a> { @@ -120,6 +336,26 @@ impl<'a> SymbolBoxes<'a> { self.doc } + /// Makes these boxes find symbols by `names` ([`Document::symbol_names`]), made from the + /// document's symbols while they had the names and order they have now. + pub(crate) fn with_names(self, names: &Arc) -> Self { + let _ = self.names.set(names.clone()); + self + } + + /// The art of the first symbol of the document named `name`, found in time independent of the + /// number of symbols after the first lookup. + pub(crate) fn symbol_art(&self, name: &str) -> Option<&'a Arc> { + let doc: &'a Document = self.doc; + let names = self.names.get_or_init(|| Arc::new(doc.symbol_names())); + let i = *names.get(name)?; + match doc.symbols.get(i) { + Some(s) if s.name == name => Some(&s.art), + // Names that no longer match the symbols: the first symbol of that name. + _ => doc.symbols.iter().find(|s| s.name == name).map(|s| &s.art), + } + } + /// Makes these boxes measure every symbol instance as [`Node::reach_bounds_with`] does, by its /// art box alone. An instance that scales or turns stroked art then measures a little larger /// than with [`Node::visual_bounds_with`], and its art is not transformed to measure it. The @@ -160,21 +396,39 @@ impl<'a> SymbolBoxes<'a> { /// art boxes. Returns `None` when [`Self::depth`] is `None` and when the art has no finite /// bounds: instances of the symbol are then measured by [`SYMBOL_SQUARE`]. pub(crate) fn art(&self, name: &str) -> Option { - if let Some(b) = self.measured.borrow().get(name) { - return *b; + let cached = self.measured.borrow().get(name).copied(); + let b = cached.unwrap_or_else(|| { + #[cfg(test)] + ART_BOXES_MEASURED.with(|c| c.set(c.get() + 1)); + let b = self.measure_art(name, |art| self.in_art(|| art_box(art, self))).flatten(); + self.measured.borrow_mut().insert(name.to_string(), b); + b + }); + if b.is_some() + && let Some(seen) = self.consulted.borrow_mut().as_mut() + && !seen.contains(name) + { + seen.insert(name.to_string()); } - let b = self.measure_art(name, |art| self.in_art(|| art_box(art, self))).flatten(); - self.measured.borrow_mut().insert(name.to_string(), b); b } + /// Runs `measure`, and returns the names of the symbols whose art boxes it took from these + /// boxes, the art of symbols it measured left out: the symbols whose art the instances it + /// measured are measured by. + pub(crate) fn consulted(&self, measure: impl FnOnce()) -> HashSet { + let was = self.consulted.replace(Some(HashSet::new())); + measure(); + self.consulted.replace(was).unwrap_or_default() + } + /// Runs `measure` on the art of the symbol named `name`. Returns `None` when [`Self::depth`] /// is `None`, without running it. pub fn measure_art(&self, name: &str, measure: impl FnOnce(&Arc) -> R) -> Option { self.depth(name)?; - let sym = self.doc.symbols.iter().find(|s| s.name == name)?; + let art = self.symbol_art(name)?; self.runs.set(self.runs.get() + 1); - Some(measure(&sym.art)) + Some(measure(art)) } /// How many times [`Self::measure_art`] has run a measure on symbol art for these boxes, the @@ -297,10 +551,9 @@ impl<'a> SymbolBoxes<'a> { /// other symbols it reaches: the depth of each one it walks to the end, and `None` for those on /// the way down to a symbol that holds an instance of itself or nests too deep. fn find_depth(&self, name: &str, learned: &mut HashMap>) -> Option { - let art = |n: &str| self.doc.symbols.iter().find(|s| s.name == n).map(|s| &s.art); // The symbols on the way down from `name`: each with the symbols its art shows that are // still to be walked, and the deepest nesting found under it so far. - let mut path: Vec<(String, Vec, usize)> = vec![(name.to_string(), shown(self.doc, art(name)?), 0)]; + let mut path: Vec<(String, Vec, usize)> = vec![(name.to_string(), self.shown(self.symbol_art(name)?), 0)]; loop { let (_, todo, _) = path.last_mut()?; let Some(next) = todo.pop() else { @@ -330,8 +583,8 @@ impl<'a> SymbolBoxes<'a> { // Symbols nested MAX_DEPTH deep under `name`. None if path.len() >= MAX_DEPTH => return None, None => { - if let Some(a) = art(&next) { - let todo = shown(self.doc, a); + if let Some(a) = self.symbol_art(&next) { + let todo = self.shown(a); path.push((next, todo, 0)); } } @@ -379,9 +632,9 @@ impl<'a> SymbolBoxes<'a> { None => { // The most objects placing makes, the art of opacity masks included, is set aside // while the art is placed and measured, and what placing did not make is given back. - let art = &self.doc.symbols.iter().find(|s| s.name == name)?.art; - let most = match self.doc.symbol_slice_map(name, linear) { - Some(m) => m.most_placed(art, self.doc), + let art = self.symbol_art(name)?; + let most = match self.slice_map(name, linear) { + Some(m) => self.in_art(|| m.most_placed_with(art, self)), None => art.count_with_masks() as u64, }; let used = self.sliced_placed.get(); @@ -398,6 +651,14 @@ impl<'a> SymbolBoxes<'a> { v.map(|v| moved.transform_rect_bbox(v)) } + /// [`Document::symbol_slice_map`] with the guides cutting the art box these boxes measure for + /// the symbol (its geometric part, which does not depend on the mode of the boxes). + pub(crate) fn slice_map(&self, name: &str, xf: Affine) -> Option { + let guides = self.doc.symbol_nine_slice(name)?; + let art = self.art_bounds(name).or_else(|| self.symbol_art(name)?.geometric_bounds())?; + NineSliceMap::new(guides, art, self.doc.symbol_natural_xf(name), xf) + } + /// The box [`Self::placed_visual_within`] returns outside quick boxes. fn place_and_measure(&self, name: &str, xf: Affine, most: u64) -> Option { self.place_and_count(name, xf, most).and_then(|(v, _)| v) @@ -407,10 +668,10 @@ impl<'a> SymbolBoxes<'a> { /// opacity masks included. `None` when the art is not placed. fn place_and_count(&self, name: &str, xf: Affine, most: u64) -> Option<(Option, u64)> { self.measure_art(name, |art| { - let art = match self.doc.symbol_slice_map(name, xf) { - Some(m) if m.most_placed(art, self.doc) > most => return None, - Some(m) => m.place(art, self.doc), - None => self.doc.place_symbol_art(name, art, xf)?, + let art = match self.slice_map(name, xf) { + Some(m) if self.in_art(|| m.most_placed_with(art, self)) > most => return None, + Some(m) => self.in_art(|| m.place_with(art, self)), + None => transformed(art, xf), }; Some((self.in_art(|| art.visual(Some(self))), art.count_with_masks() as u64)) }) @@ -431,11 +692,28 @@ impl<'a> SymbolBoxes<'a> { fn in_art(&self, f: impl FnOnce() -> R) -> R { let pad = self.brush_art.replace(false); let strokes = self.art_strokes.replace(true); + let consulted = self.consulted.take(); let r = self.quickly(f); self.brush_art.set(pad); self.art_strokes.set(strokes); + *self.consulted.borrow_mut() = consulted; r } + + /// The names of the symbols of the document that the instances in `art` show, each once. + fn shown(&self, art: &Node) -> Vec { + let mut seen = HashSet::new(); + let mut names = vec![]; + art.walk(&mut |n| { + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind + && seen.insert(symbol.as_str()) + && self.symbol_art(symbol).is_some() + { + names.push(symbol.clone()); + } + }); + names + } } /// Records every symbol on `path` in `learned` as one whose instances are measured by @@ -447,21 +725,6 @@ fn give_up(path: &[(String, Vec, usize)], learned: &mut HashMap Vec { - let mut seen = HashSet::new(); - let mut names = vec![]; - art.walk(&mut |n| { - if let NodeKind::SymbolInstance { symbol, .. } = &n.kind - && seen.insert(symbol.as_str()) - && doc.symbols.iter().any(|s| s.name == *symbol) - { - names.push(symbol.clone()); - } - }); - names -} - /// Measures symbol art `art`, with the instances in it measured by `symbols`. fn art_box(art: &Arc, symbols: &SymbolBoxes) -> Option { let finite = |r: &Rect| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()); @@ -486,16 +749,27 @@ fn art_box(art: &Arc, symbols: &SymbolBoxes) -> Option { sliced |= symbols.doc.symbol_nine_slice(symbol).is_some() || symbols.art(symbol).is_some_and(|a| a.sliced); } }); - Some(ArtBox { geometric, visual, reach, effects, brush, sliced }) + let mut reshaped = None; + if effects { + art.walk(&mut |n| { + let b = match &n.kind { + NodeKind::SymbolInstance { symbol, .. } if symbols.art(symbol).is_some_and(|a| a.reshaped.is_some()) => n.reach(Some(symbols)), + _ if n.clips() => n.children().and_then(|c| c.first()).and_then(|c| crate::hit::reshaped_clip_box(c)), + _ => None, + }; + reshaped = vectorcraft_geom::union_opt(reshaped, b.filter(finite)); + }); + } + Some(ArtBox { geometric, visual, reach, effects, brush, sliced, reshaped }) } #[cfg(test)] mod tests { use vectorcraft_color::{Color, Paint}; - use vectorcraft_geom::shapes; + use vectorcraft_geom::{Point, shapes}; use super::*; - use crate::{Appearance, Symbol}; + use crate::{Appearance, NodeId, Symbol}; /// A rectangle filled black, with a `stroke` pt black stroke (0: none). fn rect(d: &mut Document, r: Rect, stroke: f64) -> Node { @@ -630,6 +904,39 @@ mod tests { assert_eq!(s.sliced_placed.get(), 13); } + #[test] + fn measuring_9_slice_instances_reads_the_symbol_list_once() { + // 2,000 symbols, then a frame with guides and a symbol with guides holding the frame + // scaled 2 times across, each shown by 200 instances scaled by different amounts. + let mut d = Document::new(200.0, 200.0); + for i in 0..2000 { + let dot = rect(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), 0.0); + symbol(&mut d, &format!("Dot {i}"), vec![dot]); + } + let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 1.0); + symbol(&mut d, "Panel", vec![frame]); + d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default())); + let wide = instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0)); + symbol(&mut d, "Holder", vec![wide]); + d.set_symbol_nine_slice("Holder", Some(crate::SymbolNineSlice::default())); + let scaled = |d: &mut Document, name: &str| -> Vec { + (1..=200).map(|i| instance(d, name, Affine::scale_non_uniform(1.0 + f64::from(i) / 100.0, 1.5))).collect() + }; + let (panels, holders) = (scaled(&mut d, "Panel"), scaled(&mut d, "Holder")); + // What each instance measures in boxes of its own. + let exact: Vec<_> = panels.iter().map(|n| n.visual_bounds_with(&d.symbol_boxes())).collect(); + let quick: Vec<_> = holders.iter().map(|n| n.visual_bounds_with(&d.symbol_boxes().quick())).collect(); + let read = || SYMBOLS_READ.with(Cell::get); + let before = read(); + let s = d.symbol_boxes(); + assert_eq!(panels.iter().map(|n| n.visual_bounds_with(&s)).collect::>(), exact); + let s = d.symbol_boxes().quick(); + assert_eq!(holders.iter().map(|n| n.visual_bounds_with(&s)).collect::>(), quick); + // Each set of boxes reads the list once to find symbols by name. + let symbols = d.symbols.len(); + assert!(read() - before <= 2 * symbols, "{} symbols read", read() - before); + } + #[test] fn missing_symbols_and_symbols_inside_themselves_measure_as_the_square() { let mut d = Document::new(200.0, 200.0); @@ -786,4 +1093,192 @@ mod tests { assert_eq!(s.effects_reach("Leaf", [2.0, 0.0, 0.0, 2.0], &measure(7.0)), 7.0); assert_eq!(runs.get(), MAX_REACHES + 2); } + + /// How many art boxes `f` measures on this thread. + fn art_boxes_measured(f: impl FnOnce()) -> usize { + let before = ART_BOXES_MEASURED.with(Cell::get); + f(); + ART_BOXES_MEASURED.with(Cell::get) - before + } + + /// A document with symbols "S 0" to "S 9", each a 10 × 10 square around the origin, and an + /// instance of each at (40 i + 20, 20). + fn ten_symbols() -> Document { + let mut d = Document::new(400.0, 100.0); + let layer = d.layers.first().map(|l| l.id); + for i in 0..10 { + let square = rect(&mut d, Rect::new(-5.0, -5.0, 5.0, 5.0), 0.0); + symbol(&mut d, &format!("S {i}"), vec![square]); + let at = instance(&mut d, &format!("S {i}"), Affine::translate((40.0 * f64::from(i) + 20.0, 20.0))); + d.insert(layer, usize::MAX, at).unwrap(); + } + d + } + + #[test] + fn hit_tests_measure_each_symbols_art_once_while_the_symbols_stay_the_same() { + use crate::hit::{self, HitOptions}; + let d = ten_symbols(); + let clicks = || { + for i in 0..10 { + let p = Point::new(40.0 * f64::from(i) + 20.0, 20.0); + assert!(hit::hit_test(&d, p, HitOptions::default()).is_some(), "instance {i} is hit"); + assert_eq!(hit::objects_at(&d, p, HitOptions::default(), None).len(), 1); + } + assert_eq!(hit::marquee(&d, Rect::new(0.0, 0.0, 400.0, 100.0), None, false).len(), 10); + }; + let first = art_boxes_measured(clicks); + assert_eq!(first, 10, "each symbol's art box measured once"); + assert_eq!(art_boxes_measured(clicks), 0, "art boxes measured again"); + } + + #[test] + fn hit_tests_measure_a_symbol_again_after_it_changes() { + use crate::hit::{self, HitOptions}; + let mut d = ten_symbols(); + // Past the square of "S 1" at (60, 20). + let past = Point::new(71.0, 20.0); + assert!(hit::hit_test(&d, past, HitOptions::default()).is_none()); + // The art grows 3 times in place: no other copy of it is held in the document. + Arc::make_mut(&mut d.symbols[1].art).transform(Affine::scale(3.0), false); + let measured = art_boxes_measured(|| assert!(hit::hit_test(&d, past, HitOptions::default()).is_some(), "the grown art is hit")); + assert!(measured > 0); + // New art for "S 2", 40 wide. + let wide = rect(&mut d, Rect::new(-20.0, -5.0, 20.0, 5.0), 0.0); + d.symbols[2].art = Arc::new(wide); + assert!(hit::hit_test(&d, Point::new(115.0, 20.0), HitOptions::default()).is_some(), "the new art is hit"); + // "S 3" renamed: its instance now shows the 20 × 20 square. + d.symbols[3].name = "Renamed".into(); + assert!(hit::hit_test(&d, Point::new(148.0, 28.0), HitOptions::default()).is_some(), "the square is hit"); + assert_eq!(hits(&d), fresh_hits(&d)); + } + + /// What clicks on a grid over `d` hit, and what a marquee over it selects. + fn hits(d: &Document) -> (Vec>>, Vec) { + use crate::hit::{self, HitOptions}; + let mut clicks = Vec::new(); + for y in (0..400).step_by(5) { + for x in (0..400).step_by(5) { + let p = Point::new(f64::from(x), f64::from(y)); + clicks.push(hit::hit_test(d, p, HitOptions::default()).map(|h| h.ancestry)); + } + } + (clicks, hit::marquee(d, Rect::new(0.0, 0.0, 400.0, 400.0), None, false)) + } + + /// [`hits`] with no measurements kept from earlier hit tests. + fn fresh_hits(d: &Document) -> (Vec>>, Vec) { + KEPT.with_borrow_mut(Vec::clear); + hits(d) + } + + /// A bar in a panel with or without 9-slice guides, in a holder whose instance at (50, 50) is + /// scaled 2 times across. With the guides, the bar draws from x 30 to 210 and y 90 to 110; without + /// them, from x 70 to 190, inside the panel's frame from x 50 to 250 and y 50 to 150. + fn sliced_holder(guides: bool) -> Document { + let mut d = Document::new(400.0, 400.0); + let bar = rect(&mut d, Rect::new(10.0, 40.0, 70.0, 60.0), 0.0); + symbol(&mut d, "Bar", vec![bar]); + let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 0.0); + let inner = instance(&mut d, "Bar", Affine::IDENTITY); + symbol(&mut d, "Panel", vec![frame, inner]); + if guides { + d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default())); + } + let panel = instance(&mut d, "Panel", Affine::IDENTITY); + symbol(&mut d, "Holder", vec![panel]); + let layer = d.layers.first().map(|l| l.id); + let holder = instance(&mut d, "Holder", Affine::translate((50.0, 50.0)) * Affine::scale_non_uniform(2.0, 1.0)); + d.insert(layer, usize::MAX, holder).unwrap(); + d + } + + #[test] + fn hit_tests_follow_new_9_slice_guides_and_symbol_sizes() { + use crate::hit::{self, HitOptions}; + let mut d = sliced_holder(false); + // Left of the frame, where only the bar placed through the guides draws. + let left = Point::new(40.0, 100.0); + assert!(hit::hit_test(&d, left, HitOptions::default()).is_none()); + d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default())); + assert!(hit::hit_test(&d, left, HitOptions::default()).is_some(), "the bar placed through the guides is hit"); + assert_eq!(hits(&d), fresh_hits(&d)); + let before = hits(&d); + d.unknown.insert(crate::SYMBOL_SIZES.into(), serde_json::json!({ "Panel": [200.0, 100.0] })); + let after = hits(&d); + assert_ne!(after, before, "the size moves the guides"); + assert_eq!(after, fresh_hits(&d)); + } + + #[test] + fn hit_tests_measure_symbols_holding_9_slice_instances_on_each_call() { + use crate::hit::{self, HitOptions}; + let d = sliced_holder(true); + let left = Point::new(40.0, 100.0); + assert!(hit::hit_test(&d, left, HitOptions::default()).is_some()); + // The holder's art holds an instance of a symbol with guides; the panel's art holds none. + KEPT.with_borrow(|k| { + let measured = &k[0].measured; + assert!(measured.contains_key("Panel") && !measured.contains_key("Holder"), "{:?}", measured.keys()); + }); + let again = art_boxes_measured(|| assert!(hit::hit_test(&d, left, HitOptions::default()).is_some())); + assert!(again > 0, "the holder's art box measured again"); + } + + #[test] + fn kept_measurements_depend_on_the_inputs_of_clipping_path_effects() { + let d = ten_symbols(); + let key = KeptKey::of(&d, (0, false)); + assert!(key.is_of(&d, (0, false))); + assert!(!key.is_of(&d, (1, false)), "live inputs changed"); + assert!(!key.is_of(&d, (0, true)), "a clip region registered"); + } + + #[test] + fn hit_tests_with_a_locked_artboard_measure_each_symbols_art_once() { + use crate::hit::{self, HitOptions}; + let mut d = ten_symbols(); + d.artboards[0].locked = true; + let clicks = || { + for i in 0..10 { + let p = Point::new(40.0 * f64::from(i) + 20.0, 20.0); + assert!(hit::hit_test(&d, p, HitOptions::default()).is_none(), "instance {i} is on the locked artboard"); + assert!(hit::objects_at(&d, p, HitOptions::default(), None).is_empty()); + } + }; + assert!(art_boxes_measured(clicks) >= 10, "each symbol's art box measured"); + assert_eq!(art_boxes_measured(clicks), 0, "art boxes measured again"); + // A marquee passes over the objects on a locked artboard without measuring them itself: only + // its locks measure their art. + let mut d = ten_symbols(); + d.artboards[0].locked = true; + let marquee = || assert!(hit::marquee(&d, Rect::new(0.0, 0.0, 400.0, 100.0), None, false).is_empty()); + assert_eq!(art_boxes_measured(marquee), 10, "each symbol's art box measured once"); + assert_eq!(art_boxes_measured(marquee), 0, "art boxes measured again"); + } + + #[test] + fn hit_tests_hold_no_symbol_art() { + use crate::hit::{self, HitOptions}; + let d = ten_symbols(); + drop(hit::hit_test(&d, Point::new(20.0, 20.0), HitOptions::default())); + assert!(KEPT.with_borrow(|k| !k.is_empty())); + assert!(d.symbols.iter().all(|s| Arc::strong_count(&s.art) == 1), "only the document holds the symbols' art"); + } + + #[test] + fn hit_tests_keep_the_measurements_of_two_sets_of_symbols() { + use crate::hit::{self, HitOptions}; + let docs = [ten_symbols(), ten_symbols(), ten_symbols()]; + let p = Point::new(20.0, 20.0); + for d in &docs { + drop(hit::hit_test(d, p, HitOptions::default())); + } + assert_eq!(KEPT.with_borrow(Vec::len), KEPT_SETS); + // The last two are kept, the first is measured again. + let kept = art_boxes_measured(|| docs[1..].iter().for_each(|d| drop(hit::hit_test(d, p, HitOptions::default())))); + assert_eq!(kept, 0); + let first = art_boxes_measured(|| drop(hit::hit_test(&docs[0], p, HitOptions::default()))); + assert!(first > 0); + } } diff --git a/crates/doc/src/tests/units.rs b/crates/doc/src/tests/units.rs index 5a9265c702..c53f60a227 100644 --- a/crates/doc/src/tests/units.rs +++ b/crates/doc/src/tests/units.rs @@ -79,6 +79,21 @@ fn odd_text_reads_as_nothing_without_panicking() { } } +/// Text from a command or a file can be any length: a sum of thousands of terms reads as nothing +/// instead of exhausting the stack. Up to 128 `+ - * /` signs read; 129 read as nothing. +#[test] +fn a_very_long_expression_reads_as_nothing() { + let sum = |terms: usize| format!("1{}", "+1".repeat(terms - 1)); + assert_eq!(Unit::Points.parse(&sum(129)), Some(129.0)); + assert_eq!(Unit::Points.parse(&format!("10{} mm", "*1".repeat(128))), Some(Unit::Millimeters.to_pt(10.0))); + // Long text with no signs still reads. + assert_eq!(Unit::Points.parse(&format!("{}5", " ".repeat(2_000))), Some(5.0)); + for text in [sum(200_000), format!("1{}", "*1".repeat(200_000)), sum(130), format!("10{} mm", "*1".repeat(129))] { + assert_eq!(Unit::Points.parse(&text), None, "{} bytes", text.len()); + assert_eq!(crate::parse_number(&text), None, "{} bytes", text.len()); + } +} + proptest! { /// Field text made of digits, operators, `%`, spaces and unit letters reads as a finite value /// or as nothing and does not panic. diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 440c379283..6863960230 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -18,23 +18,24 @@ 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, MAX_AKI, 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, CharClass, CompositeFont, CompositePart, - CompositeParts, + COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX, CharClass, + CompositeClass, CompositeClasses, CompositeFont, CompositePart, CompositeParts, CustomCharSet, }; pub use para_style::{ Burasagari, Composer, FirstBaseline, HyphenationOptions, JustificationOptions, Justify, Kashida, Kinsoku, KinsokuShoriType, LeadingModel, Mojikumi, ParaDirection, ParaStyle, SingleWordJustify, }; +pub use runs::PATH_LEAD_MAX; pub use runs::{INLINE_CHAR, INLINE_MAX_SCALE, InlineArt, RubyAlign, RubyPosition, RubySpan, TextKind, TextRun, TextStyleDef, TypeAntiAlias}; pub use tabs_lists::{ Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, NumberStyle, ParaList, TabAlign, TabStop, }; -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`. /// @@ -66,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 16b63e0809..a8fdfbe535 100644 --- a/crates/doc/src/text/char_style.rs +++ b/crates/doc/src/text/char_style.rs @@ -44,6 +44,16 @@ pub struct CharStyle { /// Insert Aki Right: space added after the character in reading order, as [`Self::aki_left`]. #[serde(default, rename = "akiRight", skip_serializing_if = "crate::skip::is_default")] pub aki_right: f64, + /// Tsume (Character panel, East Asian options): the percentage of the blank space on each side + /// 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. 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. #[serde(default, rename = "opticalKerning", skip_serializing_if = "crate::skip::is_default")] pub optical_kerning: bool, @@ -172,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")] @@ -197,6 +219,108 @@ pub struct CharStyle { /// default glyph otherwise. Saved only when set. #[serde(default, rename = "glyphAlternate", skip_serializing_if = "Option::is_none")] pub glyph_alternate: Option, + /// The East Asian glyph form these characters are drawn in (Glyphs panel menu, with Show East + /// Asian Options): one OpenType feature of the font, such as JIS 78 forms (`jp78`), or the + /// font's default glyphs. The text keeps its characters. Saved only when set. + /// + #[serde(default, rename = "glyphForm", skip_serializing_if = "crate::skip::is_default")] + pub glyph_form: GlyphForm, +} + +/// The East Asian glyph form characters are drawn in ([`CharStyle::glyph_form`]): the font's +/// default glyphs, or the glyphs one OpenType feature substitutes. One form at a time. +/// +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum GlyphForm { + /// The font's default glyphs. + #[default] + Default, + /// Traditional forms (`trad`). + Traditional, + /// Expert forms (`expt`). + Expert, + /// JIS 2004 forms (`jp04`). + Jis04, + /// JIS 90 forms (`jp90`). + Jis90, + /// JIS 78 forms (`jp78`). + Jis78, + /// JIS 83 forms (`jp83`). + Jis83, + /// Monospaced full-width forms (`fwid`). + FullWidth, + /// Monospaced half-width forms (`hwid`). + HalfWidth, + /// Monospaced third-width forms (`twid`). + ThirdWidth, + /// Monospaced quarter-width forms (`qwid`). + QuarterWidth, +} + +impl GlyphForm { + /// Every form, in menu order, the default last. + pub const ALL: [GlyphForm; 11] = [ + GlyphForm::Traditional, + GlyphForm::Expert, + GlyphForm::Jis04, + GlyphForm::Jis90, + GlyphForm::Jis78, + GlyphForm::Jis83, + GlyphForm::FullWidth, + GlyphForm::HalfWidth, + GlyphForm::ThirdWidth, + GlyphForm::QuarterWidth, + GlyphForm::Default, + ]; + + /// The name files and commands give this form (as it is saved). + pub fn id(self) -> &'static str { + match self { + GlyphForm::Default => "default", + GlyphForm::Traditional => "traditional", + GlyphForm::Expert => "expert", + GlyphForm::Jis04 => "jis04", + GlyphForm::Jis90 => "jis90", + GlyphForm::Jis78 => "jis78", + GlyphForm::Jis83 => "jis83", + GlyphForm::FullWidth => "fullWidth", + GlyphForm::HalfWidth => "halfWidth", + GlyphForm::ThirdWidth => "thirdWidth", + GlyphForm::QuarterWidth => "quarterWidth", + } + } + + /// The form [`GlyphForm::id`] names; `None` for any other name. + pub fn from_id(id: &str) -> Option { + GlyphForm::ALL.into_iter().find(|f| f.id() == id) + } + + /// The OpenType feature that draws this form; `None` for the default glyphs. + pub fn feature(self) -> Option<&'static [u8; 4]> { + Some(match self { + GlyphForm::Default => return None, + GlyphForm::Traditional => b"trad", + GlyphForm::Expert => b"expt", + GlyphForm::Jis04 => b"jp04", + GlyphForm::Jis90 => b"jp90", + GlyphForm::Jis78 => b"jp78", + GlyphForm::Jis83 => b"jp83", + GlyphForm::FullWidth => b"fwid", + GlyphForm::HalfWidth => b"hwid", + GlyphForm::ThirdWidth => b"twid", + GlyphForm::QuarterWidth => b"qwid", + }) + } + + /// Is this one of the monospaced width forms (`fwid`, `hwid`, `twid`, `qwid`)? A font may + /// draw them with other glyphs (`GSUB`) or with other widths for the same glyphs (`GPOS`), and + /// they set the characters on a fixed width, so Proportional Metrics (`palt`) is not applied + /// with them. + /// + pub fn is_width(self) -> bool { + matches!(self, GlyphForm::FullWidth | GlyphForm::HalfWidth | GlyphForm::ThirdWidth | GlyphForm::QuarterWidth) + } } /// A glyph chosen for one character ([`CharStyle::glyph_alternate`]): the glyph id and the face it @@ -440,6 +564,13 @@ fn hundred() -> f64 { /// The largest Insert Aki Left or Right ([`CharStyle::aki_left`]), in 1/1000 em: one em. 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; @@ -534,6 +665,7 @@ impl Default for CharStyle { kerning_before: 0.0, aki_left: 0.0, aki_right: 0.0, + tsume: 0.0, optical_kerning: false, baseline_shift: 0.0, h_scale: 100.0, @@ -570,10 +702,13 @@ 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, glyph_alternate: None, + glyph_form: GlyphForm::Default, } } } @@ -588,10 +723,12 @@ impl CharStyle { /// becomes the nearer end. A leading of 0, which legacy `.ai` import stores, stays, and a /// baseline shift that is not a number becomes 0. The Tate-chu-yoko Up/Down and Left/Right /// offsets are kept as the baseline shift is. Insert Aki Left and Right are kept from 0 to - /// [`MAX_AKI`], and one that is not a number becomes 0. The Warichu Settings Lines and Scale + /// [`MAX_AKI`], and one that is not a number becomes 0; Tsume is kept from 0 to [`MAX_TSUME`] the + /// 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 }; @@ -606,6 +743,10 @@ impl CharStyle { let aki = |v: f64| if v.is_nan() { 0.0 } else { v.clamp(0.0, MAX_AKI) }; 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 = @@ -677,6 +818,15 @@ impl CharStyle { self.position = self.position.in_range(); self.small_caps = self.small_caps.map(small_caps_in_range); } + /// Sets the East Asian glyph form ([`CharStyle::glyph_form`]). A form other than the default + /// also takes away the character's glyph choice ([`CharStyle::glyph_alternate`]), which would + /// otherwise keep drawing its own glyph; the default form keeps it. + pub fn set_glyph_form(&mut self, form: GlyphForm) { + self.glyph_form = form; + if form != GlyphForm::Default { + self.glyph_alternate = None; + } + } } impl crate::Document { diff --git a/crates/doc/src/text/composite.rs b/crates/doc/src/text/composite.rs index e95428c2f5..93a7e27808 100644 --- a/crates/doc/src/text/composite.rs +++ b/crates/doc/src/text/composite.rs @@ -1,11 +1,16 @@ //! Type › Composite Fonts…: a font made of other fonts, one for each class of character (the //! Kanji font is the base; kana, punctuation, symbols, Roman letters and numerals each take a font -//! of their own, sized, raised and scaled against it). Type set in a composite font names it as its -//! family; the layout sets each character in its class's font. +//! of their own, sized, raised and scaled against it). Custom character sets give characters the +//! user picks a font of their own too, ahead of their class; of two sets that list a character, +//! the later one sets it. Type set in a composite font names it as its family; the layout sets each +//! character in its set's or its class's font. //! //! Behavior reference (public documentation): -//! . -//! Which characters fall in which class, the ranges and the defaults are VectorCraft's own. +//! , +//! custom character sets: +//! . +//! Which characters fall in which class, the ranges, the limits and the defaults are VectorCraft's +//! own. use serde::{Deserialize, Serialize}; @@ -179,12 +184,76 @@ impl CompositeParts { } } +/// A custom character set of a composite font: characters chosen by the user, set in a part of +/// their own instead of their class's part. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct CustomCharSet { + /// The set's name, unique in its composite font in any case. + pub name: String, + /// The set's characters, each once, in the order they were added. + #[serde(default)] + pub characters: String, + /// The font, style, size, baseline and scales its characters take. + #[serde(flatten)] + pub part: CompositePart, +} + +impl CustomCharSet { + /// An empty set named `name`, its characters set in `part`. + pub fn new(name: impl Into, part: CompositePart) -> Self { + Self { name: name.into(), characters: String::new(), part } + } + + /// Whether `c` can be in a custom character set: not a control character, and in the Basic + /// Multilingual Plane (U+0000 to U+FFFF). + pub fn takes(c: char) -> bool { + !c.is_control() && (c as u32) <= 0xFFFF + } + + /// The character a Unicode code names: hexadecimal digits, optionally after `U+` or `0x` + /// (`3042`, `U+3042`). `None` for anything else or a code [`Self::takes`] refuses. + pub fn char_from_code(code: &str) -> Option { + let code = code.trim(); + let hex = ["U+", "u+", "0x", "0X"].iter().find_map(|p| code.strip_prefix(p)).unwrap_or(code); + if hex.is_empty() || hex.len() > 6 || !hex.chars().all(|c| c.is_ascii_hexdigit()) { + return None; + } + u32::from_str_radix(hex, 16).ok().and_then(char::from_u32).filter(|&c| Self::takes(c)) + } +} + +/// Where a composite font sets a character: the part of one of its six classes, or the part of +/// one of its custom character sets (an index into [`CompositeFont::custom`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum CompositeClass { + Fixed(CharClass), + Custom(usize), +} + +/// The custom character set each character of a composite font's sets falls in +/// ([`CompositeFont::classes`]): the last set that lists it. +#[derive(Clone, Debug, Default)] +pub struct CompositeClasses { + custom: std::collections::HashMap, +} + +impl CompositeClasses { + /// Where the composite font sets `c`: the last custom set that lists it, else its class. + pub fn of(&self, c: char) -> CompositeClass { + self.custom.get(&c).map_or(CompositeClass::Fixed(CharClass::of(c)), |&i| CompositeClass::Custom(i)) + } +} + /// A composite font (Type › Composite Fonts…), saved with the document. Its name is the family /// that type set in it names. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CompositeFont { pub name: String, pub parts: CompositeParts, + /// Custom character sets, checked before the classes. A character two sets list is set in the + /// later set's part. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub custom: Vec, } /// The size a part can take, in percent of the type's size. @@ -197,11 +266,40 @@ pub const COMPOSITE_SCALE: std::ops::RangeInclusive = 10.0..=400.0; pub const COMPOSITE_NAME_MAX: usize = 255; /// The most composite fonts a document or a file keeps. pub const COMPOSITE_FONTS_MAX: usize = 256; +/// The most custom character sets a composite font keeps. +pub const CUSTOM_SETS_MAX: usize = 64; +/// The most characters a custom character set keeps. +pub const CUSTOM_CHARS_MAX: usize = 8192; impl CompositeFont { /// A composite font named `name` setting every class in `font` and `style`. pub fn new(name: impl Into, font: impl Into, style: impl Into) -> Self { - Self { name: name.into(), parts: CompositeParts::all(CompositePart::new(font, style)) } + Self { name: name.into(), parts: CompositeParts::all(CompositePart::new(font, style)), custom: Vec::new() } + } + + /// The part that sets the characters of `class`, `None` for a custom set the font doesn't have. + pub fn part(&self, class: CompositeClass) -> Option<&CompositePart> { + match class { + CompositeClass::Fixed(c) => Some(self.parts.get(c)), + CompositeClass::Custom(i) => self.custom.get(i).map(|s| &s.part), + } + } + + /// Where this font sets character `c`: the last custom set that lists it, else its class. For + /// many characters, [`Self::classes`] looks each up faster. + pub fn class_of(&self, c: char) -> CompositeClass { + self.custom.iter().rposition(|s| s.characters.contains(c)).map_or(CompositeClass::Fixed(CharClass::of(c)), CompositeClass::Custom) + } + + /// The custom set each character of this font's sets falls in, to look up many characters. + pub fn classes(&self) -> CompositeClasses { + let mut custom = std::collections::HashMap::new(); + for (i, s) in self.custom.iter().enumerate() { + for c in s.characters.chars() { + custom.insert(c, i); + } + } + CompositeClasses { custom } } /// Do `a` and `b` name the same composite font: equal in any case? @@ -223,36 +321,50 @@ impl CompositeFont { } /// Why this composite font can't be used, if it can't: a name [`Self::clean_name`] refuses, a - /// part without a font, a value out of its range, or a scale or Scale at Center on a class - /// that has none. + /// part without a font, a value out of its range, a scale or Scale at Center on a class that + /// has none, or a custom character set [`Self::check_custom`] refuses. pub fn check(&self) -> Result<(), String> { if Self::clean_name(&self.name).as_deref() != Some(self.name.as_str()) { return Err(format!("`{}` can't name a composite font", self.name)); } for class in CharClass::ALL { - let p = self.parts.get(class); - let k = class.key(); - if p.font.trim().is_empty() { - return Err(format!("{k}: give a font")); + check_part(self.parts.get(class), class.key(), class.scales(), class == CharClass::Kana)?; + } + self.check_custom() + } + + /// Why this font's custom character sets can't be used, if they can't: more than + /// [`CUSTOM_SETS_MAX`], a name [`Self::clean_name`] refuses or two sets share (in any case), a + /// character [`CustomCharSet::takes`] refuses or a set lists twice, more than + /// [`CUSTOM_CHARS_MAX`] characters in a set, or a part [`Self::check`] would refuse. A set's + /// characters can be scaled across and up; only kana are scaled at the center. + pub fn check_custom(&self) -> Result<(), String> { + if self.custom.len() > CUSTOM_SETS_MAX { + return Err(format!("a composite font keeps at most {CUSTOM_SETS_MAX} character sets")); + } + let mut names = std::collections::HashSet::new(); + for s in &self.custom { + let name = &s.name; + if Self::clean_name(name).as_deref() != Some(name.as_str()) { + return Err(format!("`{name}` can't name a character set")); } - let within = |v: f64, r: &std::ops::RangeInclusive| v.is_finite() && r.contains(&v); - if !within(p.size, &COMPOSITE_SIZE) { - return Err(format!("{k}: size must be {} to {}%", COMPOSITE_SIZE.start(), COMPOSITE_SIZE.end())); + if !names.insert(name.to_lowercase()) { + return Err(format!("two character sets are named `{name}`")); } - if !within(p.baseline, &COMPOSITE_BASELINE) { - return Err(format!("{k}: baseline must be {} to {}%", COMPOSITE_BASELINE.start(), COMPOSITE_BASELINE.end())); - } - for v in [p.h_scale, p.v_scale] { - if !within(v, &COMPOSITE_SCALE) { - return Err(format!("{k}: scale must be {} to {}%", COMPOSITE_SCALE.start(), COMPOSITE_SCALE.end())); + let mut seen = std::collections::HashSet::new(); + for (n, c) in s.characters.chars().enumerate() { + if n == CUSTOM_CHARS_MAX { + return Err(format!("`{name}`: a character set keeps at most {CUSTOM_CHARS_MAX} characters")); } - if v != 100.0 && !class.scales() { - return Err(format!("{k}: only kana, roman and numerals can be scaled")); + let code = c as u32; + if !CustomCharSet::takes(c) { + return Err(format!("`{name}`: U+{code:04X} is a control character or past U+FFFF")); + } + if !seen.insert(c) { + return Err(format!("`{name}`: U+{code:04X} is listed twice")); } } - if p.scale_at_center && class != CharClass::Kana { - return Err(format!("{k}: only kana can be scaled at the center")); - } + check_part(&s.part, name, true, false)?; } Ok(()) } @@ -264,9 +376,41 @@ impl CompositeFont { let mut names = std::collections::HashSet::new(); let mut kept: Vec = fonts.iter().filter(|f| f.check().is_ok() && names.insert(f.name.to_lowercase())).take(COMPOSITE_FONTS_MAX).cloned().collect(); - kept.retain(|f| CharClass::ALL.iter().all(|&c| !names.contains(&f.parts.get(c).font.to_lowercase()))); + kept.retain(|f| f.part_fonts().all(|font| !names.contains(&font.to_lowercase()))); (kept.len() != fonts.len()).then_some(kept) } + + /// The fonts of the parts, each class's then each custom set's. + pub fn part_fonts(&self) -> impl Iterator { + CharClass::ALL.into_iter().map(|c| self.parts.get(c).font.as_str()).chain(self.custom.iter().map(|s| s.part.font.as_str())) + } +} + +/// Why part `p` (of the class or set named `k`) can't be used, if it can't: no font, a value out +/// of its range, a scale when `scales` is false, or Scale at Center when `center` is false. +fn check_part(p: &CompositePart, k: &str, scales: bool, center: bool) -> Result<(), String> { + if p.font.trim().is_empty() { + return Err(format!("{k}: give a font")); + } + let within = |v: f64, r: &std::ops::RangeInclusive| v.is_finite() && r.contains(&v); + if !within(p.size, &COMPOSITE_SIZE) { + return Err(format!("{k}: size must be {} to {}%", COMPOSITE_SIZE.start(), COMPOSITE_SIZE.end())); + } + if !within(p.baseline, &COMPOSITE_BASELINE) { + return Err(format!("{k}: baseline must be {} to {}%", COMPOSITE_BASELINE.start(), COMPOSITE_BASELINE.end())); + } + for v in [p.h_scale, p.v_scale] { + if !within(v, &COMPOSITE_SCALE) { + return Err(format!("{k}: scale must be {} to {}%", COMPOSITE_SCALE.start(), COMPOSITE_SCALE.end())); + } + if v != 100.0 && !scales { + return Err(format!("{k}: only kana, roman and numerals can be scaled")); + } + } + if p.scale_at_center && !center { + return Err(format!("{k}: only kana can be scaled at the center")); + } + Ok(()) } #[cfg(test)] @@ -341,4 +485,81 @@ mod tests { spaced.name = " Mixed".into(); assert!(spaced.check().is_err()); } + + /// A character a custom set lists falls in that set ahead of its class, the later of two sets + /// that list it wins, and the quick lookup agrees with the one-character one. + #[test] + fn custom_sets_take_their_characters_before_the_classes() { + let mut f = CompositeFont::new("Mixed", "Inter", "Regular"); + let mut a = CustomCharSet::new("Marks", CompositePart::new("Source Sans 3", "Bold")); + a.characters = "※A".into(); + let mut b = CustomCharSet::new("Letters", CompositePart::new("Inter", "Italic")); + b.characters = "AB".into(); + f.custom = vec![a, b]; + let classes = f.classes(); + for (c, want) in [ + ('※', CompositeClass::Custom(0)), + ('A', CompositeClass::Custom(1)), + ('B', CompositeClass::Custom(1)), + ('C', CompositeClass::Fixed(CharClass::Roman)), + ('漢', CompositeClass::Fixed(CharClass::Kanji)), + ] { + assert_eq!(f.class_of(c), want, "{c:?}"); + assert_eq!(classes.of(c), want, "{c:?}"); + } + assert_eq!(f.part(CompositeClass::Custom(0)).map(|p| p.style.as_str()), Some("Bold")); + assert_eq!(f.part(CompositeClass::Custom(2)), None); + assert_eq!(f.check(), Ok(())); + // Read and written with the part's fields beside the set's name and characters. + let json = serde_json::to_value(&f).unwrap(); + assert_eq!(json["custom"][1]["characters"], "AB"); + assert_eq!(json["custom"][1]["style"], "Italic"); + assert_eq!(serde_json::from_value::(json).unwrap(), f); + // A font without sets is written as before. + assert!(serde_json::to_value(CompositeFont::new("Plain", "Inter", "Regular")).unwrap().get("custom").is_none()); + } + + /// Set names, characters and limits are checked; sets scale like Roman letters. + #[test] + fn custom_sets_check_their_names_and_characters() { + let ok = CompositeFont::new("Mixed", "Inter", "Regular"); + let with = |sets: Vec<(&str, &str)>, edit: fn(&mut CompositePart)| { + let mut f = ok.clone(); + for (name, chars) in sets { + let mut s = CustomCharSet::new(name, CompositePart::new("Inter", "Regular")); + s.characters = chars.into(); + edit(&mut s.part); + f.custom.push(s); + } + f.check() + }; + let none = |_: &mut CompositePart| {}; + assert_eq!(with(vec![("Empty", "")], none), Ok(())); + assert_eq!(with(vec![("Wide", "AB")], |p| p.h_scale = 80.0), Ok(())); + assert!(with(vec![("Wide", "AB")], |p| p.scale_at_center = true).is_err()); + assert!(with(vec![("Big", "A")], |p| p.size = 401.0).is_err()); + assert!(with(vec![("Same", "A"), ("same", "B")], none).unwrap_err().contains("two character sets")); + assert!(with(vec![(" Pad", "A")], none).is_err()); + assert!(with(vec![("Twice", "ABA")], none).unwrap_err().contains("U+0041 is listed twice")); + assert!(with(vec![("Tab", "A\t")], none).unwrap_err().contains("U+0009")); + assert!(with(vec![("Astral", "𠀋")], none).unwrap_err().contains("U+2000B")); + let many: String = (0x4E00u32..).filter_map(char::from_u32).take(CUSTOM_CHARS_MAX + 1).collect(); + let mut f = ok.clone(); + f.custom.push(CustomCharSet { name: "Many".into(), characters: many, part: CompositePart::new("Inter", "Regular") }); + assert!(f.check().unwrap_err().contains("at most")); + let mut f = ok.clone(); + f.custom = (0..=CUSTOM_SETS_MAX).map(|i| CustomCharSet::new(format!("S{i}"), CompositePart::new("Inter", "Regular"))).collect(); + assert!(f.check().is_err()); + } + + /// Codes are hexadecimal, with or without `U+` or `0x`, inside the Basic Multilingual Plane. + #[test] + fn custom_set_codes_name_characters() { + assert_eq!(CustomCharSet::char_from_code("3042"), Some('あ')); + assert_eq!(CustomCharSet::char_from_code(" U+203B "), Some('※')); + assert_eq!(CustomCharSet::char_from_code("0x41"), Some('A')); + for bad in ["", "U+", "zz", "20000B", "D800", "0009", "1F600", "1234567", "+41"] { + assert_eq!(CustomCharSet::char_from_code(bad), None, "{bad:?}"); + } + } } diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index dd4002dd60..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(), @@ -352,7 +353,10 @@ impl TextObject { } /// Flip type on a path to the other side of its path (Type on a Path Options › Flip, or its /// centre bracket dragged across the path): the path runs the other way and the brackets swap - /// ends, so the type keeps its stretch of the path. False, changing nothing, for other type. + /// ends, so the type keeps its stretch of the path. Type that starts before an open path's start + /// ([`TextKind::path_text_start`]) starts at its start bracket after the flip: the part of its + /// span before the path's start would come after the path's end. False, changing nothing, for + /// other type. pub fn flip_on_path(&mut self) -> bool { let Some((s, e)) = self.kind.path_span() else { return false }; let TextKind::OnPath { path, start, end } = &mut self.kind else { return false }; @@ -507,6 +511,9 @@ impl crate::Document { st.tcy_left_right = num("tcyLeftRight").unwrap_or(st.tcy_left_right); 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(); @@ -532,6 +539,9 @@ impl crate::Document { ("tcyLeftRight", Some(st.tcy_left_right)), ("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 45cf181f18..62c6b8dd33 100644 --- a/crates/doc/src/text/para_style.rs +++ b/crates/doc/src/text/para_style.rs @@ -17,22 +17,52 @@ pub enum Justify { JustifyAll, } -/// Paragraph composer (Paragraph panel menu): how lines are broken. +/// Paragraph composer (Paragraph panel menu): how lines are broken, and whether complex scripts +/// (Indic, Arabic, Hebrew) are shaped. `SingleLine` and `EveryLine` are the Middle Eastern & South +/// Asian composers: they shape complex scripts with the font's layout tables, as all type is set +/// here, and are what documents saved before the four composers existed use. The `Standard` +/// composers break lines the same way but set a complex script glyph by glyph as the font maps its +/// characters, with no conjuncts, marks placed or joining forms: what fonts that keep a script's +/// glyphs on Latin character codes (legacy ANSI Indic fonts) need. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum Composer { - /// Break each line as soon as it is full. + /// Middle Eastern & South Asian Single-line Composer: break each line as soon as it is full. SingleLine, - /// Total fit over the whole paragraph (Illustrator's default): justified lines get even word - /// spacing, ragged lines an even rag. + /// Middle Eastern & South Asian Every-line Composer: total fit over the whole paragraph + /// (Illustrator's default): justified lines get even word spacing, ragged lines an even rag. #[default] EveryLine, + /// Standard Single-line Composer: [`Composer::SingleLine`]'s breaks, complex scripts not shaped. + StandardSingleLine, + /// Standard Every-line Composer: [`Composer::EveryLine`]'s breaks, complex scripts not shaped. + StandardEveryLine, } impl Composer { fn is_default(&self) -> bool { *self == Self::default() } + + /// Does this composer break lines one at a time (as opposed to a total fit)? + pub fn is_single_line(self) -> bool { + matches!(self, Self::SingleLine | Self::StandardSingleLine) + } + + /// Does this composer shape complex scripts ([`Composer::SingleLine`], [`Composer::EveryLine`])? + pub fn shapes_complex_scripts(self) -> bool { + matches!(self, Self::SingleLine | Self::EveryLine) + } + + /// The same shaping with the other line breaking (`single_line`: one line at a time). + pub fn with_breaking(self, single_line: bool) -> Self { + match (single_line, self.shapes_complex_scripts()) { + (true, true) => Self::SingleLine, + (true, false) => Self::StandardSingleLine, + (false, true) => Self::EveryLine, + (false, false) => Self::StandardEveryLine, + } + } } /// A paragraph's hyphenation options (Paragraph panel menu › Hyphenation…): which words automatic @@ -241,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. @@ -345,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, @@ -382,6 +417,7 @@ impl From for ParaStyleFile { kinsoku, kinsoku_type, bunri_kinshi, + kurikaeshi_moji_shori, roman_hanging, kashida, korean_line_break_anywhere, @@ -409,6 +445,7 @@ impl From for ParaStyleFile { kinsoku, kinsoku_type, bunri_kinshi, + kurikaeshi_moji_shori, roman_hanging, kashida, korean_line_break_anywhere, @@ -440,6 +477,7 @@ impl From for ParaStyle { kinsoku, kinsoku_type, bunri_kinshi, + kurikaeshi_moji_shori, roman_hanging, kashida, korean_line_break_anywhere, @@ -466,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/runs.rs b/crates/doc/src/text/runs.rs index 0bf62ed155..5bf6d1bf79 100644 --- a/crates/doc/src/text/runs.rs +++ b/crates/doc/src/text/runs.rs @@ -93,8 +93,10 @@ pub enum TextKind { /// Area type flowed inside `frame` (document coordinates, untransformed by `xf`). Area { frame: PathData }, /// Type on a path, flowing from its start bracket `start` to its end bracket `end` (0..1 of the - /// path length; no `end`: the end of the path, or once round a closed path). See - /// [`TextKind::path_span`]. + /// path length; no `end`: the end of the path, or once round a closed path). On an open path + /// `start` may be below 0: the type starts that far before the path's start, and the characters + /// whose middle falls before the path's start are not drawn ([`TextKind::path_text_start`]). + /// See [`TextKind::path_span`]. OnPath { path: PathData, start: f64, @@ -117,8 +119,22 @@ impl TextKind { (s, end.map_or(1.0, |e| fraction(e).max(s))) }) } + /// Where type on a path's text starts, as a fraction of its path's length: its start bracket + /// ([`Self::path_span`]), or on an open path a start before the path's start (below 0, at most + /// [`PATH_LEAD_MAX`] path lengths before it). None for other type. + pub fn path_text_start(&self) -> Option { + let TextKind::OnPath { path, start, .. } = self else { return None }; + if !path.is_closed() && start.is_finite() && *start < 0.0 { Some(start.max(-PATH_LEAD_MAX)) } else { self.path_span().map(|(s, _)| s) } + } + /// Does type on an open path start before its path's start ([`Self::path_text_start`])? + pub fn starts_before_path(&self) -> bool { + self.path_text_start().is_some_and(|s| s < 0.0) + } } +/// How far before its path's start type on an open path may start, in lengths of the path. +pub const PATH_LEAD_MAX: f64 = 1e6; + /// Move anchors `refs` of `path`, in text space, by `d` in document space (`to_text`: the /// document → text map). False when an anchor doesn't exist. pub(super) fn move_anchors(path: &mut PathData, to_text: Affine, refs: &[(usize, usize)], d: Vec2) -> bool { diff --git a/crates/doc/src/text/tabs_lists.rs b/crates/doc/src/text/tabs_lists.rs index b8531b402d..26622fa115 100644 --- a/crates/doc/src/text/tabs_lists.rs +++ b/crates/doc/src/text/tabs_lists.rs @@ -357,7 +357,7 @@ impl ParaList { /// The style the marker is set in: `first` (the style of the paragraph's first character) /// without its baseline shift, rotation, superscript or subscript, tracking, manual kerning, - /// Insert Aki, tate-chu-yoko, warichu, underline and strikethrough. + /// Insert Aki, Tsume, tate-chu-yoko, warichu, underline and strikethrough. pub fn marker_style(first: &CharStyle) -> CharStyle { CharStyle { baseline_shift: 0.0, @@ -368,6 +368,7 @@ impl ParaList { kerning_before: 0.0, aki_left: 0.0, aki_right: 0.0, + tsume: 0.0, optical_kerning: first.optical_kerning, tate_chu_yoko: false, warichu: false, diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index 0f474d2ed8..a5230d5d86 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -129,6 +129,70 @@ 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] +fn tsume_is_saved_only_when_set_and_kept_in_range() { + let st = CharStyle::default(); + assert_eq!(st.tsume, 0.0); + let saved = serde_json::to_value(&st).unwrap(); + assert!(saved.get("tsume").is_none()); + let read = serde_json::from_value::(saved).unwrap(); + assert_eq!(read.tsume, 0.0); + let set = CharStyle { tsume: 37.5, ..CharStyle::default() }; + let saved = serde_json::to_value(&set).unwrap(); + assert_eq!(saved.get("tsume").and_then(serde_json::Value::as_f64), Some(37.5)); + assert_eq!(serde_json::from_value::(saved).unwrap(), set); + for (stored, kept) in [(-5.0, 0.0), (250.0, MAX_TSUME), (f64::NAN, 0.0), (f64::INFINITY, MAX_TSUME), (50.0, 50.0)] { + let mut damaged = CharStyle { tsume: stored, ..CharStyle::default() }; + damaged.keep_dimensions_in_range(); + assert_eq!(damaged.tsume, kept, "{stored}"); + } + let mut d = crate::Document::new(100.0, 100.0); + for tsume in [500, -1] { + let attrs = serde_json::json!({ "tsume": tsume }); + d.char_styles.push(TextStyleDef { name: format!("Tight {tsume}"), attrs: attrs.as_object().cloned().unwrap_or_default() }); + } + d.keep_type_values_in_range(); + assert_eq!((d.char_styles[0].attrs["tsume"].as_f64(), d.char_styles[1].attrs["tsume"].as_f64()), (Some(MAX_TSUME), Some(0.0))); +} + /// Each Indic numeral system draws 0–9 (and the Arabic-Indic sets) as the ten digits of its /// script's block; every system saves under its id, which reads back, and other names are refused. #[test] @@ -535,6 +599,33 @@ fn area_anchors_move_in_document_space() { assert_eq!(t, before); } +/// Type on an open path may start before the path's start: the start is kept, saved and read back, +/// while the start bracket stays at the path's start. On a closed path, and for a start that is not +/// finite, the start is the start bracket as before. +#[test] +fn type_on_an_open_path_starts_before_the_path() { + let pts = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0)]; + let on = |closed: bool, start: f64| TextKind::OnPath { + path: PathData::new(vec![vectorcraft_geom::SubPath::polyline(&pts, closed)]), + start, + end: None, + }; + let open = on(false, -0.25); + assert_eq!(open.path_text_start(), Some(-0.25)); + assert!(open.starts_before_path()); + assert_eq!(open.path_span(), Some((0.0, 1.0))); + let saved = serde_json::to_value(&open).unwrap(); + assert_eq!(saved["start"], -0.25); + assert_eq!(serde_json::from_value::(saved).unwrap(), open); + assert_eq!(on(false, -1e9).path_text_start(), Some(-PATH_LEAD_MAX)); + assert_eq!(on(false, f64::NEG_INFINITY).path_text_start(), Some(0.0)); + assert_eq!(on(false, 0.25).path_text_start(), Some(0.25)); + assert!(!on(false, 0.0).starts_before_path()); + assert_eq!(on(true, -0.25).path_text_start(), Some(0.0)); + assert!(!on(true, -0.25).starts_before_path()); + assert_eq!(TextKind::Point.path_text_start(), None); +} + /// Builds from before [`Justify::Auto`] read new type's alignment as Left or Right (and ignore /// `justify_auto`); this build reads Auto back. #[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/doc/src/units.rs b/crates/doc/src/units.rs index 234513df1d..5fabfece65 100644 --- a/crates/doc/src/units.rs +++ b/crates/doc/src/units.rs @@ -156,7 +156,12 @@ impl Unit { /// before it (`3cm*50%` is 1.5 cm, `3cm/50%` is 6 cm). After `+` or `-`, it adds or takes away /// that share of everything before it (`50pt+25%` is 62.5 pt, `100pt+20pt-50%` is 60 pt). A /// percentage on its own (`50%`) reads as nothing. + /// + /// Text with more than 128 `+ - * /` signs reads as nothing. pub fn parse(self, s: &str) -> Option { + if s.chars().filter(|c| matches!(c, '+' | '-' | '*' | '/')).count() > MAX_MEASURE_OPERATORS { + return None; + } parse_measure(s, self).filter(|v| v.is_finite()) } /// The value naming this unit in the Units preferences (`points`, `millimeters`, @@ -207,6 +212,9 @@ impl Unit { } } +/// The most `+ - * /` signs [`Unit::parse`] reads in one text. +const MAX_MEASURE_OPERATORS: usize = 128; + fn parse_measure(s: &str, default: Unit) -> Option { let s = s.trim(); // Simple arithmetic on the right (Illustrator fields accept "10+5", "100/2", "3in*2"). 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 2cffad6581..274f9bdcc4 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -17,7 +17,8 @@ //! object of its own, a stroke a path stroked by it alone (brushed strokes their brush art, made by //! the caller). -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; +use std::rc::Rc; use std::sync::Arc; use vectorcraft_doc::color::Paint; @@ -26,20 +27,22 @@ use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Vec2}; use crate::distort::{transform_move, transform_offsets}; use crate::group::{has_own_paint, paints}; -use crate::reshape::{as_art, geometry_effects, glyph_outlines, outline_nested_text, reshape_leaves}; +use crate::reshape::{ + as_art, clipping_text_outline, dressed, geometry_effects, glyph_outlines, outline_nested_text, paint_type_clip, reshape_leaves, +}; use crate::{ GeomContext, adjust_in_document, apply_geometry_carrying, crop_marks_art, evaluate_container, has_adjustment, has_crop_marks, has_geometry, - has_instance_row_raster, has_item_geometry, has_pathfinder, is_pathfinder, merged_params, needs_outline, outline_text, reshape, + has_instance_row_raster, has_item_geometry, has_pathfinder, is_pathfinder, merged_params, needs_outline, reshape, }; -fn item_effects(item: &AppearanceItem) -> &[vectorcraft_doc::Effect] { +pub(crate) fn item_effects(item: &AppearanceItem) -> &[vectorcraft_doc::Effect] { match item { AppearanceItem::Fill(f) => &f.effects, AppearanceItem::Stroke(s) => &s.effects, } } -fn clear_item_effects(item: &mut AppearanceItem) { +pub(crate) fn clear_item_effects(item: &mut AppearanceItem) { match item { AppearanceItem::Fill(f) => f.effects = crate::raster::without_geometry(&f.effects), AppearanceItem::Stroke(s) => s.effects = crate::raster::without_geometry(&s.effects), @@ -74,7 +77,7 @@ fn geometry(n: &Node) -> Option<(PathData, FillRule)> { /// `path` with the geometry effects of `effects` applied, and how gradients follow them /// ([`crate::Carry`]). -fn apply(effects: &[vectorcraft_doc::Effect], path: &PathData, ctx: &GeomContext) -> (PathData, crate::Carry) { +pub(crate) fn apply(effects: &[vectorcraft_doc::Effect], path: &PathData, ctx: &GeomContext) -> (PathData, crate::Carry) { if !has_geometry(effects) || path.is_empty() { return (path.clone(), crate::Carry::default()); } @@ -86,7 +89,7 @@ fn apply(effects: &[vectorcraft_doc::Effect], path: &PathData, ctx: &GeomContext /// context of) applied, and `carried` (`item` as the object's effects left it) with its gradient /// moved along with them and the Transform effects the geometry pass left out hidden /// ([`crate::Carry::hide_skipped`]). -fn apply_item(item: &AppearanceItem, carried: &AppearanceItem, g: &PathData, ctx: &GeomContext) -> (PathData, AppearanceItem) { +pub(crate) fn apply_item(item: &AppearanceItem, carried: &AppearanceItem, g: &PathData, ctx: &GeomContext) -> (PathData, AppearanceItem) { let (ig, carry) = apply(item_effects(item), g, &ctx.item(item)); let mut ap = Appearance { items: vec![carried.clone()], ..Default::default() }; if carry.moves(&ap) { @@ -114,13 +117,226 @@ 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) }; + /// The objects in the baked art of the instances that [`bake_node`] has replaced by their + /// placed art for one export ([`placed_symbol_art`]), counted against [`Placing::most_nodes`]. + static PLACED_NODES: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The objects in the baked art of the instances that [`bake_node`] baked for one export and + /// then left as they are ([`placed_fits`] refused the art), counted with [`PLACED_NODES`] + /// against [`Placing::most_nodes`] before more art is baked. Never given back. + static DROPPED_NODES: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How deep the object [`bake_node`] is baking sits in the tree it returns: a top-level layer + /// is 1 deep. + static LEVEL: std::cell::Cell = const { std::cell::Cell::new(1) }; + /// Whether [`bake_node`] is baking inside an object the export does not write ([`unwritten`]), + /// where no instance is placed. + static UNWRITTEN: std::cell::Cell = const { std::cell::Cell::new(false) }; } -/// `n` with its geometry effects evaluated (`None` = unchanged). +/// `f` run for an object one level deeper ([`LEVEL`]) than the one being baked. +fn one_deeper(f: impl FnOnce() -> T) -> T { + LEVEL.with(|c| c.set(c.get() + 1)); + let out = f(); + LEVEL.with(|c| c.set(c.get().saturating_sub(1))); + out +} + +/// The symbols whose instances [`bake_document_placing_symbols`] replaces by their placed art, and +/// how that art is placed through 9-slice guides. +struct Placing { + /// The names of the symbols whose art draws something that baking changes, directly or through + /// the instances of other such symbols in it ([`drawn_symbols`]). + symbols: HashSet, + /// Whether 9-slice cells are clipped ([`Document::place_symbol_art`]) or not + /// ([`Document::place_symbol_art_unclipped`]). + clip_slices: bool, + /// Most objects the baked art of all placed instances may hold together: + /// [`vectorcraft_doc::MAX_SYMBOL_NODES`] for an export. + most_nodes: u64, + /// How deep the document's symbols and patterns draw, for the instances and pattern paints + /// left in placed art. + heights: vectorcraft_doc::depth::DrawnHeights, + /// The hidden layers and layers that do not print that the export writes. + layers: WrittenLayers, +} + +/// 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 { + /// Hidden layers (written turned off, as PDF layers and DXF write them). + 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 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 || p.layers.hidden_objects), + }) + }) +} + +/// Can `baked`, the baked art of a placed instance, take the instance's place [`LEVEL`] deep, +/// when the art placed for the export so far holds `spent` objects and the art baked for +/// instances left as they are holds `dropped` ([`DROPPED_NODES`])? `Some` with the +/// objects placed then, when its objects (opacity masks' art included) fit with those within +/// [`Placing::most_nodes`] and nothing in it, the symbols and patterns it uses included, draws +/// deeper than [`vectorcraft_doc::depth::MAX_DRAWN_DEPTH`]. +fn placed_fits(baked: &Node, spent: u64, dropped: u64) -> Option { + PLACING.with(|p| { + let p = p.borrow(); + let p = p.as_ref()?; + let spent = spent.saturating_add(baked.count_with_masks() as u64); + let deepest = p.heights.deepest(baked, LEVEL.with(|c| c.get())); + (spent.saturating_add(dropped) <= p.most_nodes && deepest <= vectorcraft_doc::depth::MAX_DRAWN_DEPTH).then_some(spent) + }) +} + +/// The names of the symbols of `d` whose art needs baking ([`needs_bake`]), and of those whose art +/// holds an instance of one of them at any depth, in the art of enabled opacity masks too. +fn drawn_symbols(d: &Document) -> HashSet { + fn used(n: &Node, names: &mut Vec) { + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind { + names.push(symbol.clone()); + } + if let Some(m) = n.extras().mask.as_ref().filter(|m| !m.disabled) { + used(&m.art, names); + } + for c in n.children().into_iter().flatten() { + used(c, names); + } + } + let mut out: HashSet = d.symbols.iter().filter(|s| needs_bake(&s.art)).map(|s| s.name.clone()).collect(); + if out.is_empty() { + return out; + } + let uses: Vec<(&str, Vec)> = d + .symbols + .iter() + .filter(|s| !out.contains(&s.name)) + .map(|s| { + let mut names = vec![]; + used(&s.art, &mut names); + (s.name.as_str(), names) + }) + .collect(); + loop { + let before = out.len(); + for (name, names) in &uses { + if !out.contains(*name) && names.iter().any(|x| out.contains(x)) { + out.insert((*name).to_string()); + } + } + if out.len() == before { + return out; + } + } +} + +/// Does `n`'s subtree hold an instance of a symbol that [`bake_document_placing_symbols`] replaces +/// by its placed art, in the art of its enabled opacity masks too? False outside it, and for +/// objects the export does not write ([`unwritten`]). +fn holds_placed_symbol(n: &Node) -> bool { + placed_symbol_in(n, true) +} + +/// [`holds_placed_symbol`], with the art of `n`'s own opacity mask left out unless `own_mask` +/// (the art of the masks inside `n` is always looked into). +fn placed_symbol_in(n: &Node, own_mask: bool) -> bool { + fn walk(n: &Node, symbols: &HashSet, own_mask: bool) -> bool { + !unwritten(n) + && (matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.contains(symbol)) + || (own_mask && !n.is_ruler_guide() && n.extras().mask.as_ref().is_some_and(|m| !m.disabled && walk(&m.art, symbols, true))) + || n.children().is_some_and(|ch| ch.iter().any(|c| walk(c, symbols, true)))) + } + !UNWRITTEN.with(|c| c.get()) && PLACING.with(|p| p.borrow().as_ref().is_some_and(|p| walk(n, &p.symbols, own_mask))) +} + +/// Symbol instance `n`, while [`bake_document_placing_symbols`] bakes and its symbol is one it +/// places, as the art it draws: the symbol's art with the instance's own appearance changes and +/// its stain ([`vectorcraft_doc::symbol_overrides::instance_art`]), placed by the instance as the exporters +/// place it, in a group with the instance's id, name, visibility, transparency, opacity mask, +/// raster effects and attributes (its URL among them). The art is placed before its effects are baked, as the canvas draws it, so an +/// instance that scales its art does not scale what its effects do. `None` for other objects, +/// for instances the export does not write ([`unwritten`], hidden or inside such an object), for +/// instances nested [`vectorcraft_doc::depth::MAX_DEPTH`] deep in such art, and when the art +/// as placed, before its effects are baked, would already take the art placed for the export, +/// with the art baked for instances left as they are ([`DROPPED_NODES`]), past +/// [`Placing::most_nodes`]; those instances stay as they are. `Some` with the objects in the art +/// as placed, before its effects are baked. [`bake_node`] checks the baked art with +/// [`placed_fits`]. +fn placed_symbol_art(d: &Document, n: &Node) -> Option<(Node, u64)> { + let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return None }; + let (clip, most_nodes) = PLACING.with(|p| p.borrow().as_ref().filter(|p| p.symbols.contains(symbol)).map(|p| (p.clip_slices, p.most_nodes)))?; + if INSTANCE_DEPTH.with(|c| c.get()) >= vectorcraft_doc::depth::MAX_DEPTH || UNWRITTEN.with(|c| c.get()) || unwritten(n) { + return None; + } + let sym = d.symbols.iter().find(|s| s.name == *symbol)?; + let art = vectorcraft_doc::symbol_overrides::instance_art(&sym.art, n); + let most = match d.symbol_slice_map(symbol, *xf) { + Some(m) if clip => m.most_placed(&art, d), + Some(m) => m.most_placed_unclipped(&art, d), + None => art.count_with_masks() as u64, + }; + if PLACED_NODES.with(|c| c.get()).saturating_add(DROPPED_NODES.with(|c| c.get())).saturating_add(most) > most_nodes { + return None; + } + let placed = if clip { d.place_symbol_art(symbol, &art, *xf) } else { d.place_symbol_art_unclipped(symbol, &art, *xf) }?; + let mut g = dressed(Node::group(n.id, vec![Arc::new(placed)]), n); + g.extras_mut().attrs = n.extras().attrs.clone(); + Some((g, most)) +} + +/// `n` with its geometry effects evaluated (`None` = unchanged), and the art of its enabled opacity +/// mask baked one level deeper when it holds instances that [`bake_document_placing_symbols`] +/// places ([`holds_placed_symbol`]), so the mask masks with the art the instances draw. The art is +/// baked only while the object baked from `n` still carries `n`'s mask art; art already baked +/// with `n`'s recolored or placed form is not baked again. A ruler guide's mask stays as it is. fn bake_node(d: &mut Document, n: &Node) -> Option { + let out = bake_object(d, n); + let Some(mask) = n.extras().mask.as_ref().filter(|m| !m.disabled && !n.is_ruler_guide() && !unwritten(n) && holds_placed_symbol(&m.art)) else { + return out; + }; + let changed = out.is_some(); + let mut out = out.unwrap_or_else(|| n.clone()); + let Some(slot) = out.extras_if_any().and_then(|e| e.mask.as_mut()).filter(|s| Arc::ptr_eq(&s.art, &mask.art)) else { + return changed.then_some(out); + }; + let Some(art) = one_deeper(|| bake_node(d, &mask.art)) else { return changed.then_some(out) }; + slot.art = Arc::new(art); + Some(out) +} + +/// `n` with its geometry effects evaluated (`None` = unchanged); its opacity mask is left to +/// [`bake_node`]. +fn bake_object(d: &mut Document, n: &Node) -> Option { + // Inside an object the export leaves out, effects are baked but no instance is placed. + if !UNWRITTEN.with(|c| c.get()) && unwritten(n) { + UNWRITTEN.with(|c| c.set(true)); + let out = bake_node(d, n); + UNWRITTEN.with(|c| c.set(false)); + return out; + } // A cancelled export leaves the rest of the document as it is: the caller drops the result. // A ruler guide draws nothing and stays as it is, last in its layer. - if n.is_ruler_guide() || !needs_bake(n) || vectorcraft_doc::cancel::is_cancelled() { + // An object whose own mask's art alone holds placed instances stays as it is here. + if n.is_ruler_guide() || !(needs_bake(n) || placed_symbol_in(n, false)) || vectorcraft_doc::cancel::is_cancelled() { return None; } // Colour adjustments: the object recoloured (inside it too), then baked as it is. @@ -161,17 +377,29 @@ fn bake_node(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)); } @@ -179,7 +407,37 @@ fn bake_node(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 + // where the instance is, it is dropped with the art placed for the instances inside it, and + // the instance stays as it is. While the art bakes, its objects before baking are held in + // the budget, so the instances inside it are placed only within what is left; art baked and + // then dropped still counts against the budget for the instances after it. + if let Some((m, most)) = placed_symbol_art(d, n) { + let spent = PLACED_NODES.with(|c| c.get()); + PLACED_NODES.with(|c| c.set(spent.saturating_add(most))); + INSTANCE_DEPTH.with(|c| c.set(c.get() + 1)); + let baked = bake_node(d, &m); + INSTANCE_DEPTH.with(|c| c.set(c.get() - 1)); + let baked = baked.unwrap_or(m); + if let Some(now) = placed_fits(&baked, spent, DROPPED_NODES.with(|c| c.get())) { + PLACED_NODES.with(|c| c.set(now)); + return Some(baked); + } + PLACED_NODES.with(|c| c.set(spent)); + DROPPED_NODES.with(|c| c.set(c.get().saturating_add(baked.count_with_masks() as u64))); } // A path whose Transform effect copies it with a gradient, or scales its strokes or moves its // patterns: each copy an object of its own, so its gradient fits it rather than spanning @@ -201,8 +459,26 @@ fn bake_node(d: &mut Document, n: &Node) -> Option { { return bake_leaf(d, n); } + if let Some(m) = clip_group_with_type_clip(d, n) { + return Some(m); + } let mut m = n.clone(); - let baked: Vec> = ch.iter().map(|c| bake_node(d, c).map(Arc::new).unwrap_or_else(|| c.clone())).collect(); + // A clipping path takes the geometry effects in it as the canvas clips by it, those of a + // compound path's paths before the compound path's own ([`crate::clip::with_clip_effects_applied`]); + // the pieces it is made of then get ids of their own. + let clip = usize::from(n.clips()); + let baked: Vec> = ch + .iter() + .enumerate() + .map(|(i, c)| match (i < clip).then(|| crate::clip::with_clip_effects_applied(c)).flatten() { + Some(a) => { + let mut a = one_deeper(|| bake_node(d, &a)).unwrap_or(a); + fresh_ids(d, &mut a, &mut std::collections::HashSet::new()); + Arc::new(a) + } + None => one_deeper(|| bake_node(d, c)).map(Arc::new).unwrap_or_else(|| c.clone()), + }) + .collect(); if let Some(ch) = m.children_mut() { *ch = baked; } @@ -211,17 +487,77 @@ fn bake_node(d: &mut Document, n: &Node) -> Option { bake_leaf(d, n) } +/// Clip group or clipping layer `n` whose clipping path is type with geometry effects (its own, its +/// fills' or strokes', or a perspective), baked as the canvas draws it: the type becomes a +/// clipping path of the region the canvas clips to ([`crate::clip_outline`]), its fills (with their +/// effects baked) paint behind the clipped art inside the clip, and its strokes paint over it +/// outside the clip, in a group that `n` becomes with its clip group inside ([`Node::clip_paint`]). +/// The other members are baked as usual. `None` for other objects and when the type has nothing to +/// clip by. +fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option { + let (first, rest) = n.children()?.split_first()?; + if !n.clips() + || !matches!(first.kind, NodeKind::Text(_)) + || !(has_geometry(&first.appearance.effects) || first.projection().is_some() || has_item_geometry(first)) + { + return None; + } + let (bp, rule) = crate::clip_outline(first)?; + let mut clip = Node::path(first.id, PathData::from_bezpath(&bp), Appearance::default()); + if let NodeKind::Path { rule: r, clipping, .. } = &mut clip.kind { + (*r, *clipping) = (rule, true); + } + clip.name = first.name.clone(); + clip.visible = first.visible; + let paint = first.clip_paint(); + // The type's fills and strokes as art: baked with the type's id, as the renderer draws them, + // then given ids of their own. + let mut seen = std::collections::HashSet::from([n.id, first.id]); + let mut art = |d: &mut Document, part: Option| { + part.map(|p| { + let mut a = bake_node(d, &p).unwrap_or(p); + fresh_ids(d, &mut a, &mut seen); + Arc::new(a) + }) + }; + let fill = art(d, paint.fill); + let stroke = art(d, paint.stroke); + let members: Vec> = + std::iter::once(Arc::new(clip)).chain(fill).chain(rest.iter().map(|c| bake_node(d, c).map(Arc::new).unwrap_or_else(|| c.clone()))).collect(); + let mut m = n.clone(); + let Some(stroke) = stroke else { + if let Some(ch) = m.children_mut() { + *ch = members; + } + return Some(m); + }; + // `n` keeps its id, name and transparency, and holds the clip group and the strokes over it. + let inner = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true }); + match &mut m.kind { + NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } => { + *children = vec![Arc::new(inner), stroke]; + *clip = false; + } + _ => return None, + } + Some(m) +} + /// `m`, art evaluated from an object, with its children baked and then given ids of their own (the /// pieces copied from the source keep the source's ids until then). The pieces are baked with the -/// ids the renderer draws them with: Random in a Transform effect takes its seed from the id. +/// ids the renderer draws them with: Random in a Transform effect takes its seed from the id. When +/// `m` clips, its clipping path, unless it is type, first takes the geometry effects in it as the +/// canvas clips by it ([`crate::clip::with_clip_effects_applied`]). fn bake_pieces(d: &mut Document, mut m: Node) -> Node { let mut seen = std::collections::HashSet::from([m.id]); + let clip = usize::from(m.clips() && !m.children().and_then(|ch| ch.first()).is_some_and(|c| matches!(c.kind, NodeKind::Text(_)))); let children = m.children().cloned().unwrap_or_default(); let children = children .into_iter() - .map(|c| { - let c = Arc::unwrap_or_clone(c); - let mut c = bake_node(d, &c).unwrap_or(c); + .enumerate() + .map(|(i, c)| { + let c = (i < clip).then(|| crate::clip::with_clip_effects_applied(&c)).flatten().unwrap_or_else(|| Arc::unwrap_or_clone(c)); + let mut c = one_deeper(|| bake_node(d, &c)).unwrap_or(c); fresh_ids(d, &mut c, &mut seen); Arc::new(c) }) @@ -347,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))?; @@ -382,9 +720,14 @@ fn moved_type_group(n: &Node) -> Option { /// Type in a clipping path, other type that [`moved_type`] doesn't copy, and type inside live /// objects or inside groups with Pathfinder or geometry effects or fills and strokes that paint, is /// outlined as [`evaluate_container`] outlines it, and the other members become what it makes of -/// them. `None` when no type stays type. +/// them. `None` when no type stays type, and for a group or layer whose copies each carry the raster +/// effects listed before their Transform effect ([`crate::outer_effects`]), which is baked as the +/// canvas draws it ([`evaluate_container`]). fn container_keeping_type(d: &Document, n: &Node) -> Option { fn keep(d: &Document, n: &mut Node, moves: &[serde_json::Value], clipping: bool, kept: &mut bool) { + if !clipping { + paint_type_clip(Some(d), n); + } let clips = n.clips(); let Some(ch) = n.children_mut() else { return }; for (i, c) in ch.iter_mut().enumerate() { @@ -407,7 +750,7 @@ fn container_keeping_type(d: &Document, n: &Node) -> Option { last => Some(Node::group(c.id, copies.into_iter().chain(last).map(Arc::new).collect())), } } - None if clipping => outline_text(c).map(|o| Node { visible: c.visible, ..o }), + None if clipping => clipping_text_outline(c), None => as_art(Some(d), c, None), }; if let Some(o) = art { @@ -415,7 +758,11 @@ fn container_keeping_type(d: &Document, n: &Node) -> Option { } } } - if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) || has_pathfinder(n) || has_own_paint(n) { + if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) + || has_pathfinder(n) + || has_own_paint(n) + || crate::reshape::copied_container_raster_at(n).is_some() + { return None; } let fx = geometry_effects(n); @@ -469,7 +816,7 @@ fn piece(d: &mut Document, n: &Node, path: PathData, rule: FillRule, item: Appea /// `n`'s geometry with its object-level geometry effects applied, its fill rule, the context of /// its effects, and `n` without those effects, its gradients moved along with them. -fn leaf_base(n: &Node) -> Option<(PathData, FillRule, GeomContext<'_>, Node)> { +pub(crate) fn leaf_base(n: &Node) -> Option<(PathData, FillRule, GeomContext<'_>, Node)> { let (base, rule) = geometry(n)?; let ctx = GeomContext::of(n); let mut m = n.clone(); @@ -698,8 +1045,61 @@ fn bake_appearance_pieces(doc: Option<&Document>, n: &mut Node, outline_strokes: /// resources of its placed documents' art added ([`Document::with_placed_art`]); `None` when /// there is nothing to do (export it as is). pub fn bake_document(doc: &Document) -> Option { + bake(doc, None) +} + +/// [`bake_document`], and every symbol instance whose symbol's art draws something baking changes +/// (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, 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))) +} + +/// Restores what [`bake`] changes in the thread's baking state when it ends. +struct Restore(Option>, u64, u64, usize, bool); + +impl Drop for Restore { + fn drop(&mut self) { + PLACING.with(|p| *p.borrow_mut() = self.0.take()); + PLACED_NODES.with(|c| c.set(self.1)); + DROPPED_NODES.with(|c| c.set(self.2)); + LEVEL.with(|c| c.set(self.3)); + UNWRITTEN.with(|c| c.set(self.4)); + } +} + +/// [`bake_document`], or with `placing` [`bake_document_placing_symbols`] with that `clip_slices`, +/// [`Placing::most_nodes`] and [`Placing::layers`]. +fn bake(doc: &Document, placing: Option<(bool, u64, WrittenLayers)>) -> Option { let placed = doc.with_placed_art(); - if !placed.layers.iter().any(|l| needs_bake(l)) { + let placing = placing + .map(|(clip_slices, most_nodes, layers)| (drawn_symbols(&placed), clip_slices, most_nodes, layers)) + .filter(|p| !p.0.is_empty()) + .map(|(symbols, clip_slices, most_nodes, layers)| Placing { + symbols, + clip_slices, + most_nodes, + heights: vectorcraft_doc::depth::DrawnHeights::of(&placed), + layers, + }); + // A bake inside another one (of art an effect makes) places symbols only when it asks to. + let _restore = Restore( + PLACING.with(|p| p.replace(placing.map(Rc::new))), + PLACED_NODES.with(|c| c.replace(0)), + DROPPED_NODES.with(|c| c.replace(0)), + LEVEL.with(|c| c.replace(1)), + UNWRITTEN.with(|c| c.replace(false)), + ); + if !placed.layers.iter().any(|l| needs_bake(l) || holds_placed_symbol(l)) { return match placed { std::borrow::Cow::Owned(d) => Some(d), std::borrow::Cow::Borrowed(_) => None, @@ -707,6 +1107,7 @@ pub fn bake_document(doc: &Document) -> Option { } let mut d = placed.into_owned(); NESTED_NODES.with(|c| c.set(0)); + NESTED_DROPPED.with(|c| c.set(0)); let layers = d.layers.clone(); d.layers = layers.iter().map(|l| bake_node(&mut d, l).map(Arc::new).unwrap_or_else(|| l.clone())).collect(); Some(d) diff --git a/crates/effects/src/bake/tests.rs b/crates/effects/src/bake/tests.rs index f3855f57ca..deb705752f 100644 --- a/crates/effects/src/bake/tests.rs +++ b/crates/effects/src/bake/tests.rs @@ -2,7 +2,7 @@ use super::*; use serde_json::json; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{CharStyle, Effect, NodeId, TextObject}; -use vectorcraft_geom::{Point, Rect, shapes}; +use vectorcraft_geom::{Point, Rect, Shape, shapes}; /// Type tests need glyph outlines, which only the optional craft-fonts build input provides. fn skip_without_craft_fonts() -> bool { @@ -793,7 +793,7 @@ fn type_outlined_next_to_type_that_stays_type_keeps_its_look() { } #[test] -fn type_in_a_clipping_group_with_a_fill_of_its_own_is_outlined_plain() { +fn type_in_a_clipping_group_with_a_fill_of_its_own_keeps_its_effect() { if skip_without_craft_fonts() { return; } @@ -808,9 +808,59 @@ fn type_in_a_clipping_group_with_a_fill_of_its_own_is_outlined_plain() { g.children_mut().unwrap().push(Arc::new(clip)); let d = bake_document(&doc_with(g)).unwrap(); assert_eq!(type_origins(&d), [(20.0, 60.0), (220.0, 60.0)]); - // The type clips by its plain outlines, as the canvas clips by them: its own effect is left out. + // The type clips by its outlines moved by its own effect, as the canvas clips by them. let b = d.node(NodeId(59)).and_then(|n| n.geometric_bounds()).unwrap(); - assert!(b.y0 > 30.0 && b.y1 < 70.0, "{b:?}"); + assert!(b.y0 > 330.0 && b.y1 < 370.0, "{b:?}"); +} + +#[test] +fn clipping_type_whose_fill_has_a_geometry_effect_clips_by_its_plain_outlines() { + if skip_without_craft_fonts() { + return; + } + let near = |a: Rect, b: Rect, tol: f64| [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|v| v.abs() < tol); + for stroke in [Paint::None, Paint::solid(Color::rgb(1.0, 0.0, 0.0))] { + // Type that clips a square, with a Transform effect on its own fill. + let mut t = type_node(60); + t.appearance = Appearance::basic(Paint::solid(Color::BLACK), stroke.clone(), 1.0).into(); + for item in &mut t.appearance.items { + if let AppearanceItem::Fill(f) = item { + f.effects.push(fx("distort.transform", json!({"moveH": 300}))); + } + } + let square = Node::path(NodeId(61), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art()); + let clip = Node::new(NodeId(62), NodeKind::Group { children: vec![Arc::new(t.clone()), Arc::new(square)], clip: true }); + let canvas = crate::clip_outline(&t).map(|(bp, _)| bp.bounding_box()).unwrap(); + assert!(canvas.x1 < 100.0, "the canvas clips by the plain outlines: {canvas:?}"); + let d = bake_document(&doc_with(clip)).unwrap(); + let baked = d.node(NodeId(62)).unwrap(); + // With a stroke, the clip group sits in a group with the stroke over it, outside the clip. + let group = match baked.kind { + NodeKind::Group { clip: true, .. } => { + assert!(stroke.is_none(), "{baked:?}"); + baked + } + _ => { + let ch = baked.children().unwrap(); + assert_eq!(ch.len(), 2, "{baked:?}"); + let strokes = ch[1].appearance.items.iter().all(|i| matches!(i, AppearanceItem::Stroke(_))); + assert!(matches!(ch[1].kind, NodeKind::Text(_)) && strokes, "the type with only its stroke: {:?}", ch[1]); + &ch[0] + } + }; + let ch = group.children().unwrap(); + assert!(matches!(group.kind, NodeKind::Group { clip: true, .. }) && ch.len() == 3, "{group:?}"); + // The export clips by the outlines the canvas clips by. + assert!(matches!(ch[0].kind, NodeKind::Path { clipping: true, .. }), "{:?}", ch[0]); + let b = crate::clip_outline(&ch[0]).map(|(bp, _)| bp.bounding_box()).unwrap(); + assert!(near(b, canvas, 1e-6), "canvas {canvas:?}, export {b:?}"); + // The fills (the characters' and the moved one) paint behind the square, inside the clip. + let fill = ch[1].geometric_bounds().unwrap(); + assert!((fill.x0 - canvas.x0).abs() < 1e-6 && fill.x1 > canvas.x1 + 250.0, "{fill:?}"); + assert_eq!(ch[2].id, NodeId(61)); + let mut ids = std::collections::HashSet::new(); + baked.walk(&mut |n| assert!(ids.insert(n.id), "duplicate id {}", n.id)); + } } #[test] @@ -1065,3 +1115,545 @@ fn exporting_a_path_with_a_transform_gives_each_copy_its_own_gradient() { // Three squares of their own, not one path spanning all three. assert_eq!(gradient_pieces(d.node(NodeId(50)).unwrap()), vec![10.0; 3]); } + +/// A 10 × 10 square at (10, 40), with id `id`, that a Transform effect moves 100 pt right. +fn moved_square(id: u64) -> Node { + let mut n = Node::path(NodeId(id), shapes::rectangle(Rect::new(10.0, 40.0, 20.0, 50.0)), Appearance::default_art()); + n.appearance.effects.push(fx("distort.transform", json!({"moveH": 100.0}))); + n +} + +fn instance(id: u64, symbol: &str, xf: vectorcraft_geom::Affine) -> Node { + Node::new(NodeId(id), NodeKind::SymbolInstance { symbol: symbol.into(), xf }) +} + +fn add_symbol(d: &mut Document, name: &str, art: Node) { + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); +} + +fn bounds(d: &Document, id: u64) -> Rect { + d.node(NodeId(id)).and_then(|n| n.geometric_bounds()).unwrap_or_else(|| panic!("node {id} has bounds")) +} + +fn near_rect(a: Rect, b: Rect) -> bool { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() < 1e-6) +} + +/// Each instance draws its symbol's art with the art's effects applied where the instance places +/// it: an instance that doubles the art's size moves it the effect's 100 pt, as the canvas draws +/// it, not 200 pt. Plain baking leaves the instances and the symbols' art as they are. +#[test] +fn placing_symbols_bakes_their_art_where_each_instance_places_it() { + use vectorcraft_geom::Affine; + let mut d = doc_with(instance(900, "S", Affine::IDENTITY)); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, instance(901, "S", Affine::translate((0.0, 100.0)) * Affine::scale(2.0))).unwrap(); + add_symbol(&mut d, "S", moved_square(800)); + assert!(bake_document(&d).is_none(), "nothing in the layers needs baking"); + let out = bake_document_placing_symbols(&d, true, ALL).unwrap(); + assert!(matches!(out.node(NodeId(900)).unwrap().kind, NodeKind::Group { .. })); + assert!(near_rect(bounds(&out, 900), Rect::new(110.0, 40.0, 120.0, 50.0)), "{:?}", bounds(&out, 900)); + assert!(near_rect(bounds(&out, 901), Rect::new(120.0, 180.0, 140.0, 200.0)), "{:?}", bounds(&out, 901)); + assert_eq!(out.symbols[0].art.appearance.effects.len(), 1, "the symbol's art keeps its effect"); +} + +/// An instance of a symbol whose art holds an instance of another symbol with effects draws that +/// art with its effects too. +#[test] +fn placing_symbols_reaches_the_art_of_nested_instances() { + use vectorcraft_geom::Affine; + let mut d = doc_with(instance(900, "Outer", Affine::IDENTITY)); + add_symbol(&mut d, "Inner", moved_square(800)); + add_symbol(&mut d, "Outer", Node::group(NodeId(801), vec![Arc::new(instance(802, "Inner", Affine::translate((0.0, 100.0))))])); + let out = bake_document_placing_symbols(&d, true, ALL).unwrap(); + assert!(near_rect(bounds(&out, 900), Rect::new(110.0, 140.0, 120.0, 150.0)), "{:?}", bounds(&out, 900)); +} + +/// A 10 pt square with id `id`, masked by `art` (the mask enabled unless `disabled`). +fn masked_square(id: u64, art: Node, disabled: bool) -> Node { + let mut n = Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); + let mut mask = vectorcraft_doc::OpacityMask::new(art, false); + mask.disabled = disabled; + n.extras_mut().mask = Some(Box::new(mask)); + n +} + +/// Whether the art of `n`'s opacity mask is still a symbol instance, and its bounds when it is not. +fn mask_art(n: &Node) -> (bool, Option) { + let art = &n.extras().mask.as_ref().unwrap_or_else(|| panic!("node {:?} has a mask", n.id)).art; + (matches!(art.kind, NodeKind::SymbolInstance { .. }), art.geometric_bounds()) +} + +/// An instance in the art of an enabled opacity mask is placed and baked like any other, so the +/// mask masks with the art the instance draws, and the masked object stays as it is (a clipping +/// path stays one); one in a disabled mask, in the mask of an object the export leaves out, or in +/// a ruler guide's mask, stays as it is. +#[test] +fn placing_symbols_reaches_instances_in_opacity_masks() { + use vectorcraft_geom::Affine; + let mut d = doc_with(masked_square(700, instance(900, "S", Affine::IDENTITY), false)); + let layer = d.layers[0].id; + d.insert(Some(layer), 1, masked_square(701, instance(901, "S", Affine::IDENTITY), true)).unwrap(); + let mut hidden = masked_square(702, instance(902, "S", Affine::IDENTITY), false); + hidden.visible = false; + d.insert(Some(layer), 2, hidden).unwrap(); + let mut clipping = masked_square(703, instance(903, "S", Affine::IDENTITY), false); + if let NodeKind::Path { clipping: c, .. } = &mut clipping.kind { + *c = true; + } + d.insert(Some(layer), 3, Node::group(NodeId(704), vec![Arc::new(clipping)])).unwrap(); + let mut guide = Node::new(NodeId(705), NodeKind::RulerGuide { vertical: false, pos: 5.0, artboard: None }); + guide.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(instance(905, "S", Affine::IDENTITY), false))); + d.insert(Some(layer), 4, guide).unwrap(); + add_symbol(&mut d, "S", moved_square(800)); + let out = bake_document_placing_symbols(&d, true, ALL).unwrap(); + for id in [700, 703] { + let (still, b) = mask_art(out.node(NodeId(id)).unwrap()); + assert!(!still && b.is_some_and(|b| near_rect(b, Rect::new(110.0, 40.0, 120.0, 50.0))), "{id}: {b:?}"); + } + assert!(matches!(out.node(NodeId(703)).unwrap().kind, NodeKind::Path { clipping: true, .. }), "the clipping path stays one"); + assert!(mask_art(out.node(NodeId(701)).unwrap()).0, "a disabled mask's instance stays"); + assert!(mask_art(out.node(NodeId(702)).unwrap()).0, "a hidden object's mask's instance stays"); + assert!(mask_art(out.node(NodeId(705)).unwrap()).0, "a ruler guide's mask's instance stays"); +} + +/// A symbol whose art holds an instance only in an opacity mask's art is placed too, and the +/// instance in its mask is placed with it. +#[test] +fn placing_symbols_reaches_instances_in_the_masks_of_symbol_art() { + use vectorcraft_geom::Affine; + let mut d = doc_with(instance(900, "Outer", Affine::IDENTITY)); + add_symbol(&mut d, "Inner", moved_square(800)); + add_symbol(&mut d, "Outer", masked_square(803, instance(802, "Inner", Affine::IDENTITY), false)); + let out = bake_document_placing_symbols(&d, true, ALL).unwrap(); + assert!(!is_instance(&out, 900), "the outer instance is placed"); + let mut found = None; + out.node(NodeId(900)).unwrap().walk(&mut |n| { + if n.id == NodeId(803) { + found = Some(mask_art(n)); + } + }); + let (still, b) = found.unwrap_or_else(|| panic!("the masked square is in the placed art")); + assert!(!still && b.is_some_and(|b| near_rect(b, Rect::new(110.0, 40.0, 120.0, 50.0))), "{b:?}"); +} + +/// A symbol whose art holds an instance of itself is placed until the depth limit, and the export +/// ends. +#[test] +fn placing_a_symbol_that_holds_itself_stops() { + use vectorcraft_geom::Affine; + let mut d = doc_with(instance(900, "Loop", Affine::IDENTITY)); + add_symbol( + &mut d, + "Loop", + Node::group(NodeId(801), vec![Arc::new(moved_square(800)), Arc::new(instance(802, "Loop", Affine::translate((0.0, 1.0))))]), + ); + let out = bake_document_placing_symbols(&d, true, ALL).unwrap(); + let mut lefts = vec![]; + out.node(NodeId(900)).unwrap().walk(&mut |n| lefts.extend(n.path_data().and_then(|p| p.bounds()).map(|b| b.x0))); + assert!(lefts.len() > 1 && lefts.iter().all(|x| (x - 110.0).abs() < 1e-6), "{lefts:?}"); + let mut depth = 0; + let mut n = out.node(NodeId(900)).unwrap(); + while let Some(next) = n.children().and_then(|ch| ch.last()) { + n = next; + depth += 1; + } + assert!(depth <= 3 * (vectorcraft_doc::depth::MAX_DEPTH + 1), "{depth}"); +} + +/// A dynamic symbol instance's own paint for an object of the art applies before the object's +/// effects are baked: a fill whose own Transform effect makes the square a group of pieces still +/// paints in the instance's red, and its sibling keeps the symbol's paint. +#[test] +fn placing_symbols_keeps_dynamic_instances_changes() { + use vectorcraft_geom::Affine; + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let mut square = Node::path(NodeId(800), shapes::rectangle(Rect::new(10.0, 40.0, 20.0, 50.0)), Appearance::default_art()); + if let Some(AppearanceItem::Fill(f)) = square.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))) { + f.effects.push(fx("distort.transform", json!({"moveH": 100.0}))); + } + let sibling = Node::path(NodeId(801), shapes::rectangle(Rect::new(10.0, 60.0, 20.0, 70.0)), Appearance::default_art()); + let mut inst = instance(900, "D", Affine::IDENTITY); + inst.extras_mut().symbol_overrides = vec![vectorcraft_doc::SymbolOverride { path: vec![0], fill: Some(red.clone()), ..Default::default() }]; + let mut d = doc_with(inst); + add_symbol(&mut d, "D", Node::group(NodeId(802), vec![Arc::new(square), Arc::new(sibling)])); + d.symbols[0].dynamic = true; + let out = bake_document_placing_symbols(&d, true, ALL).unwrap(); + let mut fills = vec![]; + out.node(NodeId(900)).unwrap().walk(&mut |n| { + if n.path_data().is_some() + && let Some(b) = n.geometric_bounds() + { + fills.push((b.x0.round(), b.y0.round(), n.appearance.fill_paint())); + } + }); + assert!(fills.contains(&(110.0, 40.0, red)), "{fills:?}"); + assert!(fills.contains(&(10.0, 60.0, Paint::solid(Color::WHITE))), "{fills:?}"); +} + +/// An instance whose fill stains its symbol's art places the art in its stained colors, with the +/// art's effects applied after the stain: a Transform moves the stained square and an Invert +/// inverts the stained color. +#[test] +fn placing_symbols_keeps_the_instances_stain() { + use vectorcraft_geom::Affine; + let blue = Color::rgb8(30, 90, 220); + let mut inst = instance(900, "Mark", Affine::IDENTITY); + inst.appearance = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0).into(); + inst.appearance.items.retain(|i| i.is_fill()); + if let AppearanceItem::Fill(f) = &mut inst.appearance.items[0] { + f.opacity = 0.5; + } + let square = + Node::path(NodeId(800), shapes::rectangle(Rect::new(10.0, 40.0, 20.0, 50.0)), Appearance::basic(Paint::solid(blue), Paint::None, 0.0)); + let stained = vectorcraft_doc::symbol_overrides::instance_art(&square, &inst).appearance.fill_paint().color().unwrap(); + assert_ne!(stained.to_hex(), blue.to_hex()); + let [r, g, b] = stained.to_rgb(); + let inverted = Color::rgb(1.0 - r, 1.0 - g, 1.0 - b); + for (id, params, want) in [("distort.transform", json!({"moveH": 100.0}), stained), (crate::addons::color::INVERT, json!({}), inverted)] { + let mut art = square.clone(); + art.appearance.effects.push(fx(id, params)); + let mut d = doc_with(inst.clone()); + add_symbol(&mut d, "Mark", art); + let out = bake_document_placing_symbols(&d, true, ALL).unwrap(); + assert!(!is_instance(&out, 900), "{id}: the instance is placed"); + let mut fills = vec![]; + out.node(NodeId(900)).unwrap().walk(&mut |n| { + if n.path_data().is_some() { + fills.extend(n.appearance.fill_paint().color().map(|c| c.to_hex())); + } + }); + assert_eq!(fills, [want.to_hex()], "{id}"); + } +} + +/// Every layer written, as DXF writes them (template layers are never written). +const ALL: WrittenLayers = WrittenLayers { hidden: true, non_printing: true, hidden_objects: false }; + +fn is_instance(d: &Document, id: u64) -> bool { + d.node(NodeId(id)).is_some_and(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })) +} + +/// The art placed for an export is counted as baked: the copies an effect makes count, so an +/// instance whose baked art passes what is left of the budget stays an instance, and the budget +/// holds the baked art of the instances placed, exactly. +#[test] +fn placing_symbols_counts_the_baked_art() { + use vectorcraft_geom::Affine; + let mut d = doc_with(instance(900, "S", Affine::IDENTITY)); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, instance(901, "S", Affine::translate((0.0, 100.0)))).unwrap(); + add_symbol(&mut d, "S", gradient_copies(800)); + let all = bake(&d, Some((true, u64::MAX, ALL))).unwrap(); + let each = all.node(NodeId(900)).map_or(0, |n| n.count_with_masks() as u64); + assert!(each > 2, "the instance's group, and the copies as objects of their own: {each}"); + assert_eq!(all.node(NodeId(901)).map(|n| n.count_with_masks() as u64), Some(each)); + let fits = bake(&d, Some((true, 2 * each, ALL))).unwrap(); + assert!(!is_instance(&fits, 900) && !is_instance(&fits, 901)); + let short = bake(&d, Some((true, 2 * each - 1, ALL))).unwrap(); + assert_eq!(usize::from(is_instance(&short, 900)) + usize::from(is_instance(&short, 901)), 1, "one instance stays as it is"); +} + +/// The baked art of an instance placed inside another's art is counted once: a budget of exactly +/// the outer instance's baked art places both. +#[test] +fn placing_symbols_counts_nested_art_once() { + use vectorcraft_geom::Affine; + let mut d = doc_with(instance(900, "Outer", Affine::IDENTITY)); + add_symbol(&mut d, "Inner", gradient_copies(800)); + add_symbol(&mut d, "Outer", Node::group(NodeId(801), vec![Arc::new(instance(802, "Inner", Affine::IDENTITY))])); + let all = bake(&d, Some((true, u64::MAX, ALL))).unwrap(); + let total = all.node(NodeId(900)).map_or(0, |n| n.count_with_masks() as u64); + let exact = bake(&d, Some((true, total, ALL))).unwrap(); + assert!(!is_instance(&exact, 900) && !is_instance(&exact, 802), "both are placed within {total}"); + let short = bake(&d, Some((true, total - 1, ALL))).unwrap(); + assert!(is_instance(&short, 900), "the outer instance stays as it is"); +} + +/// While an instance's art bakes, the art's own objects are held in the budget: an instance +/// nested in it whose art does not fit in what is left stays as it is, and the outer instance is +/// placed around it. +#[test] +fn placing_symbols_holds_the_outer_art_while_it_bakes() { + use vectorcraft_geom::Affine; + let mut d = doc_with(instance(900, "Outer", Affine::IDENTITY)); + add_symbol(&mut d, "Inner", Node::group(NodeId(803), vec![Arc::new(gradient_copies(800))])); + let mut art: Vec> = (0..5) + .map(|i| Arc::new(Node::path(NodeId(810 + i), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()))) + .collect(); + art.push(Arc::new(instance(802, "Inner", Affine::IDENTITY))); + let outer = Node::group(NodeId(801), art); + // The outer instance's group around its art, with the inner instance left as it is. + let around = 1 + outer.count_with_masks() as u64; + add_symbol(&mut d, "Outer", outer); + let all = bake(&d, Some((true, u64::MAX, ALL))).unwrap(); + let inner = all.node(NodeId(802)).map_or(0, |n| n.count_with_masks() as u64); + assert!(inner > 2 && inner <= around, "the inner art alone fits: {inner} <= {around}"); + let out = bake(&d, Some((true, around, ALL))).unwrap(); + assert!(!is_instance(&out, 900) && is_instance(&out, 802), "the outer instance is placed around the inner one"); +} + +/// Art baked for an instance and then left out, because it passes the budget, still counts: an +/// instance after it whose art would fit in the budget alone stays as it is, and a budget with +/// room for both places both. +#[test] +fn placing_symbols_counts_the_art_it_drops() { + use vectorcraft_geom::Affine; + let mut d = doc_with(instance(901, "Small", Affine::IDENTITY)); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, instance(900, "Big", Affine::IDENTITY)).unwrap(); + add_symbol(&mut d, "Big", gradient_copies(800)); + add_symbol(&mut d, "Small", moved_square(810)); + let all = bake(&d, Some((true, u64::MAX, ALL))).unwrap(); + let count = |id: u64| all.node(NodeId(id)).map_or(0, |n| n.count_with_masks() as u64); + let (big, small) = (count(900), count(901)); + assert!(small < big, "{small} < {big}"); + let short = bake(&d, Some((true, big - 1, ALL))).unwrap(); + assert!(is_instance(&short, 900), "the big art passes {}", big - 1); + assert!(is_instance(&short, 901), "the big art's {big} objects count, so the small art does not fit"); + let both = bake(&d, Some((true, big + small, ALL))).unwrap(); + assert!(!is_instance(&both, 900) && !is_instance(&both, 901)); +} + +/// Instances the export does not write are not placed and do not count against the budget: with +/// room for one instance's baked art, hidden instances, an instance in a hidden group, one on a +/// template layer, one on a layer that does not print and one on a hidden layer (when the export +/// leaves those layers out) come first and stay as they are, and the visible instance after them +/// is placed. An export that writes those layers places their instances first. +#[test] +fn placing_symbols_skips_instances_the_export_leaves_out() { + use vectorcraft_geom::Affine; + let mut d = doc_with(instance(900, "S", Affine::IDENTITY)); + add_symbol(&mut d, "S", gradient_copies(800)); + let each = bake(&d, Some((true, u64::MAX, ALL))).unwrap().node(NodeId(900)).map_or(0, |n| n.count_with_masks() as u64); + let layer = d.layers[0].id; + let mut hidden = instance(901, "S", Affine::IDENTITY); + hidden.visible = false; + let mut group = Node::group(NodeId(902), vec![Arc::new(instance(903, "S", Affine::IDENTITY))]); + group.visible = false; + for (i, n) in [hidden, group].into_iter().enumerate() { + d.insert(Some(layer), i, n).unwrap(); + } + let mut left_out = vec![]; + for (id, template, printable, visible) in [(910, true, true, true), (920, false, false, true), (930, false, true, false)] { + let mut l = Node::layer(NodeId(id), &format!("L{id}"), vectorcraft_doc::LayerColor::Preset(0)); + if let NodeKind::Layer { template: t, printable: p, .. } = &mut l.kind { + *t = template; + *p = printable; + } + l.visible = visible; + if let Some(ch) = l.children_mut() { + ch.push(Arc::new(instance(id + 1, "S", Affine::IDENTITY))); + } + left_out.push(Arc::new(l)); + } + d.layers.splice(0..0, left_out); + let out = bake(&d, Some((true, each, WrittenLayers::default()))).unwrap(); + assert!(!is_instance(&out, 900), "the visible instance is placed within {each}"); + for id in [901, 903, 911, 921, 931] { + assert!(is_instance(&out, id), "{id} stays as it is"); + } + // 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, ..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. +fn in_groups(id: u64, levels: u64, leaf: Node) -> Node { + (0..levels).fold(leaf, |n, i| Node::group(NodeId(id + i), vec![Arc::new(n)])) +} + +/// Placed art is drawn no deeper than the document may draw: an instance whose art's effects add +/// a level past it stays an instance, and the instances around it are placed. +#[test] +fn placing_symbols_keeps_the_baked_art_within_the_drawn_depth() { + use vectorcraft_doc::depth::{DrawnHeights, MAX_DRAWN_DEPTH}; + use vectorcraft_geom::Affine; + // The instance on the layer is 2 deep; A to D each hold the next 31 objects down, and E's + // square is 2 deep in its art: 2 + 4 × 31 + 2 = MAX_DRAWN_DEPTH. + let mut d = doc_with(instance(900, "A", Affine::IDENTITY)); + for (i, (name, next)) in [("A", "B"), ("B", "C"), ("C", "D"), ("D", "E")].into_iter().enumerate() { + let base = 1000 * (i as u64 + 1); + add_symbol(&mut d, name, in_groups(base, 30, instance(base + 100, next, Affine::IDENTITY))); + } + add_symbol(&mut d, "E", in_groups(5000, 1, gradient_copies(5100))); + assert!(!d.too_deep(None)); + assert_eq!(DrawnHeights::of(&d).deepest(&d.layers[0], 1), MAX_DRAWN_DEPTH); + let out = bake_document_placing_symbols(&d, true, ALL).unwrap(); + // E's square becomes a group of copies, a level past the cap: E's instance stays. + assert!(is_instance(&out, 4100), "E's instance stays as it is"); + assert!(!is_instance(&out, 900) && !is_instance(&out, 3100), "A to D are placed"); + assert!(DrawnHeights::of(&out).deepest(&out.layers[0], 1) <= MAX_DRAWN_DEPTH); + // Without the chain above it, E's art is placed. + let mut shallow = doc_with(instance(900, "E", Affine::IDENTITY)); + add_symbol(&mut shallow, "E", in_groups(5000, 1, gradient_copies(5100))); + assert!(!is_instance(&bake_document_placing_symbols(&shallow, true, ALL).unwrap(), 900)); +} + +/// Art baked for an instance and then left out because it draws too deep still counts when the +/// baked art of a later instance is checked: that art fits before its effects add copies, but +/// not once they do. +#[test] +fn placing_symbols_counts_art_dropped_for_depth_against_later_baked_art() { + use vectorcraft_geom::Affine; + // The chain of placing_symbols_keeps_the_baked_art_within_the_drawn_depth, then F, whose + // square becomes a group of copies once baked. + let mut d = doc_with(instance(900, "A", Affine::IDENTITY)); + for (i, (name, next)) in [("A", "B"), ("B", "C"), ("C", "D"), ("D", "E")].into_iter().enumerate() { + let base = 1000 * (i as u64 + 1); + add_symbol(&mut d, name, in_groups(base, 30, instance(base + 100, next, Affine::IDENTITY))); + } + add_symbol(&mut d, "E", in_groups(5000, 1, gradient_copies(5100))); + add_symbol(&mut d, "F", gradient_copies(6000)); + let layer = d.layers[0].id; + d.insert(Some(layer), 1, instance(901, "F", Affine::IDENTITY)).unwrap(); + let all = bake(&d, Some((true, u64::MAX, ALL))).unwrap(); + assert!(is_instance(&all, 4100) && !is_instance(&all, 900) && !is_instance(&all, 901)); + let count = |d: &Document, id: u64| d.node(NodeId(id)).map_or(0, |n| n.count_with_masks() as u64); + let (a, f) = (count(&all, 900), count(&all, 901)); + // E's baked art, as placed where nothing above it draws deep. + let mut shallow = doc_with(instance(4100, "E", Affine::IDENTITY)); + add_symbol(&mut shallow, "E", in_groups(5000, 1, gradient_copies(5100))); + let e = count(&bake(&shallow, Some((true, u64::MAX, ALL))).unwrap(), 4100); + assert!(f > 2, "F's copies are objects of their own: {f}"); + let short = bake(&d, Some((true, a + e + f - 1, ALL))).unwrap(); + assert!(!is_instance(&short, 900) && is_instance(&short, 4100), "A to D are placed, E is not"); + assert!(is_instance(&short, 901), "E's dropped {e} objects count, so F's baked {f} do not fit"); + 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 424beebe17..ea727b804c 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -182,50 +182,50 @@ 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)}. 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":[]}), + "{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)}. 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":[]}), + "{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)}. 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}), + "{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)}. 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":[]}), + "{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), 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","drawHiddenFaces":false}), + "{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)}. 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"}), + "{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)}. 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"}), + "{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( "convertToShape.rectangle", @@ -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( @@ -417,7 +417,7 @@ pub fn effect_catalog() -> Vec { "artistic.roughPastels", "Rough Pastels…", ARTISTIC, - "{strokeLength: 0..40 (6; longer pastel strokes), strokeDetail: 1..20 (10; bristle texture along the strokes), texture: \"brick\"|\"burlap\"|\"canvas\"|\"sandstone\" (\"canvas\"), scaling: % 50..200 (100), relief: 0..50 (4), lightDirection: \"bottom\"|\"bottomLeft\"|\"left\"|\"topLeft\"|\"top\"|\"topRight\"|\"right\"|\"bottomRight\" (\"top\"), invert: bool (false)} repaints the object in soft diagonal pastel strokes over a textured surface, keeping its coverage. Slider ranges follow the documented controls; numeric defaults are chosen for VectorCraft and are not verified against proprietary defaults.", + "{strokeLength: 0..40 (6; longer pastel strokes), strokeDetail: 1..20 (10; bristle texture along the strokes), texture: \"brick\"|\"burlap\"|\"canvas\"|\"sandstone\"|\"loaded\" (\"canvas\"; \"loaded\" draws the image in textureImage and draws Canvas when there is none; the others are surfaces made in code), textureImage?: {path} | {name?, dataBase64} | string (Load Texture…: an image file that File › Place reads, within the renderer's pixel allowance, stored as its gray levels in a grayscale PNG in base64; a file sets texture to \"loaded\" unless texture is given, and the stored string, as effect.list gives it, is kept as it is), scaling: % 50..200 (100), relief: 0..50 (4), lightDirection: \"bottom\"|\"bottomLeft\"|\"left\"|\"topLeft\"|\"top\"|\"topRight\"|\"right\"|\"bottomRight\" (\"top\"), invert: bool (false)} repaints the object in soft diagonal pastel strokes over a textured surface, keeping its coverage. A loaded texture lies one image pixel per point at 100 %, centered on the object's center and repeated; each pixel's luma is the surface's height, from 0 for black to 1 pt for white, and a transparent pixel counts as middle gray. Slider ranges follow the documented controls; numeric defaults are chosen for VectorCraft and are not verified against proprietary defaults.", json!({ "strokeLength": 6.0, "strokeDetail": 10.0, @@ -468,8 +468,8 @@ pub fn effect_catalog() -> Vec { "blur.radial", "Radial Blur…", BLUR, - "{amount: 1..100 (10; spin: an arc of `amount`°, zoom: the content scaled by up to about ±amount/2 %), method: \"spin\"|\"zoom\" (\"spin\"), quality: \"draft\"|\"good\"|\"best\" (\"good\"; 16, 64 or 256 samples)} blurs around the object's centre", - json!({"amount": 10.0, "method": "spin", "quality": "good"}), + "{amount: 1..100 (10; spin: an arc of `amount`°, zoom: the content scaled by up to about ±amount/2 %), method: \"spin\"|\"zoom\" (\"spin\"), quality: \"draft\"|\"good\"|\"best\" (\"good\"; 16, 64 or 256 samples), centerX: 0..1 (0.5; the Blur Center across the object's bounds, 0 their left edge), centerY: 0..1 (0.5; the Blur Center down the object's bounds, 0 their top edge)} blurs around the Blur Center, which moves and scales with the object. A centerX or centerY outside 0..1 is refused", + json!({"amount": 10.0, "method": "spin", "quality": "good", "centerX": 0.5, "centerY": 0.5}), ), r( "blur.smart", @@ -859,7 +859,7 @@ pub fn effect_catalog() -> Vec { crate::SVG_FILTER, "SVG Filter", &["Effect", "SVG Filters"], - "{name: string (the filter's id), xml: string (one SVG element with an id and 1..64 primitives, at most 64 KB), scale: number 0.001..1000 (1; points per unit of the filter's user space), origin: [x, y] pt ([0, 0]; where the filter's user space starts in the document)} runs the SVG filter on the object's pixels, its lengths in points times scale, at the Document Raster Effects resolution or finer; svgFilter.apply applies one of the document's filters (svgFilter.list)", + "{name: string (the filter's id), xml: string (one SVG element with an id and 1..64 primitives, at most 64 KB), scale: number 0.001..1000 (1; points per unit of the filter's user space), origin: [x, y] pt ([0, 0]; where the filter's user space starts in the document), axes?: [a, b, c, d] (absent or [1, 0, 0, 1]: the document's axes, and not null; the document directions of one unit along the filter's x axis [a, b] and y axis [c, d] before scale, each -1000..1000, with a·d - b·c at least 0.001 from 0; a turned, skewed or unevenly scaled user space, as SVG import gives a filtered element under a rotate, skew or uneven scale; the filter's offsets, blurs and region run along these axes; moving, turning or skewing the object moves origin and leaves axes)} runs the SVG filter on the object's pixels, its lengths in points times scale, at the Document Raster Effects resolution or finer; svgFilter.apply applies one of the document's filters (svgFilter.list)", json!({"scale": 1.0, "origin": [0.0, 0.0]}), )); v diff --git a/crates/effects/src/clip.rs b/crates/effects/src/clip.rs index a3e31f1842..8a8730f66d 100644 --- a/crates/effects/src/clip.rs +++ b/crates/effects/src/clip.rs @@ -7,9 +7,157 @@ use vectorcraft_geom::{BezPath, FillRule, PathData}; /// The clipping path `clip` of a clip group as one path and fill rule: compound paths keep their /// holes, even-odd paths their rule, text clips by its glyph outlines and a group by the union of -/// its members. `None` when there is nothing to clip by (the clipped art is then hidden). +/// its members. The live geometry effects of the clipping path (and of the members it clips by) +/// reshape the region, as they reshape what it paints, and so do the geometry effects of a path's +/// fills and strokes: the region is then the union of the paths they give, as an export bakes them. +/// `None` when there is nothing to clip by (the clipped art is then hidden). pub fn clip_outline(clip: &Node) -> Option<(BezPath, FillRule)> { - clip.clip_outline(Some(&outline_text), &unite) + reshaped_clip_outline(clip).unwrap_or_else(|| clip.clip_outline(Some(&outline_text), &unite)) +} + +/// [`clip_outline`] of a clipping path that a live geometry effect reshapes; `None` when nothing +/// `clip` clips by has a geometry effect of its own or on a fill or stroke. A hidden member of a +/// group or layer does not clip, so its effects are not counted. +pub fn reshaped_clip_outline(clip: &Node) -> Option> { + clip_effects_applied(clip, true, || true).map(|m| m.clip_outline(Some(&outline_text), &unite)) +} + +/// `n`, the clipping path of a clip group, with the live geometry effects of everything it clips by +/// applied, innermost first, and removed: a path or compound path with effects becomes a path of +/// its reshaped geometry that keeps its fills, strokes and other effects (its gradients follow the +/// effects, as an export bakes it), the paths of a compound path and the visible members of a group +/// are reshaped by their own effects before the effects around them, a group's or layer's own +/// effects reshape its members as an export evaluates them, and other objects with effects (type) +/// become a path of their reshaped region. A path or compound path whose fills or strokes have +/// geometry effects becomes a group of one path per fill and stroke, reshaped by the path's effects +/// and then by that fill's or stroke's, as an export bakes it; [`clip_outline`] clips by their +/// union, and the group is marked as such pieces +/// ([`vectorcraft_doc::NodeExtras::clip_pieces`]), so a clipping path that paints still paints +/// them ([`Node::clip_paint`]). `None` when nothing in it has a geometry effect. Effects on the +/// clip group or around it then reshape the result, after its own. +pub(crate) fn with_clip_effects_applied(n: &Node) -> Option { + with_clip_effects_applied_while(n, || true) +} + +/// [`with_clip_effects_applied`] that calls `take` before it visits each member of a group, layer +/// or compound path in `n`, at every depth: once `take` returns `false`, that member and the +/// members after it are not visited. The members of a group or layer that are not visited stay as +/// they are, with their effects. A compound path with geometry effects of its own still becomes a +/// path of its reshaped geometry. A path or compound path whose fills or strokes have geometry +/// effects still becomes a group of one path per fill and stroke. In both cases the paths in it +/// that are not visited go into that geometry as they are, and their own effects are not applied. +pub(crate) fn with_clip_effects_applied_while(n: &Node, take: fn() -> bool) -> Option { + let mut m = clip_effects_applied(n, true, take)?; + if matches!(n.kind, NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. }) && matches!(m.kind, NodeKind::Group { clip: false, .. }) { + m.extras_mut().clip_pieces = true; + } + Some(m) +} + +/// [`with_clip_effects_applied_while`]; with `items` unset (the paths of a compound path, which +/// draw with the compound path's fills and strokes), the geometry effects of `n`'s own fills and +/// strokes are left out. +fn clip_effects_applied(n: &Node, items: bool, take: fn() -> bool) -> Option { + let mut m: Option = None; + let members: &[std::sync::Arc] = match &n.kind { + NodeKind::Group { children, clip: true } => children.get(..1).unwrap_or_default(), + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Compound { children, .. } => children, + _ => &[], + }; + // A group or layer clips by its visible members after its shaper; a compound path by all of + // its paths, and a nested clip group by its clipping path, shown or hidden + // ([`Node::clip_shapes`]). + let all = matches!(n.kind, NodeKind::Compound { .. } | NodeKind::Group { clip: true, .. }); + let skip = usize::from(matches!(n.kind, NodeKind::Group { clip: false, .. } | NodeKind::Layer { .. }) && n.extras().shaper.is_some()); + // The paths of a compound path draw with the compound path's fills and strokes, and stay paths. + let compound = matches!(n.kind, NodeKind::Compound { .. }); + for (i, c) in members.iter().enumerate().skip(skip).filter(|(_, c)| all || c.visible) { + if !take() { + break; + } + if let Some(r) = clip_effects_applied(c, items && !compound, take) + && let Some(slot) = m.get_or_insert_with(|| n.clone()).children_mut().and_then(|ch| ch.get_mut(i)) + { + *slot = std::sync::Arc::new(r); + } + } + let items = items + && matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) + && n.appearance.items.iter().any(|i| crate::has_geometry(crate::bake::item_effects(i))); + if items && let Some((g, rule, ctx, mut p)) = crate::bake::leaf_base(m.as_ref().unwrap_or(n)) { + let children = n + .appearance + .items + .iter() + .zip(&p.appearance.items) + .map(|(item, carried)| { + // A fill or stroke whose Transform effect scales strokes or moves patterns is drawn + // through its art, as an export bakes such a path ([`crate::reshape`]). + let mut whole = Node::path(n.id, g.clone(), Appearance { items: vec![carried.clone()], ..Default::default() }); + if let NodeKind::Path { rule: r, .. } = &mut whole.kind { + *r = rule; + } + if crate::has_transform_art(&whole) + && let Some(art) = crate::reshape(None, &whole, None) + { + return std::sync::Arc::new(art); + } + let (ig, mut it) = crate::bake::apply_item(item, carried, &g, &ctx); + crate::bake::clear_item_effects(&mut it); + let mut piece = Node::path(n.id, ig, Appearance { items: vec![it], ..Default::default() }); + if let NodeKind::Path { rule: r, .. } = &mut piece.kind { + *r = rule; + } + std::sync::Arc::new(piece) + }) + .collect(); + // The path's transparency and raster effects stay on the group of its pieces. + p.appearance.items.clear(); + p.kind = NodeKind::Group { children, clip: false }; + return Some(p); + } + if !crate::has_geometry(&n.appearance.effects) { + return m; + } + let cur = m.as_ref().unwrap_or(n); + // A group's or layer's effects reshape each of its members (a clip group's its clipping + // path), as an export evaluates them; otherwise they reshape its region, below. + if matches!(cur.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) + && let Some(e) = crate::group::evaluate_container(None, cur) + { + return Some(e); + } + // A path or compound path, as an export bakes it. + if let Some((g, rule, _, mut p)) = crate::bake::leaf_base(cur) { + let clipping = match &cur.kind { + NodeKind::Path { clipping, .. } => *clipping, + NodeKind::Compound { children, .. } => children.iter().any(|c| matches!(c.kind, NodeKind::Path { clipping: true, .. })), + _ => false, + }; + p.kind = Node::path(n.id, g, Appearance::default()).kind; + if let NodeKind::Path { rule: r, clipping: c, .. } = &mut p.kind { + (*r, *c) = (rule, clipping); + } + return Some(p); + } + // Type, as its painted outlines that its effects reshape as an export evaluates them. + if matches!(cur.kind, NodeKind::Text(_)) + && let Some(mut o) = crate::outline_text(cur) + { + o.visible = n.visible; + o.appearance.effects = n.appearance.effects.clone(); + if let Some(e) = crate::group::evaluate_container(None, &o) { + return Some(e); + } + } + let (bp, rule) = cur.clip_outline(Some(&outline_text), &unite)?; + let (g, _) = crate::bake::apply(&n.appearance.effects, &PathData::from_bezpath(&bp), &crate::GeomContext::of(n)); + let mut p = Node::path(n.id, g, Appearance::default()); + if let NodeKind::Path { rule: r, .. } = &mut p.kind { + *r = rule; + } + p.visible = n.visible; + Some(p) } /// The knockout shape of a piece of a mesh-warped image ([`Node::knockout_outline`]) painted opaque diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index bb2f605a91..9531159e01 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() @@ -661,8 +673,9 @@ pub fn has_container_appearance(n: &Node) -> bool { /// The regions a group's or layer's own fills and strokes paint, in document space, each with its /// fill rule: every visible member path and compound path, type as its glyph outlines and live /// objects evaluated; a compound shape as its area, with the symbol instances among its members -/// as their symbols' art from `doc`; the members of a clip group or clipping layer without its -/// clipping path. Images, other symbol instances and guides add nothing. A Repeat counts the +/// as their symbols' art from `doc`; a clip group or clipping layer (`n` itself or one among its +/// members) as the region its clipping path clips to ([`crate::clip::clip_outline`]), so members +/// it hides add nothing. Images, other symbol instances and guides add nothing. A Repeat counts the /// Repeats in the art of `doc`'s symbols that its instances show toward its instance budget. pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRule)> { fn push(doc: Option<&Document>, n: &Node, out: &mut Vec<(PathData, FillRule)>) { @@ -690,8 +703,14 @@ pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRul } } fn members(doc: Option<&Document>, n: &Node, out: &mut Vec<(PathData, FillRule)>) { - let clip = usize::from(n.clips()); - for c in n.children().into_iter().flatten().skip(clip) { + // A clip group shows its members only inside its clipping path: its outline is that + // region, not the clipped members' own shapes, which may reach far outside it (#7289). + if n.clips() { + let clip = n.children().and_then(|ch| ch.first()); + out.extend(clip.and_then(|c| crate::clip::clip_outline(c)).map(|(bp, rule)| (PathData::from_bezpath(&bp), rule))); + return; + } + for c in n.children().into_iter().flatten() { push(doc, c, out); } } @@ -734,35 +753,75 @@ fn item_art(id: NodeId, item: &AppearanceItem, shapes: &[(PathData, FillRule)], Some(g) } -/// Whether a sublayer among the members of `n`, or among its groups' members, holds a ruler guide. -fn sublayer_guides(n: &Node) -> bool { - n.children().is_some_and(|ch| ch.iter().any(|c| c.holds_ruler_guides() || (!c.is_layer() && sublayer_guides(c)))) +/// The members of a container that [`take_held_guides`] visits, by index, each with the same for +/// its own members. A ruler guide's entry is empty, whether its container is a layer or a group; a +/// container's is not. +#[derive(Default)] +struct HeldGuides(Vec<(usize, HeldGuides)>); + +/// The members of `n` that are ruler guides (`is_guide`), and those holding one at any depth, in +/// order. Every member at every depth is looked at once: a sublayer or group with no guide of its +/// own is still looked into, and a guide directly in a group counts as one in a layer does. A +/// member holding no guide gets no entry. +fn held_guides(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> HeldGuides { + let mut held = vec![]; + for (i, c) in n.children().into_iter().flatten().enumerate() { + if is_guide(c) { + held.push((i, HeldGuides::default())); + continue; + } + let inner = held_guides(c, is_guide); + if !inner.0.is_empty() { + held.push((i, inner)); + } + } + HeldGuides(held) } -/// Move the ruler guides of the sublayers among the members of `n`, and among its groups' -/// members, to `out`, in order. A guide taken from a hidden or locked sublayer, or from one inside -/// such a sublayer or group, is hidden or locked itself. Only containers holding one are copied. -fn take_sublayer_guides(n: &mut Node, out: &mut Vec>, hidden: bool, locked: bool) { +/// Move the ruler guides of `n` and of its members that [`held_guides`] found (`held`) to `out`: +/// those of `n` first, in order, then those of each member in turn. A guide taken from a hidden or +/// locked container, or from one inside such a container, is hidden or locked itself. Only the +/// containers in `held` are copied, and only those are visited. +fn take_held_guides(n: &mut Node, held: HeldGuides, out: &mut Vec>, hidden: bool, locked: bool) { let Some(ch) = n.children_mut() else { return }; - for c in ch.iter_mut().filter(|c| c.holds_ruler_guides() || (!c.is_layer() && sublayer_guides(c))) { + let (mut own, mut deeper) = (vec![], vec![]); + for (i, inner) in held.0 { + if inner.0.is_empty() { + own.push(i); + continue; + } + let Some(c) = ch.get_mut(i) else { continue }; let c = Arc::make_mut(c); let (hidden, locked) = (hidden || !c.visible, locked || c.locked); - if c.is_layer() - && let Some(lc) = c.children_mut() - { - let (taken, art): (Vec<_>, Vec<_>) = std::mem::take(lc).into_iter().partition(|g| g.is_ruler_guide()); - *lc = art; - out.extend(taken.into_iter().map(|mut g| { - if hidden || locked { - let g = Arc::make_mut(&mut g); - g.visible &= !hidden; - g.locked |= locked; - } - g - })); - } - take_sublayer_guides(c, out, hidden, locked); + take_held_guides(c, inner, &mut deeper, hidden, locked); } + if !own.is_empty() { + let mut own = own.into_iter().peekable(); + for (i, mut c) in std::mem::take(ch).into_iter().enumerate() { + if own.next_if_eq(&i).is_none() { + ch.push(c); + continue; + } + if hidden || locked { + let g = Arc::make_mut(&mut c); + g.visible &= !hidden; + g.locked |= locked; + } + out.push(c); + } + } + out.append(&mut deeper); +} + +/// Move the ruler guides of `n` and those held at any depth by the sublayers and groups among its +/// members to `out`, in order: a container's own guides, then those of its members. A sublayer or +/// group with no guide of its own still gives up those of its members. A guide taken from a hidden +/// or locked sublayer or group, or from one inside such a container, is hidden or locked itself. +/// Each member at every depth is looked at once (`is_guide`), and only containers holding a guide +/// are copied. +fn take_sublayer_guides(n: &mut Node, out: &mut Vec>, is_guide: &impl Fn(&Node) -> bool) { + let held = held_guides(n, is_guide); + take_held_guides(n, held, out, false, false); } /// `n`, a group or layer, as plain art: its Pathfinder effects evaluated, its geometry effects @@ -773,11 +832,15 @@ fn take_sublayer_guides(n: &mut Node, out: &mut Vec>, hidden: bool, lo /// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live /// objects among the members are evaluated with the symbols of `doc` (see [`member_shapes`]), and /// a Pathfinder operation or compound shape takes the symbol instances among its members as their -/// symbols' art from `doc`. +/// symbols' art from `doc`. A Transform effect that makes copies with raster effects listed before +/// it gives each copy those raster effects ([`copied_container`]). pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { if !is_container(n) { return None; } + if let Some(t) = crate::reshape::copied_container_raster_at(n) { + return Some(copied_container(doc, n, t)); + } let pathfinder = has_pathfinder(n); let fx = crate::reshape::geometry_effects(n); let paint = has_own_paint(n); @@ -785,12 +848,15 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { return None; } let mut m = n.clone(); - // A layer's ruler guides take no part: they go back above the evaluated art at the end. - let mut guides = m.children_mut().map(|ch| ch.split_off(Node::guide_run_start(ch))).unwrap_or_default(); - // So do its sublayers' guides, which would otherwise go with the art the effects replace or - // copy: they stay on this layer, hidden and locked as their sublayers were. - if m.is_layer() && (pathfinder || !fx.is_empty()) { - take_sublayer_guides(&mut m, &mut guides, false, false); + // Its ruler guides take no part: they go back above the evaluated art at the end. With effects + // that replace or copy the art, so do its guides among the art and those in its sublayers and + // groups, which would otherwise go with that art: they stay on `n`, in order, hidden and + // locked as their containers were. + let mut guides = vec![]; + if pathfinder || !fx.is_empty() { + take_sublayer_guides(&mut m, &mut guides, &Node::is_ruler_guide); + } else if let Some(ch) = m.children_mut() { + guides = ch.split_off(Node::guide_run_start(ch)); } if pathfinder { let hook = |c: &Node| crate::outline_object(doc, c); @@ -803,7 +869,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. @@ -835,12 +905,73 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { Some(m) } +/// `n`, a group or layer whose own effects split at `t` ([`crate::reshape::copied_container_raster_at`]), +/// as plain art: the effects before the Transform effect at `t` evaluated on its members as one +/// piece ([`evaluate_container`]), with the raster effects among them, and that piece copied by the +/// Transform effect, each copy a group of its own carrying those raster effects moved, turned, +/// reflected and scaled with it ([`crate::reshape::copied_container_art`]). The art keeps the kind, +/// transparency and opacity mask of `n` and the raster effects from `t` on, which paint once around +/// all the copies; a clip group's or clipping layer's copies each clip, and the art itself does not. +/// Its ruler guides, those in its sublayers and groups included, go once above the copies, hidden +/// and locked as their containers were. +fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node { + let mut m = n.clone(); + let mut guides = vec![]; + take_sublayer_guides(&mut m, &mut guides, &Node::is_ruler_guide); + let mut source = m.clone(); + source.appearance.effects = n.appearance.effects.get(..t).unwrap_or_default().to_vec(); + // With no geometry effect before the Transform effect, `evaluate_container` leaves the members' + // own effects live (it only paints the group's own fills and strokes): the members are drawn + // first, so their effects apply before the copies are made. + if crate::reshape::geometry_effects(&source).is_empty() { + source = crate::reshape::outlined_members(doc, &source); + // The members' raster effects follow the group's own Transform effects as well. + let _later = crate::raster::LaterGroups::enter(&n.appearance.effects); + members_as_drawn(doc, &mut source); + } + let mut piece = evaluate_container(doc, &source).unwrap_or_else(|| { + let mut p = source.clone(); + p.appearance.effects = crate::raster::without_geometry(&p.appearance.effects); + p + }); + // The piece is one copy: the transparency, opacity mask and guides stay on the art. + piece.name = None; + piece.visible = true; + piece.locked = false; + (piece.opacity, piece.blend, piece.isolate) = (1.0, Default::default(), false); + piece.extras_mut().mask = None; + // The copies are made about the piece's bounds, measured first: a layer leaves its hidden + // members out of them, and a group does not. + let bounds = piece.geometric_bounds(); + // A layer's copies are groups in it. + if let NodeKind::Layer { children, clip, .. } = &mut piece.kind { + piece.kind = NodeKind::Group { children: std::mem::take(children), clip: *clip }; + } + let (art, effects) = crate::reshape::copied_container_art(doc, n, t, piece, bounds); + let copies = art.children().cloned().unwrap_or_default(); + if let NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } = &mut m.kind { + *children = copies; + *clip = false; + } + m.appearance.items.clear(); + m.appearance.contents_index = None; + m.appearance.effects = effects; + if let Some(ch) = m.children_mut() { + ch.extend(guides); + } + m +} + /// Replace each visible member of `n` with geometry or Pathfinder effects of its own, at every /// depth of its groups and layers, by the art it draws ([`evaluate_container`], /// [`crate::reshape::own_effects_art`]), so the geometry effects of `n` reshape what its members -/// draw. A clip group's clipping path stays as it is, and so do images, symbol instances and the -/// other objects that `own_effects_art` leaves alone, and a group or layer with a 3D effect with -/// everything in it. Calls nested in one another, through the +/// draw. A clip group's clipping path only takes the geometry effects in it into its geometry +/// ([`crate::clip::with_clip_effects_applied_while`]), and the members of a clipping group or +/// compound path count toward the limit below. A group or layer in a clipping path that has +/// geometry effects of its own is walked twice, once for its members' effects and once for its +/// own, and its members count each time. Images, symbol instances and the other objects +/// that `own_effects_art` leaves alone stay as they are, and so does a group or layer with a 3D +/// effect with everything in it. Calls nested in one another, through the /// groups and layers it walks and the art it evaluates (symbol art and Pathfinder members /// included), stop at [`vectorcraft_doc::depth::MAX_DEPTH`] deep, and together they replace at /// most [`crate::SYMBOL_ART_MAX_NODES`] members: past either limit, members stay as they are. @@ -848,6 +979,13 @@ pub(crate) fn members_as_drawn(doc: Option<&Document>, n: &mut Node) { let Some(_frame) = DrawnFrame::enter() else { return }; let clip = usize::from(n.clips()); let Some(ch) = n.children_mut() else { return }; + // The clipping path's own geometry effects shape it before the effects around it do. + if clip == 1 + && let Some(first) = ch.first_mut() + && let Some(applied) = crate::clip::with_clip_effects_applied_while(first, DrawnFrame::take_member) + { + *first = Arc::new(applied); + } for c in ch.iter_mut().skip(clip).filter(|c| c.visible) { if !DrawnFrame::take_member() { return; diff --git a/crates/effects/src/group/tests.rs b/crates/effects/src/group/tests.rs index c6e2a78c73..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(); @@ -747,9 +840,9 @@ fn a_baked_group_that_keeps_its_type_applies_its_members_effects_first() { assert!((w - 250.0).abs() < 1e-6, "{w}"); } -/// A clip group's clipping path keeps its own effects; the clipped members take theirs first. +/// A clip group's clipping path and the clipped members take their own effects first. #[test] -fn a_clipping_path_keeps_its_own_effects_under_a_groups_effects() { +fn a_clipping_path_takes_its_own_effects_before_a_groups_effects() { let mut clip = with_effect(square_at_100(), offset_10()); clip.id = NodeId(2); if let NodeKind::Path { clipping, .. } = &mut clip.kind { @@ -762,7 +855,9 @@ fn a_clipping_path_keeps_its_own_effects_under_a_groups_effects() { let clip_group = art.children().unwrap()[0].clone(); let ch = clip_group.children().unwrap(); assert!(matches!(ch[0].kind, NodeKind::Path { clipping: true, .. }), "{:?}", ch[0].kind); - assert_eq!(crate::reshape::geometry_effects(&ch[0]).len(), 1, "the clipping path keeps its Offset Path"); + assert!(crate::reshape::geometry_effects(&ch[0]).is_empty(), "the clipping path's Offset Path is applied"); + let w = ch[0].geometric_bounds().unwrap().width(); + assert!((w - 60.0).abs() < 0.5, "grown by 10 on each side, then scaled to 50 %: {w}"); assert!(matches!(ch[1].kind, NodeKind::Group { .. }) && crate::reshape::geometry_effects(&ch[1]).is_empty(), "the member is drawn as its art"); } @@ -847,6 +942,53 @@ fn nested_groups_with_effects_count_toward_the_depth_limit() { assert!(deepest.is_some_and(|d| crate::reshape::geometry_effects(&d).len() == 1), "the deepest member keeps its effect"); } +/// The members of a clipping path count toward the member limit: with room for two more members, +/// the third member of a clipping group keeps its own effect as it is. +#[test] +fn clipping_path_members_past_the_member_limit_stay_as_they_are() { + let member = |id: u64| { + let mut m = with_effect(square_at_100(), offset_10()); + m.id = NodeId(id); + Arc::new(m) + }; + let clipping = Node::group(NodeId(20), vec![member(2), member(3), member(4)]); + let mut clipped = Node::new(NodeId(5), NodeKind::Group { children: vec![Arc::new(clipping), Arc::new(square_at_100())], clip: true }); + // An enclosing call that has visited all the members it may but two. + let _outer = DrawnFrame::enter().unwrap(); + DRAWN.with(|d| d.set((1, crate::SYMBOL_ART_MAX_NODES - 2))); + members_as_drawn(None, &mut clipped); + let clipping = clipped.children().unwrap()[0].clone(); + let effects: Vec = clipping.children().unwrap().iter().map(|m| crate::reshape::geometry_effects(m).len()).collect(); + assert_eq!(effects, [0, 0, 1], "the first two members take their Offset Path, the third keeps it"); + let widths: Vec = clipping.children().unwrap().iter().map(|m| m.geometric_bounds().unwrap().width()).collect(); + assert!((widths[0] - 120.0).abs() < 0.5 && (widths[1] - 120.0).abs() < 0.5 && (widths[2] - 100.0).abs() < 0.5, "{widths:?}"); +} + +/// A compound clipping path with an effect of its own takes that effect when the member limit is +/// reached among its paths: with room for one more member, the first path (at 100 to 200) takes +/// its Offset Path, the second (at 300 to 400) goes in as it is, and the compound path's Offset +/// Path reshapes both, to 80 to 220 and 290 to 410. +#[test] +fn a_compound_clipping_path_takes_its_own_effect_at_the_member_limit() { + let member = |id: u64, x: f64| { + let path = Node::path(NodeId(id), shapes::rectangle(Rect::new(x, 100.0, x + 100.0, 200.0)), black()); + Arc::new(with_effect(path, offset_10())) + }; + let kind = NodeKind::Compound { children: vec![member(2, 100.0), member(3, 300.0)], rule: FillRule::NonZero }; + let clipping = with_effect(Node::new(NodeId(20), kind), offset_10()); + let mut clipped = Node::new(NodeId(5), NodeKind::Group { children: vec![Arc::new(clipping), Arc::new(square_at_100())], clip: true }); + // An enclosing call that has visited all the members it may but one. + let _outer = DrawnFrame::enter().unwrap(); + DRAWN.with(|d| d.set((1, crate::SYMBOL_ART_MAX_NODES - 1))); + members_as_drawn(None, &mut clipped); + let clipping = clipped.children().unwrap()[0].clone(); + assert!(crate::reshape::geometry_effects(&clipping).is_empty(), "the compound path's Offset Path is in its geometry"); + let subpaths = clipping.path_data().unwrap().subpaths.clone(); + let bounds: Vec<(f64, f64)> = subpaths.into_iter().map(|sp| PathData::single(sp).bounds().unwrap()).map(|b| (b.x0, b.x1)).collect(); + let near = |(a, b): (f64, f64), (x0, x1): (f64, f64)| (a - x0).abs() < 0.5 && (b - x1).abs() < 0.5; + assert!(bounds.len() == 2 && near(bounds[0], (80.0, 220.0)) && near(bounds[1], (290.0, 410.0)), "{bounds:?}"); +} + /// An image or a symbol instance that a group's Transform effect moves takes the placed gradients /// of its own fills along, as a path does, and each copy takes them as many times as it takes the /// transform. @@ -1757,3 +1899,258 @@ fn a_sublayers_ruler_guide_in_a_hidden_or_locked_group_stays_hidden_or_locked() assert_eq!(guides, [(NodeId(20), !hidden, locked)], "hidden {hidden}, locked {locked}"); } } + +/// Gathering the ruler guides of nested sublayers, and of a sublayer inside nested groups, looks +/// at each member at every depth once, and takes the same guides, in the same order and +/// state, as a layer's effects keep. +#[test] +fn gathering_sublayer_ruler_guides_looks_at_each_member_once() { + use std::cell::Cell; + use vectorcraft_doc::LayerColor; + const CHAIN: u64 = 6; + let guide = |id| Arc::new(Node::new(NodeId(id), NodeKind::RulerGuide { vertical: true, pos: id as f64, artboard: None })); + let layer = |id, children: Vec>| { + let mut l = Node::layer(NodeId(id), "Sub", LayerColor::Preset(1)); + if let Some(ch) = l.children_mut() { + *ch = children; + } + l + }; + // Sublayers nested CHAIN deep, each holding the next before its own art and guide. The second + // is hidden and the fourth locked. + let first_guide = guide(201); + let mut chain = layer(100 + CHAIN, vec![sq(300 + CHAIN, 0.0, Color::BLACK), guide(200 + CHAIN)]); + for depth in (1..CHAIN).rev() { + let own = if depth == 1 { first_guide.clone() } else { guide(200 + depth) }; + chain = layer(100 + depth, vec![Arc::new(chain), sq(300 + depth, 0.0, Color::BLACK), own]); + (chain.visible, chain.locked) = (depth != 2, depth == 4); + } + let second_guide = chain.children().and_then(|c| c[0].children()).map(|c| c[2].clone()).unwrap(); + // A sublayer inside five nested groups, the third of them locked. + let mut groups = layer(450, vec![guide(250), sq(350, 0.0, Color::BLACK)]); + for depth in (1..=5).rev() { + groups = Node::group(NodeId(400 + depth), vec![Arc::new(groups)]); + groups.locked = depth == 3; + } + let free = Arc::new(Node::group(NodeId(500), vec![sq(501, 0.0, Color::BLACK), sq(502, 5.0, Color::BLACK)])); + // A sublayer with no guide, its group holding none either. + let quiet = Node::group(NodeId(601), vec![sq(602, 0.0, Color::BLACK), sq(603, 5.0, Color::BLACK)]); + let quiet = Arc::new(layer(600, vec![Arc::new(quiet)])); + let mut root = layer(10, vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), Arc::new(chain), Arc::new(groups), free.clone(), quiet.clone(), guide(20)]); + fn members(n: &Node) -> usize { + n.children().into_iter().flatten().map(|c| 1 + members(c)).sum() + } + let expected: Vec<_> = (1..=CHAIN).map(|depth| (NodeId(200 + depth), depth < 2, depth >= 4)).chain([(NodeId(250), true, true)]).collect(); + let state = |g: &[Arc]| g.iter().map(|g| (g.id, g.visible, g.locked)).collect::>(); + + let mut m = root.clone(); + let looked = Cell::new(0_usize); + let is_guide = |n: &Node| { + looked.set(looked.get() + 1); + n.is_ruler_guide() + }; + let mut taken = vec![]; + take_sublayer_guides(&mut m, &mut taken, &is_guide); + assert_eq!(looked.get(), members(&root), "each member is looked at once, those of guide-free containers included"); + assert_eq!(taken[0].id, NodeId(20), "the layer's own guide comes first"); + assert_eq!(state(&taken[1..]), expected, "a sublayer's own guides, then its sublayers', each once"); + assert!(Arc::ptr_eq(&taken[1], &first_guide), "a guide with nothing to change is not copied"); + assert!(!Arc::ptr_eq(&taken[2], &second_guide), "a guide made hidden is copied"); + assert!(second_guide.visible, "the guide as it was stays as it was"); + let ch = m.children().unwrap(); + assert_eq!(ch.len(), 5, "the layer's own guide is taken"); + assert!(Arc::ptr_eq(&ch[3], &free), "a member with no sublayer guide is not copied"); + assert!(Arc::ptr_eq(&ch[4], &quiet), "a sublayer with no guide is not copied"); + let ids = |n: &Node| n.children().into_iter().flatten().map(|c| c.id).collect::>(); + assert_eq!(ids(&ch[1]), [NodeId(102), NodeId(301)], "the sublayer's art stays, in order"); + assert_eq!(ids(&root.children().unwrap()[1]), [NodeId(102), NodeId(301), NodeId(201)], "the source keeps its guides"); + + fn found(n: &Node, out: &mut Vec) { + for c in n.children().into_iter().flatten() { + if c.is_ruler_guide() { + out.push(c.id); + } + found(c, out); + } + } + for (effect, params) in [("pathfinder.add", serde_json::json!({})), ("distort.transform", serde_json::json!({"moveH": 30, "copies": 2}))] { + root.appearance.effects = vec![Effect { id: effect.into(), params, visible: true }]; + let art = evaluate_container(None, &root).unwrap(); + let ch = art.children().unwrap(); + let tail = &ch[ch.len() - expected.len() - 1..]; + assert_eq!(tail[0].id, NodeId(20), "{effect}: the layer's own guide comes first"); + assert_eq!(state(&tail[1..]), expected, "{effect}: then the sublayers' guides"); + let mut all = vec![]; + found(&art, &mut all); + assert_eq!(all.len(), expected.len() + 1, "{effect}: each guide once"); + } +} + +/// Where each ruler guide in `n` is, at every depth, with its position, visibility and lock. +fn ruler_guides_in(n: &Node, out: &mut Vec<(NodeId, NodeKind, bool, bool)>) { + for c in n.children().into_iter().flatten() { + if c.is_ruler_guide() { + out.push((c.id, c.kind.clone(), c.visible, c.locked)); + } + ruler_guides_in(c, out); + } +} + +/// A ruler guide in a layer inside a group inside a sublayer that holds no guide of its own, at +/// any depth of that pattern, survives its layer's Pathfinder effect or Transform copies once, last +/// in the layer, hidden or locked when any container on its way was. +#[test] +fn a_ruler_guide_below_a_guide_free_sublayer_and_a_group_survives_its_layers_effects() { + use vectorcraft_doc::LayerColor; + let layer = |id, children: Vec>, (hidden, locked): (bool, bool)| { + let mut l = Node::layer(NodeId(id), "Sub", LayerColor::Preset(1)); + if let Some(ch) = l.children_mut() { + *ch = children; + } + (l.visible, l.locked) = (!hidden, locked); + Arc::new(l) + }; + let group = |id, children: Vec>, (hidden, locked): (bool, bool)| { + let mut g = Node::group(NodeId(id), children); + (g.visible, g.locked) = (!hidden, locked); + Arc::new(g) + }; + let kind = NodeKind::RulerGuide { vertical: false, pos: 7.0, artboard: None }; + let states = [(false, false), (true, false), (false, true)]; + for (effect, params) in [("pathfinder.add", serde_json::json!({})), ("distort.transform", serde_json::json!({"moveH": 30, "copies": 2}))] { + for depth in 1..=3_u64 { + for sub in states { + for grp in states { + for inner in states { + // Layer 10 → sublayer → group → … → layer holding the guide, the pattern + // repeated `depth` times; only the innermost layer holds a guide. + let mut n = layer(900, vec![sq(901, 0.0, Color::BLACK), Arc::new(Node::new(NodeId(20), kind.clone()))], inner); + for d in (0..depth).rev() { + let (s, g) = if d == 0 { (sub, grp) } else { ((false, false), (false, false)) }; + n = group(700 + d, vec![sq(710 + d, 5.0, Color::BLACK), n], g); + n = layer(800 + d, vec![n, sq(810 + d, 2.0, Color::BLACK)], s); + } + let mut root = Node::layer(NodeId(10), "Layer 1", LayerColor::Preset(0)); + if let Some(ch) = root.children_mut() { + *ch = vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), n]; + } + root.appearance.effects.push(Effect { id: effect.into(), params: params.clone(), visible: true }); + let art = evaluate_container(None, &root).unwrap(); + let (hidden, locked) = (sub.0 || grp.0 || inner.0, sub.1 || grp.1 || inner.1); + let mut all = vec![]; + ruler_guides_in(&art, &mut all); + let case = format!("{effect}, depth {depth}, sublayer {sub:?}, group {grp:?}, layer {inner:?}"); + assert_eq!(all, [(NodeId(20), kind.clone(), !hidden, locked)], "{case}: the guide, once, unchanged"); + let last = art.children().and_then(|c| c.last()).unwrap(); + assert_eq!(last.id, NodeId(20), "{case}: last in the layer"); + } + } + } + } + } +} + +/// A ruler guide directly in a group, in a layer or in a group with a Pathfinder effect or +/// Transform copies, survives that effect once, last in the container, hidden or locked as its +/// groups were. So does one among a group's art rather than after it. +#[test] +fn a_ruler_guide_in_a_group_survives_its_containers_effects() { + use vectorcraft_doc::LayerColor; + let kind = NodeKind::RulerGuide { vertical: true, pos: 4.0, artboard: None }; + let guide = || Arc::new(Node::new(NodeId(20), kind.clone())); + for (effect, params) in [("pathfinder.add", serde_json::json!({})), ("distort.transform", serde_json::json!({"moveH": 30, "copies": 2}))] { + for (hidden, locked) in [(false, false), (true, false), (false, true)] { + let mut inner = Node::group(NodeId(12), vec![sq(2, 5.0, Color::BLACK), guide(), sq(3, 8.0, Color::BLACK)]); + (inner.visible, inner.locked) = (!hidden, locked); + let outer = Arc::new(Node::group(NodeId(11), vec![Arc::new(inner)])); + let fx = Effect { id: effect.into(), params: params.clone(), visible: true }; + let mut l = Node::layer(NodeId(10), "Layer 1", LayerColor::Preset(0)); + if let Some(ch) = l.children_mut() { + *ch = vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), outer.clone()]; + } + l.appearance.effects.push(fx.clone()); + let mut g = Node::group(NodeId(13), vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), outer]); + g.appearance.effects.push(fx.clone()); + for (what, n) in [("layer", l), ("group", g)] { + let art = evaluate_container(None, &n).unwrap(); + let mut all = vec![]; + ruler_guides_in(&art, &mut all); + let case = format!("{effect} on a {what}, hidden {hidden}, locked {locked}"); + assert_eq!(all, [(NodeId(20), kind.clone(), !hidden, locked)], "{case}: the guide, once, unchanged"); + assert_eq!(art.children().and_then(|c| c.last()).map(|c| c.id), Some(NodeId(20)), "{case}: last"); + } + } + // A group's guide placed before its art. + let mut g = Node::group(NodeId(13), vec![guide(), sq(1, 0.0, Color::BLACK), sq(2, 5.0, Color::BLACK)]); + g.appearance.effects.push(Effect { id: effect.into(), params: params.clone(), visible: true }); + let art = evaluate_container(None, &g).unwrap(); + let mut all = vec![]; + ruler_guides_in(&art, &mut all); + assert_eq!(all, [(NodeId(20), kind.clone(), true, false)], "{effect}: a group's leading guide, once"); + assert_eq!(art.children().and_then(|c| c.last()).map(|c| c.id), Some(NodeId(20)), "{effect}: moved last"); + } +} + +/// The ruler guides of a layer or group with a Pathfinder effect or Transform copies, one among +/// its art and one after it, go after the evaluated art in the order they were in. +#[test] +fn a_containers_ruler_guides_keep_their_order_through_its_effects() { + use vectorcraft_doc::LayerColor; + let guide = |id| Arc::new(Node::new(NodeId(id), NodeKind::RulerGuide { vertical: false, pos: 3.0, artboard: None })); + for (effect, params) in [("pathfinder.add", serde_json::json!({})), ("distort.transform", serde_json::json!({"moveH": 30, "copies": 2}))] { + let members = || vec![sq(1, 0.0, Color::BLACK), guide(20), sq(2, 5.0, Color::BLACK), guide(21)]; + let fx = Effect { id: effect.into(), params: params.clone(), visible: true }; + let mut l = Node::layer(NodeId(10), "Layer 1", LayerColor::Preset(0)); + if let Some(ch) = l.children_mut() { + *ch = members(); + } + l.appearance.effects.push(fx.clone()); + let mut g = Node::group(NodeId(11), members()); + g.appearance.effects.push(fx); + for (what, n) in [("layer", l), ("group", g)] { + let art = evaluate_container(None, &n).unwrap(); + let mut all = vec![]; + ruler_guides_in(&art, &mut all); + let ids = all.iter().map(|(id, ..)| *id).collect::>(); + assert_eq!(ids, [NodeId(20), NodeId(21)], "{effect} on a {what}: the guides, in order"); + let ch = art.children().unwrap(); + let tail = ch[ch.len() - 2..].iter().map(|c| c.id).collect::>(); + assert_eq!(tail, [NodeId(20), NodeId(21)], "{effect} on a {what}: last, in order"); + } + } +} + +/// A group's own Fill + Offset Path below its contents follows the outline of a clip group among +/// its members, its clipping path, not the clipped art it hides outside that path (#7289). +#[test] +fn a_groups_own_fill_follows_a_clip_groups_clipping_path_not_its_hidden_art() { + let mut clip = square_at_100(); + clip.id = NodeId(2); + if let NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + // The clipped art reaches 100 pt past the clipping path on either side. + let hidden = Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 100.0, 300.0, 200.0)), black()); + let clipped = Node::new(NodeId(5), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(hidden)], clip: true }); + let mut g = Node::group(NodeId(10), vec![Arc::new(clipped.clone())]); + let mut fill = vectorcraft_doc::FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0))); + fill.effects.push(offset_10()); + g.appearance.items = vec![AppearanceItem::Fill(fill)]; + g.appearance.set_contents_at(1); + let near = |a: Rect, b: Rect| (a.x0 - b.x0).abs() < 0.5 && (a.y0 - b.y0).abs() < 0.5 && (a.x1 - b.x1).abs() < 0.5 && (a.y1 - b.y1).abs() < 0.5; + let expected = Rect::new(90.0, 90.0, 210.0, 210.0); + + let art = evaluate_container(None, &g).unwrap(); + let ch = art.children().unwrap(); + assert_eq!(ch.len(), 2, "the fill's art below the clip group"); + assert_eq!(ch[0].id, NodeId(10)); + let b = drawn_bounds(&ch[0]).unwrap(); + assert!(near(b, expected), "the offset fill hugs the clipping path: {b:?}"); + + // The clip group itself with that fill: the same outline. + let mut own = clipped; + own.appearance = g.appearance.clone(); + assert_eq!(member_shapes(None, &own).len(), 1); + let b = member_shapes(None, &own)[0].0.bounds().unwrap(); + assert!(near(b, Rect::new(100.0, 100.0, 200.0, 200.0)), "the clipping path's region: {b:?}"); +} diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index c18a31d842..271ce1c162 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -68,8 +68,11 @@ pub use adjust::{ ADJUSTMENTS, CHANNELS, ColorMap, ImageHook, adjust, adjust_in_document, color_map, curve_at, curve_points, has_adjustment, is_adjustment, is_channel, }; -pub use bake::{StrokeArt, bake_appearance, bake_document, bake_type_appearance, expand_art, expand_leaf, fresh_ids, needs_bake}; -pub use clip::{WarpSeams, clip_outline, knockout_silhouette, warp_pieces_translucent}; +pub use bake::{ + StrokeArt, WrittenLayers, bake_appearance, bake_document, bake_document_placing_symbols, bake_type_appearance, expand_art, expand_leaf, + fresh_ids, needs_bake, +}; +pub use clip::{WarpSeams, clip_outline, knockout_silhouette, reshaped_clip_outline, warp_pieces_translucent}; pub use group::{ OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder, is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, shape_art, @@ -78,26 +81,30 @@ pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_par pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner}; pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks}; pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace}; -pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, without_geometry}; +pub use raster::{ + RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps, staged_effects, + 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, outline_art, outline_text, - 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, }; pub use solids::{ - CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, ROTATE, ROTATE_SURFACES, - ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options, graphic_bounds, - graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, missing_symbol, - names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, solid_art, solid_art_in, takes_graphics, three_d_meshes, - three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid, validate_solid_in, - validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options, with_graphic, + CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, RENDER, RENDER_MODES, ROTATE, + ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options, + graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, missing_symbol, + names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, renders_wireframe, solid_art, solid_art_in, takes_graphics, + three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid, + validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options, + with_graphic, }; 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 8592776a95..99bd568ee9 100644 --- a/crates/effects/src/lighting.rs +++ b/crates/effects/src/lighting.rs @@ -136,8 +136,156 @@ pub(crate) fn facet_art( composed_art(id, path, paint, Ramp::Rgb(light), seam) } -/// Composite smooth solid-fill facets with one clip and three channel groups per surface. -/// Black channel backdrops keep shared edges opaque before the final coverage is applied. +/// The width of the seam stroke of a facet's underlay: a round stroke that reaches 1 pt past each +/// edge, over the pixels that the antialiased edges of two neighboring facets each cover only in +/// part at 1:1. A clip to the surface's outline removes what it paints past the surface. +pub(crate) const UNDERLAY_SEAM: f64 = 2.0; + +/// The area facet `path` and its round seam stroke `seam` wide paint together: the stroke's outer +/// contours and the facet, all wound one way with a positive area. The stroke's inner contours, +/// wound the other way, are left out: the facet covers them, and contours that cancel each other +/// leave partial coverage where a union of footprints meets at a pixel. +pub(crate) fn footprint(path: &vectorcraft_geom::BezPath, seam: f64) -> vectorcraft_geom::BezPath { + use kurbo::{PathEl, Shape}; + let stroke = kurbo::stroke(path.iter(), &kurbo::Stroke::new(seam).with_join(kurbo::Join::Round), &kurbo::StrokeOpts::default(), 0.05); + let sign = if stroke.area() < 0.0 { -1.0 } else { 1.0 }; + let mut footprint = vectorcraft_geom::BezPath::new(); + let mut contour = vectorcraft_geom::BezPath::new(); + for el in stroke.elements().iter().chain(std::iter::once(&PathEl::MoveTo(kurbo::Point::ZERO))) { + if matches!(el, PathEl::MoveTo(_)) && !contour.elements().is_empty() { + if contour.area() * sign >= 0.0 { + footprint.extend(contour.iter()); + } + contour = vectorcraft_geom::BezPath::new(); + } + contour.push(*el); + } + let mut boundary = path.clone(); + if boundary.area() * sign < 0.0 { + boundary = boundary.reverse_subpaths(); + } + footprint.extend(boundary.iter()); + 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 +/// uncovered with the neighbors' own colors, so the background does not show through. `None` unless +/// 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(); + let mut underlay = Vec::with_capacity(faces.len()); + for face in faces { + if face.extras().mask.is_some() { + return None; + } + match &face.kind { + NodeKind::Path { clipping: false, .. } => { + let path = face.path_data()?.to_bezpath(); + let mut seam = None; + let mut grown = (**face).clone(); + for item in &mut grown.appearance.items { + if let AppearanceItem::Stroke(s) = item { + seam = Some(seam.map_or(s.width, |w: f64| w.max(s.width))); + s.width = UNDERLAY_SEAM; + } + } + outline.extend(footprint(&path, seam?).iter()); + underlay.push(Arc::new(grown)); + } + NodeKind::Group { children, clip: true } if children.len() == 2 => { + let clip = children.first()?.path_data()?.to_bezpath(); + let wider = Node::path(id, vectorcraft_geom::PathData::from_bezpath(&footprint(&clip, UNDERLAY_SEAM)), Appearance::default()); + let colors = children.get(1)?.clone(); + outline.extend(clip.iter()); + underlay.push(Arc::new(Node::new(id, NodeKind::Group { children: vec![Arc::new(wider), colors], clip: true }))); + } + _ => return None, + } + } + 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. 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; @@ -161,25 +309,53 @@ 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]; if let Some(value) = color.get_mut(channel) { *value = 1.0; } + let paints: Vec = facets + .iter() + .map(|face| { + if let Some(ramp) = face.rgb_gradient { + smooth_paint(vectorcraft_three_d::LightGradient { diffuse: ramp.channels[channel], ambient: 0.0, color }, Color::WHITE) + } else { + Paint::solid(shade(Color::WHITE, color.map(|c| c * face.illumination[channel]))) + } + }) + .collect(); + let draw = |seam: fn(&vectorcraft_three_d::Facet) -> f64| -> Vec> { + facets + .iter() + .zip(&paints) + .map(|(face, paint)| { + let edge = seam_stroke(paint.clone(), seam(face)); + Arc::new(Node::path( + id, + face.path(), + Appearance { + items: vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(edge)], + ..Default::default() + }, + )) + }) + .collect() + }; let mut children = vec![Arc::new(cover(Paint::solid(Color::BLACK)))]; - children.extend(facets.iter().map(|face| { - let paint = if let Some(ramp) = face.rgb_gradient { - smooth_paint(vectorcraft_three_d::LightGradient { diffuse: ramp.channels[channel], ambient: 0.0, color }, Color::WHITE) - } else { - Paint::solid(shade(Color::WHITE, color.map(|c| c * face.illumination[channel]))) + children.extend(draw(|_| UNDERLAY_SEAM)); + 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() + } }; - let edge = seam_stroke(paint.clone(), (face.thickness() / 2.0).clamp(0.05, 0.75)); - Arc::new(Node::path( - id, - face.path(), - Appearance { items: vec![AppearanceItem::Fill(FillLayer::new(paint)), AppearanceItem::Stroke(edge)], ..Default::default() }, - )) + Arc::new(Node::path(id, path, Appearance { items, ..Default::default() })) })); let mut group = Node::group(id, children); group.isolate = true; @@ -227,25 +403,42 @@ 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 kurbo::Shape; use std::sync::Arc; use vectorcraft_doc::color::BlendMode; use vectorcraft_doc::{Appearance, Node, NodeKind, OpacityMask}; use vectorcraft_geom::{Rect, shapes}; - let (base, mask) = opaque_paint(paint); - // Clip once to the union of this single-contour face and its round seam stroke. - // Align their winding so the nonzero fill adds coverage instead of cancelling it. - let mut boundary = path.to_bezpath(); - let mut footprint = kurbo::stroke(boundary.iter(), &kurbo::Stroke::new(seam).with_join(kurbo::Join::Round), &kurbo::StrokeOpts::default(), 0.05); - if boundary.area() * footprint.area() < 0.0 { - boundary = boundary.reverse_subpaths(); + // An unplaced gradient (and a freeform gradient without points) stays fitted to the face's + // bounds grown by 1 pt, not to the larger cover below. + let mut paint = paint.clone(); + if let Paint::Gradient(g) = &mut paint { + g.pin(path.bounds().unwrap_or(Rect::ZERO).inflate(1.0, 1.0)); } - footprint.extend(boundary.iter()); - let clip = Node::path(id, vectorcraft_geom::PathData::from_bezpath(&footprint), Appearance::default()); + let (base, mask) = opaque_paint(&paint); + // Clip once to the union of this single-contour face and its round seam stroke. + let clip = Node::path(id, vectorcraft_geom::PathData::from_bezpath(&footprint(&path.to_bezpath(), seam)), Appearance::default()); // Opaque rectangles cover the complete seam stroke, without separately antialiasing - // either ramp. Opaque sources need only vector clipping, not full-frame opacity masks. - let bounds = path.bounds().unwrap_or(Rect::ZERO).inflate(1.0, 1.0); + // either ramp. Opaque sources need only vector clipping, not full-frame opacity masks. They + // reach at least half a point past the seam stroke grown for an underlay ([`sealed`]), so + // their own edges stay outside either clip. + let margin = seam.max(1.0) + UNDERLAY_SEAM / 2.0; + let bounds = path.bounds().unwrap_or(Rect::ZERO).inflate(margin, margin); let cover = |paint| Node::path(id, shapes::rectangle(bounds), Appearance::basic(paint, Paint::None, 0.0)); let mut illumination = match light { Ramp::Single(light) => cover(smooth_paint(light, Color::WHITE)), @@ -380,4 +573,91 @@ mod tests { assert_eq!(point.color.to_rgb(), [1.0, 0.25, 0.25]); assert_eq!(shaded.swatch, None, "a changed freeform point detaches the gradient swatch"); } + + /// Under colored light, a face's unplaced source gradient is fitted to the face's bounds grown by + /// 1 pt, whatever the size of the cover rectangle that draws it; a placed one keeps its placement. + #[test] + fn composed_faces_fit_unplaced_gradients_to_the_face_not_the_cover() { + use vectorcraft_doc::NodeKind; + use vectorcraft_geom::{Rect, shapes}; + use vectorcraft_three_d::{RgbGradient, ShadeGradient}; + let face = shapes::rectangle(Rect::new(10.0, 20.0, 50.0, 40.0)); + let ramp = |b| ShadeGradient { start: Point::new(10.0, 20.0), end: Point::new(50.0, 20.0), brightness: [b, 1.0] }; + let light = RgbGradient { channels: [ramp(0.2), ramp(0.5), ramp(0.8)] }; + let stops = vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, Color::BLACK)]; + let unplaced = GradientPaint { gradient: Gradient::new(GradientKind::Linear, stops), geom: None, angle: 0.0, swatch: None, freeform: None }; + let placed = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(80.0, 0.0), aspect: 1.0, focal: None }; + let fitted = unplaced.resolve(Rect::new(9.0, 19.0, 51.0, 41.0)); + for (geom, expected) in [(None, fitted), (Some(placed), placed)] { + let paint = Paint::Gradient(Box::new(GradientPaint { geom, ..unplaced.clone() })); + for seam in [0.05, 0.75] { + let art = facet_art(vectorcraft_doc::NodeId(1), &face, &paint, light, seam); + let NodeKind::Group { children, clip: true } = &art.kind else { panic!("a clipped composite") }; + let base = &children[1].children().unwrap()[0]; + let Paint::Gradient(g) = base.appearance.items[0].paint() else { panic!("the source gradient") }; + assert_eq!(g.geom, Some(expected), "seam {seam}"); + } + } + } + + /// 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 89eb541b19..f6c33079c0 100644 --- a/crates/effects/src/pixel.rs +++ b/crates/effects/src/pixel.rs @@ -29,8 +29,10 @@ mod sketch_ink; mod texture; mod video; +use std::f64::consts::{PI, TAU}; + use serde_json::Value; -use vectorcraft_geom::{Affine, Point, Rect}; +use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use crate::util::{flag, num, text}; @@ -155,12 +157,14 @@ pub enum PixelFx { /// `texture_coverage` (0..40) says. Underpainting { brush_size: f64, texture_coverage: f64, texture: Texture, scaling: f64, relief: f64, light: Light, invert: bool }, /// Artistic › Rough Pastels: diagonal pastel strokes `length` (0..40) long, bristle detail - /// (1..20), then a [`Texture`] surface scaled by `scaling` (0.5..2), in relief as strong as - /// `relief` (0..50) and lit from `light`; `invert` turns the surface's heights over. + /// (1..20), then a [`Texture`] surface (a loaded one included) scaled by `scaling` (0.5..2), in + /// relief as strong as `relief` (0..50) and lit from `light`; `invert` turns the surface's + /// heights over. RoughPastels { length: f64, detail: f64, texture: Texture, scaling: f64, relief: f64, light: Light, invert: bool }, - /// Blur › Radial Blur around the object's centre: along arcs (spin, an arc of `amount`°) or - /// along rays (zoom, the content scaled by up to about ±`amount`/2 %), averaging 2^`passes` samples. - RadialBlur { amount: f64, zoom: bool, passes: u32 }, + /// Blur › Radial Blur around its Blur Center, `center` (0..1 across and down the object's + /// bounds; (0.5, 0.5) the object's centre): along arcs (spin, an arc of `amount`°) or along + /// rays (zoom, the content scaled by up to about ±`amount`/2 %), averaging 2^`passes` samples. + RadialBlur { amount: f64, zoom: bool, passes: u32, center: [f64; 2] }, /// Blur › Smart Blur (Normal mode): each pixel averaged with the neighbours within `radius` /// whose colour differs from its own by no more than `threshold` levels, over a grid of /// `samples` × `samples` neighbours at most. @@ -314,9 +318,12 @@ pub struct PixelSpace { pub to_doc: Affine, /// The size of a pixel in document units. pub px: f64, - /// The object's centre (document coordinates): where Radial Blur blurs around, and where the - /// Pixelate filters' patterns are anchored (so they move with the object). + /// The object's centre (document coordinates): where Radial Blur blurs around by default, and + /// where the Pixelate filters' patterns are anchored (so they move with the object). pub center: Point, + /// The width and height of the object's bounds (document units), centred on `center`: Radial + /// Blur's Blur Center lies at a share of them. + pub size: Vec2, /// What the colour channels hold. pub channels: Channels, /// The height of a line of the document's raster grid (document units: 72 / Document Raster @@ -327,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| { @@ -381,7 +391,7 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option { "artistic.roughPastels" => PixelFx::RoughPastels { length: num(p, "strokeLength", 6.0).clamp(0.0, 40.0), detail: num(p, "strokeDetail", 10.0).clamp(1.0, 20.0), - texture: Texture::parse(text(p, "texture", "canvas")), + texture: Texture::parse_with(text(p, "texture", "canvas"), p.get(TEXTURE_IMAGE).and_then(Value::as_str)), scaling: num(p, "scaling", 100.0).clamp(50.0, 200.0) / 100.0, relief: num(p, "relief", 4.0).clamp(0.0, 50.0), light: Light::parse(text(p, "lightDirection", "top")), @@ -421,6 +431,7 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option { amount: num(p, "amount", 10.0).clamp(1.0, 100.0), zoom: text(p, "method", "spin").eq_ignore_ascii_case("zoom"), passes: quality([("draft", 4), ("good", 6), ("best", 8)], 6), + center: [num(p, "centerX", 0.5).clamp(0.0, 1.0), num(p, "centerY", 0.5).clamp(0.0, 1.0)], }, "blur.smart" => PixelFx::SmartBlur { radius: num(p, "radius", 3.0).clamp(0.1, 100.0), @@ -559,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")) }, @@ -608,13 +618,13 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option { impl PixelFx { /// How far beyond `bounds` (the content's, document units) the effect can paint. pub fn outset(&self, bounds: Rect) -> f64 { - // From the centre to the farthest corner, and to the nearest side. - let far = 0.5 * bounds.width().hypot(bounds.height()); - let near = 0.5 * bounds.width().min(bounds.height()); match *self { - // A rotated corner reaches the circle through the corners. - PixelFx::RadialBlur { zoom: false, .. } => (far - near).max(0.0), - PixelFx::RadialBlur { amount, zoom: true, .. } => far * (blur::zoom_extent(amount).exp() - 1.0), + // A rotated corner reaches the circle about the Blur Center through the farthest corner. + PixelFx::RadialBlur { zoom: false, center, .. } => { + let (far, near) = blur::center_reach(bounds, center); + (far - near).max(0.0) + } + PixelFx::RadialBlur { amount, zoom: true, center, .. } => blur::center_reach(bounds, center).0 * (blur::zoom_extent(amount).exp() - 1.0), PixelFx::SmartBlur { radius, .. } => radius, PixelFx::AccentedEdges { .. } => 0.0, // Strokes reach out of the object as far as they reach into it. @@ -786,7 +796,7 @@ impl PixelFx { PixelFx::RoughPastels { length, detail, ref texture, scaling, relief, light, invert } => { artistic::rough_pastels(px, w, h, space, length, detail, texture, scaling, relief, light, invert) } - PixelFx::RadialBlur { amount, zoom, passes } => blur::radial(px, w, h, space, amount, zoom, passes), + PixelFx::RadialBlur { amount, zoom, passes, center } => blur::radial(px, w, h, space, amount, zoom, passes, center), PixelFx::SmartBlur { radius, threshold, samples, mode: SmartBlurMode::Normal } => { blur::smart(px, w, h, to_px(radius), threshold, samples) } @@ -849,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/blur.rs b/crates/effects/src/pixel/blur.rs index 0a061571ba..877061922d 100644 --- a/crates/effects/src/pixel/blur.rs +++ b/crates/effects/src/pixel/blur.rs @@ -1,6 +1,6 @@ //! Blur › Radial Blur and Smart Blur (Normal, Edge Only and Overlay Edge). -use vectorcraft_geom::{Affine, Point, Vec2}; +use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use super::{PixelSpace, Px16, box_blur, pick, to8, to16}; @@ -29,13 +29,31 @@ fn bilinear(buf: &[Px16], w: usize, h: usize, x: f64, y: f64) -> [f32; 4] { std::array::from_fn(|i| a[i] * wa + b[i] * wb + c[i] * wc + d[i] * wd) } -/// Radial Blur: the average of the content turned (spin) or scaled (zoom) about the centre over -/// evenly spaced steps spanning `amount`. Each pass averages the previous result with itself -/// turned both ways by half the last step, so `passes` passes average 2^`passes` samples at two -/// lookups a pixel each. -pub(super) fn radial(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, amount: f64, zoom: bool, passes: u32) { +/// How far Radial Blur's Blur Center `center` (0..1 across and down `bounds`) lies from the +/// farthest corner of `bounds`, and from its nearest side. +pub(super) fn center_reach(bounds: Rect, center: [f64; 2]) -> (f64, f64) { + // The share of the width (height) on the far side of the center, doubled: 1 at the middle. + let far = |f: f64| 1.0 + (2.0 * f - 1.0).abs(); + let (w, h) = (bounds.width(), bounds.height()); + let near = ((2.0 - far(center[0])) * w).min((2.0 - far(center[1])) * h); + (0.5 * (far(center[0]) * w).hypot(far(center[1]) * h), 0.5 * near) +} + +/// Where Radial Blur's Blur Center `center` (0..1 across and down the object's bounds) lies in the +/// document: the object's centre at (0.5, 0.5). +pub(super) fn blur_center(space: &PixelSpace, center: [f64; 2]) -> Point { + let shift = Vec2::new((center[0] - 0.5) * space.size.x, (center[1] - 0.5) * space.size.y); + if shift.x.is_finite() && shift.y.is_finite() { space.center + shift } else { space.center } +} + +/// Radial Blur: the average of the content turned (spin) or scaled (zoom) about the Blur Center +/// (`center`, [`blur_center`]) over evenly spaced steps spanning `amount`. Each pass averages the +/// previous result with itself turned both ways by half the last step, so `passes` passes average +/// 2^`passes` samples at two lookups a pixel each. +#[allow(clippy::too_many_arguments)] // the effect's four options +pub(super) fn radial(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, amount: f64, zoom: bool, passes: u32, center: [f64; 2]) { // The centre in pixel index coordinates (pixel centres at whole numbers). - let c = space.to_doc.inverse() * space.center - Vec2::new(0.5, 0.5); + let c = space.to_doc.inverse() * blur_center(space, center) - Vec2::new(0.5, 0.5); if !(c.x.is_finite() && c.y.is_finite()) { return; } 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 a1a083f0fe..6dd7942e5e 100644 --- a/crates/effects/src/pixel/tests.rs +++ b/crates/effects/src/pixel/tests.rs @@ -12,6 +12,7 @@ fn space(w: usize, h: usize) -> PixelSpace { to_doc: Affine::IDENTITY, px: 1.0, center: Point::new(w / 2.0, h / 2.0), + size: vectorcraft_geom::Vec2::new(w, h), channels: Channels::Rgb, line: 1.0, extent: 0.5 * w.hypot(h), @@ -479,12 +480,16 @@ fn film_grain_leaves_invalid_coordinate_spaces_alone() { #[test] fn params_take_defaults_and_stay_in_range() { - assert_eq!(fx("blur.radial", json!({})), PixelFx::RadialBlur { amount: 10.0, zoom: false, passes: 6 }); + assert_eq!(fx("blur.radial", json!({})), PixelFx::RadialBlur { amount: 10.0, zoom: false, passes: 6, center: [0.5, 0.5] }); assert_eq!( - fx("blur.radial", json!({"amount": 1e308, "method": "ZOOM", "quality": "best"})), - PixelFx::RadialBlur { amount: 100.0, zoom: true, passes: 8 } + fx("blur.radial", json!({"amount": 1e308, "method": "ZOOM", "quality": "best", "centerX": 0.25, "centerY": 1})), + PixelFx::RadialBlur { amount: 100.0, zoom: true, passes: 8, center: [0.25, 1.0] } + ); + // A saved center outside the bounds (the commands refuse one) draws at the nearest edge. + assert_eq!( + fx("blur.radial", json!({"amount": -5, "quality": "nonsense", "centerX": -3, "centerY": 7})), + PixelFx::RadialBlur { amount: 1.0, zoom: false, passes: 6, center: [0.0, 1.0] } ); - assert_eq!(fx("blur.radial", json!({"amount": -5, "quality": "nonsense"})), PixelFx::RadialBlur { amount: 1.0, zoom: false, passes: 6 }); assert_eq!(fx("blur.smart", json!({})), PixelFx::SmartBlur { radius: 3.0, threshold: 25.0, samples: 7, mode: SmartBlurMode::Normal }); assert_eq!( fx("blur.smart", json!({"radius": "1e999", "threshold": -1, "quality": "low", "blurMode": "EDGEONLY"})), @@ -519,6 +524,11 @@ fn outsets_follow_the_object() { let far = 0.5 * 100f64.hypot(50.0); assert!((spin.outset(b) - (far - 25.0)).abs() < 1e-9); assert!(fx("blur.radial", json!({"method": "zoom", "amount": 100})).outset(b) > 0.4 * far); + // About a corner the spin reaches the circle through the opposite corner, the whole diagonal out. + let corner = fx("blur.radial", json!({"centerX": 0, "centerY": 0})); + assert!((corner.outset(b) - 100f64.hypot(50.0)).abs() < 1e-9, "{}", corner.outset(b)); + let zoom = |center: f64| fx("blur.radial", json!({"method": "zoom", "amount": 100, "centerX": center, "centerY": center})).outset(b); + assert!((zoom(1.0) - 2.0 * zoom(0.5)).abs() < 1e-9, "a zoom about a corner reaches twice as far"); assert_eq!(fx("blur.smart", json!({"radius": 4})).outset(b), 4.0); assert_eq!(fx("blur.smart", json!({"radius": 4})).reach(1.0), Some(4.0)); // The edge modes also read the copy blurred over a wide radius's samples. @@ -633,6 +643,40 @@ fn spin_blur_smears_along_arcs_and_keeps_the_centre() { assert_eq!(at(&z, w, 32, 16)[3], 0, "not across it"); } +/// The Blur Center moves the point the blur turns about: a dot on it stays sharp, a dot on the +/// object's centre then spreads, and the center follows the object when it moves or is scaled. +#[test] +fn radial_blur_turns_about_its_blur_center() { + let (w, h) = (41, 41); + // A dot on pixel (10, 30), whose centre (10.5, 30.5) is the Blur Center below, and one on the + // object's centre. + let src = image(w, h, |x, y| if (x == 10 && y == 30) || (x == 20 && y == 20) { grey(255) } else { [0, 0, 0, 0] }); + let blur = |p: serde_json::Value, s: &PixelSpace, src: &[u8]| { + let mut d = src.to_vec(); + fx("blur.radial", p).apply(&mut d, w, h, s); + d + }; + let off = json!({"amount": 60, "quality": "best", "centerX": 10.5 / 41.0, "centerY": 30.5 / 41.0}); + let d = blur(off.clone(), &space(w, h), &src); + assert!(at(&d, w, 10, 30)[3] > 100, "the dot on the Blur Center barely moves: {:?}", at(&d, w, 10, 30)); + assert!(at(&d, w, 20, 20)[3] < 100, "the dot on the object's centre spreads: {:?}", at(&d, w, 20, 20)); + // The default center is the object's centre, the same as no center at all. + assert_eq!(blur(json!({"amount": 60, "centerX": 0.5, "centerY": 0.5}), &space(w, h), &src), blur(json!({"amount": 60}), &space(w, h), &src)); + // Moved 7 pt right and 3 pt down, the object draws the same pixels. + let moved = + PixelSpace { to_doc: Affine::translate((7.0, 3.0)), center: space(w, h).center + vectorcraft_geom::Vec2::new(7.0, 3.0), ..space(w, h) }; + assert_eq!(blur(off.clone(), &moved, &src), d, "the center moves with the object"); + // Drawn at twice the size (two points a pixel), the center lies on the same pixels. + let big = PixelSpace { + to_doc: Affine::scale(2.0), + px: 2.0, + center: Point::new(41.0, 41.0), + size: vectorcraft_geom::Vec2::new(82.0, 82.0), + ..space(w, h) + }; + assert_eq!(blur(off, &big, &src), d, "the center scales with the object"); +} + #[test] fn smart_blur_smooths_noise_and_keeps_edges() { let (w, h) = (40, 20); @@ -862,6 +906,7 @@ fn lengths_are_document_units() { to_doc: Affine::scale(1.0 / scale as f64), px: 1.0 / scale as f64, center: Point::ZERO, + size: vectorcraft_geom::Vec2::ZERO, channels: Channels::Rgb, line: 1.0, extent: 0.0, @@ -916,7 +961,15 @@ fn linear_light_blur_mixes_light_not_values() { fn pixel_timings() { let (w, h) = (2000, 2000); let src = image(w, h, |x, y| [(x % 256) as u8, (y % 256) as u8, ((x ^ y) % 256) as u8, 255]); - let s = PixelSpace { to_doc: Affine::IDENTITY, px: 1.0, center: Point::new(1000.0, 1000.0), channels: Channels::Rgb, line: 1.0, extent: 0.0 }; + let s = PixelSpace { + to_doc: Affine::IDENTITY, + px: 1.0, + center: Point::new(1000.0, 1000.0), + size: vectorcraft_geom::Vec2::new(2000.0, 2000.0), + channels: Channels::Rgb, + line: 1.0, + extent: 0.0, + }; let cases = [ ("blur.radial", json!({"quality": "draft"})), ("blur.radial", json!({"quality": "good"})), @@ -1494,6 +1547,42 @@ fn texturizer_draws_a_loaded_texture_as_relief() { assert_eq!(fx("texture.texturizer", json!({"texture": "LOADED", "textureImage": "not a texture"})), fx("texture.texturizer", json!({}))); } +/// Rough Pastels draws a loaded texture as its surface, and Scaling, Relief, Light Direction and +/// Invert act on it as on the built-in ones. +#[test] +fn rough_pastels_draws_a_loaded_texture_as_its_surface() { + let w = 64; + let mid = grey(150); + let rings = stored(12, 10, |x, y| { + let v = ((x as f64 - 5.5).hypot(y as f64 - 4.5) * 0.9).sin().abs(); + let g = (v * 255.0).round() as u8; + [g, g, g, 255] + }); + let run = |mut p: serde_json::Value| { + p["strokeLength"] = json!(0); + let mut d = flat(w, mid); + fx("artistic.roughPastels", p).apply(&mut d, w, w, &space(w, w)); + d + }; + let relief = run(json!({"texture": "loaded", "textureImage": rings, "relief": 20})); + assert_ne!(relief, flat(w, mid)); + for (_, builtin) in TEXTURES { + assert_ne!(relief, run(json!({"texture": builtin, "relief": 20})), "{builtin}"); + } + for (key, value) in [("invert", json!(true)), ("scaling", json!(200)), ("lightDirection", json!("bottomRight")), ("relief", json!(5))] { + let mut p = json!({"texture": "loaded", "textureImage": rings, "relief": 20}); + p[key] = value; + assert_ne!(run(p), relief, "{key}"); + } + assert_eq!(run(json!({"texture": "loaded", "textureImage": rings, "relief": 0})), flat(w, mid)); + let parsed = fx("artistic.roughPastels", json!({"texture": "Loaded", "textureImage": rings})); + assert!(matches!(parsed, PixelFx::RoughPastels { texture: Texture::Loaded(_), .. }), "{parsed:?}"); + // Without a stored texture, or with one that isn't, Loaded draws Canvas. + for p in [json!({"texture": "loaded"}), json!({"texture": "loaded", "textureImage": "not a texture"})] { + assert_eq!(fx("artistic.roughPastels", p), fx("artistic.roughPastels", json!({}))); + } +} + /// The Texture filters' patterns lie in document space around the object's centre: the same at /// twice the resolution, and moving with the object. #[test] @@ -1615,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/tests_paint.rs b/crates/effects/src/pixel/tests_paint.rs index e84e587c9a..20fb8d10f2 100644 --- a/crates/effects/src/pixel/tests_paint.rs +++ b/crates/effects/src/pixel/tests_paint.rs @@ -14,6 +14,7 @@ fn space(w: usize, h: usize) -> PixelSpace { to_doc: Affine::IDENTITY, px: 1.0, center: Point::new(w / 2.0, h / 2.0), + size: vectorcraft_geom::Vec2::new(w, h), channels: Channels::Rgb, line: 1.0, extent: 0.5 * w.hypot(h), diff --git a/crates/effects/src/pixel/tests_sketch.rs b/crates/effects/src/pixel/tests_sketch.rs index fd467a23ca..127b79c5f0 100644 --- a/crates/effects/src/pixel/tests_sketch.rs +++ b/crates/effects/src/pixel/tests_sketch.rs @@ -14,6 +14,7 @@ fn space(w: usize, h: usize) -> PixelSpace { to_doc: Affine::IDENTITY, px: 1.0, center: Point::new(w / 2.0, h / 2.0), + size: vectorcraft_geom::Vec2::new(w, h), channels: Channels::Rgb, line: 1.0, extent: 0.5 * w.hypot(h), 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/preview.rs b/crates/effects/src/preview.rs index ad36ab56dc..8d330a606b 100644 --- a/crates/effects/src/preview.rs +++ b/crates/effects/src/preview.rs @@ -1,4 +1,4 @@ -//! Use Preview Bounds: objects measured as they are drawn, with their geometry effects. +//! Use Preview Bounds: objects measured as they are drawn, with geometry and projected 3D effects. //! //! [`drawn_art`] gives an object whose geometry effects change what it draws as plain art. A path //! or compound path is given as its effected geometry, and a fill or stroke with geometry effects @@ -11,12 +11,15 @@ //! ([`expanded_live_group`]), with each of those objects given as its own art. A clip group or //! layer whose clipping path has strokes with geometry effects is given as that path's geometry //! before its effects, which the renderer clips by, and those strokes as drawn. Fills and -//! strokes that paint nothing (hidden, or painted None) are left out. [`bounds_of`], +//! strokes that paint nothing (hidden, or painted None) are left out. Extrude & Bevel, Revolve, +//! Inflate and Rotate are measured by the same projected vector art the renderer draws, with +//! any geometry effects after projection applied to that art; [`drawn_art`], which clicks and +//! marquees use, leaves 3D effects unprojected. [`bounds_of`], //! [`oriented_bounds`] and [`anchor_bounds`] measure the visual bounds of that art, strokes //! included, where [`Document::bounds_of`], [`Document::oriented_bounds`] and //! [`Selection::anchor_bounds`] measure the objects themselves. Raster effects (shadows, glows, //! blurs) are not measured. In one object, the art of at most 4,096 symbol instances is measured -//! with its geometry effects, and the other instances in it are measured without them. +//! with its geometry and 3D effects, and the other instances in it are measured without them. //! [`bounds_of_with`], [`oriented_bounds_with`] and [`anchor_bounds_with`] measure as these do and, //! with [`Measure::glyphs`], take point type by the ink of its glyphs (Measure Type by Glyph Bounds). @@ -31,12 +34,12 @@ use vectorcraft_geom::{Affine, PathData, Rect, Shape, union_opt}; use crate::group::has_own_paint; use crate::reshape::{geometry_effects, leaf_geometry}; use crate::{ - GeomContext, apply_geometry_with, evaluate_container, expanded_live_group, has_geometry, has_item_geometry, has_pathfinder, has_transform_art, - needs_outline, outline_art, paints, reshape, + GeomContext, apply_geometry_with, evaluate_container, expanded_live_group, has_geometry, has_item_geometry, has_pathfinder, has_revolve, + has_solid, has_transform_art, needs_outline, outline_art, paints, reshape, revolve_art_in, solid_art_in, }; -/// Most symbol instances in one object whose art [`Drawn`] measures with its geometry effects: -/// past it, the other instances in the object are measured without geometry effects. +/// Most symbol instances in one object whose art [`Drawn`] measures with geometry or 3D effects: +/// past it, the other instances in the object are measured without those effects. const MAX_INSTANCES: usize = 4096; /// The bounds of `ids`: with `preview`, their visual bounds as drawn ([`visual_bounds`]), else @@ -191,8 +194,8 @@ pub fn laid_out_ink(layout: &vectorcraft_text::TextLayout, t: &vectorcraft_doc:: .fold(layout.ink_bounds(), |acc, (_, bar)| union_opt(acc, Some(bar.bounding_box()))) } -/// The visual bounds of `n` as drawn: those of its [`drawn_art`], else -/// [`Node::visual_bounds_with`]. +/// The visual bounds of `n` as drawn: those of its [`drawn_art`] with its 3D effects projected, +/// else [`Node::visual_bounds_with`]. pub fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { Drawn::new(symbols).visual_bounds(n) } @@ -204,31 +207,45 @@ pub fn bounds_in(symbols: &SymbolBoxes, n: &Node, a: Affine) -> Option { } /// `n` as plain art with the geometry effects in it applied, at every depth, symbol instances -/// measured by `symbols`. Raster effects stay on the art. A group, layer or intertwine without a -/// clip is rebuilt with the drawn art of each member that has one. A clip group or layer becomes a -/// group of its clipping path without strokes and the drawn art of the path's strokes, when they -/// have one. `None` when no geometry effect in `n` changes what it draws. +/// measured by `symbols`, for clicks and marquees. Raster effects stay on the art. A group, layer or +/// intertwine without a clip is rebuilt with the drawn art of each member that has one. A clip group +/// or layer becomes a group of its clipping path without strokes and the drawn art of the path's +/// strokes, when they have one. 3D effects stay on the art unprojected, so each object in it keeps +/// its own id. `None` when no geometry effect in `n` changes what it draws. pub fn drawn_art(symbols: &SymbolBoxes, n: &Node) -> Option { - Drawn::new(symbols).drawn_art(n) + Drawn::without_3d(symbols).drawn_art(n) } -/// Whether [`drawn_art`] gives `n` art of its own, or would give one to an object in it. A symbol -/// instance in `n` counts when its symbol's art has a geometry effect. +/// Whether `n` is measured by art of its own with Use Preview Bounds, or an object in it is: a +/// geometry or 3D effect in it changes what it draws. A symbol instance in `n` counts when its +/// symbol's art has geometry or 3D effects. pub fn draws_geometry(symbols: &SymbolBoxes, n: &Node) -> bool { Drawn::new(symbols).draws_geometry(n) } -/// One measurement: whether the art of each symbol checked so far draws geometry, by symbol name, -/// and how many more instances' art it measures with its geometry effects in the current object ([`MAX_INSTANCES`]). +/// One measurement: whether each symbol checked so far draws geometry or 3D art, by symbol name, +/// and how many more instances it measures with those effects in the current object ([`MAX_INSTANCES`]). +/// With `three_d` false, 3D effects are left on the art unprojected ([`drawn_art`]). struct Drawn<'s, 'd> { symbols: &'s SymbolBoxes<'d>, draws: RefCell>, left: Cell, + three_d: bool, } impl<'s, 'd> Drawn<'s, 'd> { fn new(symbols: &'s SymbolBoxes<'d>) -> Self { - Drawn { symbols, draws: RefCell::default(), left: Cell::new(MAX_INSTANCES) } + Drawn { symbols, draws: RefCell::default(), left: Cell::new(MAX_INSTANCES), three_d: true } + } + + /// A measurement that projects no 3D effect, for clicks and marquees ([`drawn_art`]). + fn without_3d(symbols: &'s SymbolBoxes<'d>) -> Self { + Drawn { three_d: false, ..Self::new(symbols) } + } + + /// Whether `n` has a 3D effect of its own that this measurement projects. + fn projects(&self, n: &Node) -> bool { + self.three_d && (has_revolve(n) || has_solid(n)) } /// Sets the count of instances left back to [`MAX_INSTANCES`], for the next object. @@ -273,6 +290,7 @@ impl<'s, 'd> Drawn<'s, 'd> { let mut found = false; n.walk(&mut |c| { found = found + || self.projects(c) || match &c.kind { NodeKind::SymbolInstance { symbol, .. } => !geometry_effects(c).is_empty() || self.symbol_draws(symbol), _ => reshapes(c), @@ -292,14 +310,29 @@ impl<'s, 'd> Drawn<'s, 'd> { d } - /// The art the geometry effects of `n` itself give it, or that a symbol instance gets from the - /// geometry effects in its symbol's art. A group or layer with fills or strokes of its own that + /// The art the geometry or 3D effects of `n` itself give it, or that a symbol instance gets from + /// those effects in its symbol's art, with the instance's appearance overrides applied. + /// A group or layer with fills or strokes of its own that /// paint, around members with geometry effects, is evaluated too: its fills and strokes paint /// the members' geometry before their effects. A blend, envelope or repeat whose objects have /// geometry effects is evaluated as the renderer evaluates it ([`expanded_live_group`]), and /// the objects in its evaluated art keep their geometry effects. `None` when it has none, and /// for a symbol instance past [`MAX_INSTANCES`]. fn own_art(&self, n: &Node) -> Option { + let doc = Some(self.symbols.document()); + // A symbol instance with a 3D effect of its own counts toward MAX_INSTANCES before its art is built. + let counted = matches!(n.kind, NodeKind::SymbolInstance { .. }) && self.projects(n); + if counted { + let left = self.left.get().checked_sub(1)?; + self.left.set(left); + } + if self.three_d + && let Some(art) = revolve_art_in(doc, n).or_else(|| solid_art_in(doc, n)) + { + // The builders retain later geometry on the projected group. Measure it after that + // geometry too; item-level effects are handled by the ordinary member traversal. + return Some(self.own_art(&art).unwrap_or(art)); + } let inner = || n.children().is_some_and(|ch| ch.iter().any(|c| self.draws_geometry(c))); let painted = || has_own_paint(n) && inner(); match &n.kind { @@ -312,9 +345,14 @@ impl<'s, 'd> Drawn<'s, 'd> { if geometry_effects(n).is_empty() && !self.symbol_draws(symbol) { return None; } - let left = self.left.get().checked_sub(1)?; - self.left.set(left); + if !counted { + let left = self.left.get().checked_sub(1)?; + self.left.set(left); + } let art = self.symbols.measure_art(symbol, Arc::clone)?; + // Paint overrides can remove a projected surface or change its stroke outline. + let art = + if n.extras().symbol_overrides.is_empty() { art } else { Arc::new(vectorcraft_doc::symbol_overrides::dynamic_art(&art, n)) }; // An instance in perspective is projected by `reshape`. let doc = Some(self.symbols.document()); reshape(doc, n, Some(&*art)).or_else(|| outline_art(doc, n, Some(&*art))) diff --git a/crates/effects/src/raster.rs b/crates/effects/src/raster.rs index b59d61beb2..6948d0f977 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; } } @@ -606,18 +606,138 @@ fn transform_step(e: &Effect) -> Option { (copies == 0 && !flag(&p, "random", false)).then(|| map.with_translation(Vec2::ZERO)) } +/// The Transform effects of `effects` that move the image of its last visible Rasterize effect +/// instead of the art it is made from: the indices of the visible Transform effects listed after +/// it that move or copy the art, when from the first visible Transform effect after it on every +/// visible effect is a Transform effect that does not move at random, and at most one of them makes +/// copies. Effects apply in the order they are listed, so the image is made of the art before those +/// Transform effects and moves with them, its pixel grid and room around the art included; each copy +/// carries the same image ([`stage_maps`]). `None` when there is no such Transform effect, or the +/// effects after the Rasterize effect hold anything else from there on. +pub fn rasterize_stage(effects: &[Effect]) -> Option> { + let r = effects.iter().rposition(|e| e.visible && e.id == RASTERIZE)?; + let first = r + 1 + effects.get(r + 1..)?.iter().position(|e| e.visible && e.id == "distort.transform")?; + let mut at = vec![]; + let mut copying = false; + for (i, e) in effects.iter().enumerate().skip(first).filter(|(_, e)| e.visible) { + if e.id != "distort.transform" { + return None; + } + let p = merged_params(&e.id, &e.params); + if !flag(&p, "objects", true) { + continue; + } + if flag(&p, "random", false) { + return None; + } + let (map, copies) = crate::distort::transform_map(Rect::ZERO, &p, 0); + if copies > 0 { + if copying { + return None; + } + copying = true; + } + if copies > 0 || map != Affine::IDENTITY { + at.push(i); + } + } + (!at.is_empty()).then_some(at) +} + +/// `effects` with the Transform effects at `at` hidden ([`rasterize_stage`]): what the image of +/// the Rasterize effect before them is made from. +pub fn staged_effects(effects: &[Effect], at: &[usize]) -> Vec { + let mut out = effects.to_vec(); + for &i in at { + if let Some(e) = out.get_mut(i) { + e.visible = false; + } + } + out +} + +/// The maps the Transform effects at `at` of `effects` ([`rasterize_stage`]) place the Rasterize +/// image by, for `staged`, the geometry the effects before them make: each one's map about its +/// reference point on the bounds of the geometry it takes, as the geometry pass applies it, the +/// last one outermost. A Transform effect with copies places the image once more for each copy +/// the geometry pass makes, copy `k` through its map `k` times. The maps come in the order the +/// images paint, the lowest first: the last copy lowest and the original on top, as copied objects +/// stack. `None` when `staged` is empty or a map is not a number. +pub fn stage_maps(effects: &[Effect], at: &[usize], staged: &vectorcraft_geom::PathData) -> Option> { + let mut cur = staged.clone(); + let mut b = staged.bounds()?; + // The original's map first, then each copy's. + let mut maps = vec![Affine::IDENTITY]; + for &i in at { + let e = effects.get(i)?; + let p = merged_params(&e.id, &e.params); + let (m, copies) = crate::distort::transform_map(b, &p, 0); + if copies == 0 { + maps.iter_mut().for_each(|x| *x = m * *x); + cur = cur.transformed(m); + } else { + // As many copies as the geometry pass makes: it stops early past its limits. + let next = crate::distort::transform(&cur, b, &p, 0); + let made = (next.anchor_count() / cur.anchor_count().max(1)).saturating_sub(1); + let placed = maps.clone(); + let mut xf = Affine::IDENTITY; + for _ in 0..made { + xf = m * xf; + maps.extend(placed.iter().map(|x| xf * *x)); + } + cur = next; + } + b = cur.bounds().unwrap_or(b); + } + maps.reverse(); + maps.iter().all(|m| m.is_finite()).then_some(maps) +} + /// Does raster effect `id` follow the Transform effects listed after it ([`followed`])? An SVG /// filter does not, and neither does Rasterize, whose image keeps its own pixel grid and room -/// around the art. +/// around the art: the image moves with those Transform effects instead ([`rasterize_stage`]). 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; } @@ -625,15 +745,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 83ff68431f..50ecc6b549 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -107,11 +107,209 @@ 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`]), 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) + has_gradient_copies(n) + || has_layered_copies(n) + || has_transform_options(n) + || has_painted_effects(n) + || (matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && copied_raster_at(n).is_some()) + || has_copied_row_raster(n) +} + +/// Is `n` a path or compound path with a fill or stroke that paints and whose raster effects are +/// carried by copies: one whose own effects list a Transform effect that makes copies after a +/// raster effect that follows it ([`copied_row_raster_at`]), or one with a raster effect that +/// follows a Transform effect ([`crate::raster::follows`]) on a path whose own Transform effect makes +/// copies ([`has_transform_copies`])? Each copy is then an object of its own carrying that fill's or +/// stroke's raster effects, moved, turned, reflected and scaled with it ([`transform_item_leaf`], +/// [`follow_copies`]). +pub fn has_copied_row_raster(n: &Node) -> bool { + if !matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }) { + return false; + } + // Checked first: this runs for every object drawn. + if !n.appearance.items.iter().any(follows_row_raster) { + return false; + } + n.appearance.items.iter().any(|i| crate::paints(i) && copied_row_raster_at(i.effects()).is_some()) || has_transform_copies(n) +} + +/// Does `item` paint and carry a visible raster effect that follows a Transform effect +/// ([`crate::raster::follows`])? +fn follows_row_raster(item: &AppearanceItem) -> bool { + crate::paints(item) && item.effects().iter().any(|e| e.visible && crate::raster::follows(&e.id)) +} + +/// Where a fill's or stroke's own effects `fx` split so that each copy of a Transform effect carries +/// the raster effects listed before it: the index of the first visible Transform effect that makes +/// copies (an earlier one that makes copies included) for which a visible raster effect that +/// follows a Transform effect ([`crate::raster::follows`]) is listed before it, every other visible +/// effect before it is a geometry effect or such a raster effect, and no Transform effect before it +/// that makes copies or moves at random holds those raster effects back +/// ([`crate::raster::held_back`]). `None` otherwise, and when a raster effect is listed after it +/// and before a later Transform effect that makes copies or moves at random, which would apply to +/// the art that raster effect paints. +fn copied_row_raster_at(fx: &[Effect]) -> Option { + 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. + if !effects.iter().any(|e| e.visible && crate::raster::follows(&e.id)) || !effects.iter().any(|e| e.visible && e.id == "distort.transform") { + return None; + } + let t = effects.iter().rposition(|e| { + e.visible && e.id == "distort.transform" && crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).1 > 0 + })?; + let before = effects.get(..t)?; + let carried = before.iter().any(|e| e.visible && crate::raster::follows(&e.id)) + && before.iter().all(|e| !e.visible || is_geometry(&e.id) || crate::raster::follows(&e.id)); + let excluded = n.extras().mask.as_ref().is_some_and(|m| m.linked) + || crate::has_solid(n) + || crate::has_revolve(n) + || crate::has_crop_marks(n) + || crate::addons::halftone::has_halftone(n) + || has_painted_effects(n) + || n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())) + || n.projection().is_some(); + (carried && !excluded).then_some(t) +} + +/// Where the own effects of `n`, a group or layer, split so that each copy of a Transform effect +/// carries the raster effects listed before that effect ([`crate::evaluate_container`]), as those of +/// a path split ([`copied_raster_at`]): the index of the last visible Transform effect that makes +/// copies, when a visible raster effect that follows a Transform effect is listed before it and +/// every other visible effect before it is a geometry effect or such a raster effect. `None` +/// otherwise, and for a compound shape, a Shaper group, a group or layer with a Pathfinder effect, a +/// linked opacity mask, a 3D effect, Crop Marks, Vector Halftone, a live-effect plug-in that paints +/// what it returns, a perspective, or a fill or stroke that paints with geometry effects of its own. +pub(crate) fn copied_container_raster_at(n: &Node) -> Option { + if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) { + return None; + } + let effects = &n.appearance.effects; + // Checked first: this runs for every group and layer drawn. + if !effects.iter().any(|e| e.visible && crate::raster::follows(&e.id)) || !effects.iter().any(|e| e.visible && e.id == "distort.transform") { + return None; + } + let t = effects.iter().rposition(|e| { + e.visible && e.id == "distort.transform" && crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).1 > 0 + })?; + let before = effects.get(..t)?; + let carried = before.iter().any(|e| e.visible && crate::raster::follows(&e.id)) + && before.iter().all(|e| !e.visible || is_geometry(&e.id) || crate::raster::follows(&e.id)); + let excluded = n.is_compound_shape() + || n.extras().shaper.is_some() + || crate::has_pathfinder(n) + || n.extras().mask.as_ref().is_some_and(|m| m.linked) + || crate::has_solid(n) + || crate::has_revolve(n) + || crate::has_crop_marks(n) + || crate::addons::halftone::has_halftone(n) + || effects.iter().any(|e| painted_plugin(e).is_some()) + || n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())) + || n.projection().is_some(); + (carried && !excluded).then_some(t) +} + +/// `piece`, the art that the effects of `n` (a group or layer whose own effects split at `t`, +/// [`copied_container_raster_at`]) before the Transform effect at `t` make of it, with the raster +/// effects among them as its own, copied by that Transform effect: a group with `n`'s id holding +/// the copies, the last copy lowest and the original on top, each copy's own raster effects moved, +/// turned, reflected and scaled with it ([`crate::raster::follow_contents`]), once, whatever Scale +/// Strokes & Effects says. The members' own raster effects in each copy stay as a Transform effect +/// that copies a group leaves them. The geometry effects after `t` then reshape all the copies as +/// one piece. The copies stop where [`copy_art`]'s do, each with its raster effects. The copies +/// inside `piece` that an earlier copying Transform effect of `n` made, which carry `n`'s id, have +/// their raster effects moved, turned, reflected and scaled with each copy in the same way +/// ([`follow_carried`]). The copies are made about `bounds`, the piece's bounds. Returns the art +/// and the raster effects from `t` on, as they ran. +pub(crate) fn copied_container_art(doc: Option<&Document>, n: &Node, t: usize, piece: Node, bounds: Option) -> (Node, Vec) { + let rest = n.appearance.effects.get(t..).unwrap_or_default(); + let own = piece.appearance.effects.clone(); + let original = piece.clone(); + let mut art = Node::group(n.id, vec![Arc::new(piece)]); + if let (Some(e), Some(bounds)) = (rest.first(), bounds) { + let params = merged_params(&e.id, &e.params); + let (m, copies) = crate::distort::transform_map(bounds, ¶ms, n.id.0); + let max = Budget::EFFECTS.at_least(art_cost(&art)); + copy_art(&mut art, m, copies, copy_scaling(crate::distort::TransformOptions::of(¶ms)), max); + if let Some(children) = art.children_mut() { + // The original is last, and each copy above it is mapped once more by `m`. + let step = m.with_translation(vectorcraft_geom::Vec2::ZERO); + let mut a = Affine::IDENTITY; + for (k, c) in children.iter_mut().rev().enumerate() { + // Each copy is the piece in a group of its own: the piece takes its place. + if let Some([one]) = c.children().map(Vec::as_slice) { + *c = one.clone(); + } + if k > 0 { + a *= step; + // Scale Strokes & Effects scaled the copy's own effects with it: they follow + // its map from their values on the original instead. + let copy = Arc::make_mut(c); + copy.appearance.effects = own.clone(); + crate::raster::follow_contents(&mut copy.appearance.effects, a, Affine::IDENTITY); + follow_carried(copy, &original, n.id, a); + } + } + } + } + let later: Vec<&Effect> = rest.iter().skip(1).filter(|e| e.visible && is_geometry(&e.id)).collect(); + let carry = reshape_leaves_apart(&mut art, &later, &n.appearance.effects, Budget::EFFECTS, (false, false), doc); + let mut ran = n.appearance.effects.clone(); + if carry.skipped() { + carry.hide_skipped(&mut ran); + } + let effects = crate::raster::without_geometry(ran.get(t..).unwrap_or_default()); + (art, effects) +} + +/// Give the members of `copy` with `id` (the copies that an earlier copying Transform effect of a +/// group or layer made, [`copied_container_art`]), at every depth below such members, the raster +/// effects of the matching members of `original`, the piece `copy` was made from, made to follow +/// `a` ([`crate::raster::follow_contents`]). +fn follow_carried(copy: &mut Node, original: &Node, id: NodeId, a: Affine) { + let (Some(ch), Some(was)) = (copy.children_mut(), original.children()) else { return }; + for (c, w) in ch.iter_mut().zip(was).filter(|(c, w)| w.id == id && c.id == id) { + let c = Arc::make_mut(c); + c.appearance.effects = w.appearance.effects.clone(); + crate::raster::follow_contents(&mut c.appearance.effects, a, Affine::IDENTITY); + follow_carried(c, w, id, a); + } } /// Is `e` a visible live-effect plug-in whose manifest declares `paintOutput`: its id's plug-in id, @@ -475,11 +673,69 @@ fn laid_out(t: &vectorcraft_doc::TextObject) -> (Vec, kurbo::Bez (runs, all, layout.bounds, colours) } +/// Paint `piece`, a piece of type's outline in text space (glyphs, ruby glyphs or an underline or +/// strikethrough bar), with `style`, the fills and strokes of its run, and place it in the document +/// by `xf`, the type's transform, as the renderer paints the run: its unplaced gradients are fixed +/// to `bounds`, the layout's bounds in text space, so every piece of the type shows the one +/// 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. +/// +/// 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, 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`]). @@ -487,7 +743,6 @@ pub fn outline_text(n: &Node) -> Option { let NodeKind::Text(t) = &n.kind else { return None }; let (runs, all, bounds, colours) = laid_out(t); let path = |bp: &kurbo::BezPath| PathData::from_bezpath(bp).transformed(t.xf); - let scaling = vectorcraft_doc::Scaling { strokes: true, patterns: true, ..Default::default() }; let mut children: Vec> = vec![]; for (i, (bp, run)) in runs.iter().zip(&t.runs).enumerate() { // Colour glyphs paint themselves, under their run's fill, as the renderer paints them. @@ -495,11 +750,10 @@ pub fn outline_text(n: &Node) -> Option { if bp.elements().is_empty() { continue; } - let mut ap = run.style.appearance(); - ap.pin_gradients(bounds); - let mut piece = Node::path(n.id, PathData::from_bezpath(bp), ap); - piece.transform(t.xf, scaling); + let mut piece = Node::path(n.id, PathData::from_bezpath(bp), Appearance::default()); + 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(); @@ -689,18 +943,32 @@ fn instances_as_art(doc: Option<&Document>, n: &mut Node, outline: OutlineHook, } } +/// Type `t` in a clip group's clipping path as its outlines ([`outline_text`]) with its +/// visibility, or with geometry effects as a path of the region they give it, which is what +/// [`crate::clip_outline`] clips by. +pub(crate) fn clipping_text_outline(t: &Node) -> Option { + if let Some(p) = crate::clip::with_clip_effects_applied(t) { + return Some(p); + } + let o = outline_text(t)?; + Some(Node { visible: t.visible, ..o }) +} + /// Replace type anywhere inside `n` by its outlines, as art that keeps the type's look /// ([`as_art`]). Type in a clip group's clipping path (all of `n` when `clipping` is set) becomes -/// its plain outlines ([`outline_text`]) with its visibility, which is what -/// [`crate::clip_outline`] clips by. The swatches and patterns that live-effect plug-ins painting -/// their pieces name are looked up in `doc`. +/// its outlines with its visibility and effects ([`clipping_text_outline`]), and its fills and +/// strokes become art of their own ([`paint_type_clip`]). The swatches and patterns that +/// live-effect plug-ins painting their pieces name are looked up in `doc`. pub(crate) fn outline_nested_text(doc: Option<&Document>, n: &mut Node, clipping: bool) { + if !clipping { + paint_type_clip(doc, n); + } let clips = n.clips(); let Some(ch) = n.children_mut() else { return }; for (i, c) in ch.iter_mut().enumerate() { let clipping = clipping || (clips && i == 0); let art = match &c.kind { - NodeKind::Text(_) if clipping => outline_text(c).map(|o| Node { visible: c.visible, ..o }), + NodeKind::Text(_) if clipping => clipping_text_outline(c), NodeKind::Text(_) => as_art(doc, c, None), _ => None, }; @@ -712,6 +980,36 @@ pub(crate) fn outline_nested_text(doc: Option<&Document>, n: &mut Node, clipping } } +/// When `n` is a clip group or clipping layer whose clipping path is type that paints +/// ([`Node::clip_paint`]), make it the art the canvas draws for it: the type's outlines clip +/// ([`clipping_text_outline`]), its fills as art ([`as_art`]) paint behind the clipped art inside +/// the clip, and its strokes as art paint over it, outside the clip, in a group that `n` becomes +/// (keeping its id, name and transparency) with the clip group inside. The other members stay as +/// they are. Hidden type paints nothing. +pub(crate) fn paint_type_clip(doc: Option<&Document>, n: &mut Node) { + let Some((first, rest)) = n.children().and_then(|ch| ch.split_first()) else { return }; + if !n.clips() || !matches!(first.kind, NodeKind::Text(_)) || !first.visible { + return; + } + let paint = first.clip_paint(); + if paint.fill.is_none() && paint.stroke.is_none() { + return; + } + let Some(clip) = clipping_text_outline(first) else { return }; + let art = |part: Option| part.and_then(|p| as_art(doc, &p, None)).map(Arc::new); + let members: Vec> = std::iter::once(Arc::new(clip)).chain(art(paint.fill)).chain(rest.iter().cloned()).collect(); + let stroke = art(paint.stroke); + let id = n.id; + match (&mut n.kind, stroke) { + (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }, None) => *children = members, + (NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. }, Some(stroke)) => { + *children = vec![Arc::new(Node::new(id, NodeKind::Group { children: members, clip: true })), stroke]; + *clip = false; + } + _ => {} + } +} + /// `n` (see [`needs_outline`]) with its object-level geometry effects and its perspective applied: /// its [`outline_art`] reshaped as one piece, or for an image the image clipped by its reshaped /// frame. Type's own fills and strokes keep their effects on its whole outline. An image's own @@ -757,6 +1055,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()) @@ -787,6 +1095,10 @@ fn as_art_opts( nodes: &SymbolNodes, apart: bool, ) -> Option { + if let Some(t) = copied_raster_at(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 { NodeKind::Image(im) => { @@ -842,7 +1154,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); } @@ -858,7 +1170,7 @@ fn as_art_opts( /// `art`, the art made of `n`, with `n`'s name, visibility, transparency, opacity mask and /// remaining (raster) effects. -fn dressed(mut art: Node, n: &Node) -> Node { +pub(crate) fn dressed(mut art: Node, n: &Node) -> Node { art.name = n.name.clone(); art.visible = n.visible; art.opacity = n.opacity; @@ -872,6 +1184,107 @@ fn dressed(mut art: Node, n: &Node) -> Node { art } +/// [`dressed`] that keeps the effects of `art`. +fn dressed_keeping_effects(mut art: Node, n: &Node) -> Node { + let effects = std::mem::take(&mut art.appearance.effects); + let mut art = dressed(art, n); + art.appearance.effects = effects; + art +} + +/// 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, 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 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); + } + transform_items(&mut art, doc); + let mut ran = source.appearance.effects.clone(); + if carry.skipped() { + carry.hide_skipped(&mut ran); + } + art.appearance.effects = crate::raster::without_geometry(&ran); + art + } + }; + let mut art = Node::group(n.id, vec![Arc::new(piece)]); + if let (Some(e), Some(bounds)) = (rest.first(), art.geometric_bounds()) { + let params = merged_params(&e.id, &e.params); + let (m, copies) = crate::distort::transform_map(bounds, ¶ms, n.id.0); + let options = crate::distort::TransformOptions::of(¶ms); + // The raster effects follow the copies below; Scale Strokes & Effects scales the others. + let mut scaling = copy_scaling(options); + scaling.effects = options.strokes.then_some(scale_unfollowed as fn(&mut Effect, f64)); + let max = Budget::EFFECTS.at_least(art_cost(&art)); + copy_art(&mut art, m, copies, scaling, max); + if let Some(children) = art.children_mut() { + // The original is last, and each copy above it is mapped once more by `m`. + let step = m.with_translation(vectorcraft_geom::Vec2::ZERO); + let mut a = Affine::IDENTITY; + let none = HashSet::new(); + for (k, c) in children.iter_mut().rev().enumerate() { + if k > 0 { + a *= step; + follow_art(Arc::make_mut(c), a, &none, Some(&none), None, 0); + } + // Each copy is the piece in a group of its own: the piece takes its place. + if let Some([one]) = c.children().map(Vec::as_slice) { + *c = one.clone(); + } + } + } + } + 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, 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()); + 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, compound path, type, image or symbol instance whose copies each carry the raster +/// effects listed before it ([`copied_raster_at`]) and for a group or layer whose copies do +/// ([`copied_container_raster_at`]). +pub fn outer_effects(n: &Node) -> &[Effect] { + match copied_raster_at(n).or_else(|| copied_container_raster_at(n)) { + Some(t) => n.appearance.effects.get(t..).unwrap_or_default(), + None => &n.appearance.effects, + } +} + /// A group with `n`'s id holding `n` without its transparency, opacity mask and effects: the one /// piece that `n`'s own geometry effects reshape. fn one_piece(n: &Node) -> Node { @@ -899,6 +1312,9 @@ pub(crate) fn own_effects_art(doc: Option<&Document>, n: &Node) -> Option { return None; } + if let Some(t) = copied_raster_at(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. return crate::bake_type_appearance(doc, n).map(|art| Node { knockout: vectorcraft_doc::Knockout::Off, ..art }); @@ -981,19 +1397,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 @@ -1014,7 +1430,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 @@ -1025,7 +1444,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; @@ -1062,7 +1488,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)); @@ -1106,6 +1532,7 @@ struct Step<'a> { seed: u64, effect: Option, apart: bool, + rows: bool, doc: Option<&'a Document>, wholes: &'a HashMap, held: bool, @@ -1270,8 +1697,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) @@ -1279,9 +1710,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. @@ -1297,6 +1731,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); @@ -1688,7 +2125,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 { @@ -2004,7 +2441,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. @@ -2021,9 +2459,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 @@ -2033,12 +2482,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. /// @@ -2084,7 +2538,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; }; @@ -2162,13 +2616,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() { @@ -2219,6 +2684,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; @@ -2239,7 +2705,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> { @@ -2460,12 +2926,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>, @@ -2508,15 +2976,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); @@ -2541,6 +3024,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 { .. }); @@ -2613,6 +3127,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 74b23340cd..c065e507df 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -5,9 +5,10 @@ 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_three_d::{Edge, Revolve}; +use vectorcraft_geom::{FillRule, PathData, PathEl, Point, Rect, Vec2}; +use vectorcraft_three_d::{Edge, Revolve, SolidFaces}; +use crate::solids::wireframe::{WireFace, wireframe_params}; use crate::solids::{ Profile, Scope, is_container, members, object_profile, past_effect, profile, reshape_members, resolve_for, solid_paints, union_bounds, }; @@ -104,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, } @@ -153,7 +155,12 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) let b = union_bounds(&shapes).ok_or(EMPTY)?; let options = shared_options(&shapes, options_of(id, p))?; let mut copies = 0; - shapes.iter().try_for_each(|s| check_surface(&s.path, b, options, surface_item(&s.items), &mut copies))?; + // In wireframe mode the edges are drawn with no paint copies, graphics or shadow. + let wire = wireframe_params(id, p); + shapes.iter().try_for_each(|s| check_surface(&s.path, b, options, surface_item(&s.items).filter(|_| !wire), &mut copies))?; + if wire { + return Ok(()); + } // Without graphics, or without the document they draw from, no member is measured for them. if let Some(doc) = doc.filter(|_| id == REVOLVE && !crate::solids::mapped_graphics(p).is_empty()) { match graphics_member(&shapes, b, options).and_then(|k| shapes.get(k)) { @@ -165,7 +172,7 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) } } } - let casting = shapes.iter().filter(|s| surface_item(&s.items).is_some_and(|i| paint_of(i).1 * s.opacity > 0.0)); + let casting = shapes.iter().filter(|s| surface_item(&s.items).is_some_and(|i| crate::solids::shadow::casts(paint_of(i).1 * s.opacity))); return check_shadow(p, casting.map(|s| &s.path), b, options); } let (path, _) = object_profile(n, "Revolve")?; @@ -175,7 +182,11 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) let path = geometry(&path, before, &GeomContext::of(n)); let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?; let paints = solid_paints(n); - check_surface(&path, b, options_of(id, p), surface_item(&paints), &mut 0)?; + let wire = wireframe_params(id, p); + check_surface(&path, b, options_of(id, p), surface_item(&paints).filter(|_| !wire), &mut 0)?; + if wire { + return Ok(()); + } check_graphics(doc, id, &path, b, options_of(id, p), p, &mut 0)?; check_shadow(p, [&path], b, options_of(id, p)) } @@ -221,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 @@ -260,7 +271,11 @@ pub(crate) fn validate_item_of(doc: Option<&Document>, n: &Node, id: &str, p: &V let options = options_of(kind, ¶ms); let path = geometry(&path, at.and_then(|at| effects.get(..at)).unwrap_or(effects), &ctx.item(item)); let b = path.bounds().ok_or(EMPTY)?; - check_surface(&path, b, options, crate::paints(item).then_some(item), &mut copies)?; + let wire = wireframe_params(kind, ¶ms); + check_surface(&path, b, options, (crate::paints(item) && !wire).then_some(item), &mut copies)?; + if wire { + continue; + } // The graphics of every item add their paints' copies to the graphics' budget, as they // are drawn; only the edited item's graphics are refused here. let graphics = check_graphics(doc, kind, &path, b, options, ¶ms, &mut graphic_copies); @@ -282,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()); } @@ -323,6 +362,7 @@ pub(crate) fn validate_revolve_params(p: &Value) -> Result<(), String> { pub(crate) fn validate_params_of(id: &str, p: &Value) -> Result<(), String> { validate_revolve_params(p)?; crate::solids::graphics::validate(id, p)?; + crate::solids::wireframe::validate_render(id, p)?; if id == CLASSIC_REVOLVE { classic::validate(p)?; } @@ -335,46 +375,97 @@ fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData { /// The shadow of Revolve `fx` cast by the surface of `path` in `item`'s paint about the axis of /// `b`, revolved with `options`, as dark as `item` is opaque and in its blending mode; `None` with -/// the shadow off, when `item` is fully transparent or when it casts nothing, and an error when -/// the surface it is cast from is past the limits. -fn shadow_of(id: NodeId, fx: &Effect, path: &PathData, item: &AppearanceItem, b: Rect, options: Revolve) -> Result, String> { +/// the shadow off, when `item` is fully transparent or its opacity is not a finite number, or when +/// it casts nothing, and an error when the surface it is cast from is past the limits. +/// +/// `kept` holds the faces the surface drawn kept for its shadow ([`surface`]); without them the +/// surface is swept again for its shadow alone. +fn shadow_of( + id: NodeId, + fx: &Effect, + path: &PathData, + item: &AppearanceItem, + b: Rect, + options: Revolve, + kept: Option, +) -> Result, String> { let Some(settings) = crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)) else { return Ok(None) }; let (_, opacity, blend) = paint_of(item); - if opacity <= 0.0 { + if !crate::solids::shadow::casts(opacity) { return Ok(None); } let mut caster = vectorcraft_three_d::ShadowCaster::new(); - caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options)?; + cast_surface(&mut caster, path, b, options, kept)?; Ok(crate::solids::shadow::art(id, &caster, settings, crate::solids::shadow::Ink { opacity, blend })) } +/// Does Revolve `fx` cast a shadow, so a surface in paint as opaque as `opacity` keeps the faces +/// its shadow is cast from ([`surface`])? +fn casts(fx: &Effect, opacity: f32) -> bool { + crate::solids::shadow::casts(opacity) && crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)).is_some() +} + +/// Add the surface of `path` about the axis of `b` to `caster`: the faces it kept when it was +/// drawn, or without them, the surface swept for its shadow alone. +fn cast_surface( + caster: &mut vectorcraft_three_d::ShadowCaster, + path: &PathData, + b: Rect, + options: Revolve, + kept: Option, +) -> Result, String> { + match kept { + Some(kept) => caster.add_solid(kept), + None => { + #[cfg(test)] + crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); + caster.revolve(path, options.fill_rule, b, options) + } + } +} + /// The shadow of group Revolve `fx` cast by the surfaces of the members `shapes` that have one, /// about the axis of `b`, on one plane; each member's part is as dark as its surface is opaque, /// in its paint's blending mode, and its opacity mask and blending mode apply to that part /// ([`crate::solids::shadow::scoped_art`]). An error when the surfaces it is cast from are past the -/// limits. -fn group_shadow(id: NodeId, fx: &Effect, shapes: &[Profile], b: Rect, options: Revolve) -> Result>, String> { +/// limits. `kept` holds, member by member, the faces each surface drawn kept for its shadow +/// ([`surface`]); a member without them is swept again for its shadow alone. +fn group_shadow( + id: NodeId, + fx: &Effect, + shapes: &[Profile], + b: Rect, + options: Revolve, + kept: Vec>, +) -> Result>, String> { let Some(settings) = crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)) else { return Ok(vec![]) }; let mut caster = vectorcraft_three_d::ShadowCaster::new(); let mut cast = vec![]; + let mut kept = kept.into_iter(); for s in shapes { + let kept = kept.next().flatten(); let Some((_, opacity, blend)) = surface_item(&s.items).map(paint_of) else { continue }; - // A member whose surface is fully transparent casts nothing. + // A member whose surface is fully transparent, or whose opacity is not a finite number, casts nothing. let ink = crate::solids::shadow::Ink { opacity: opacity * s.opacity, blend }; - if ink.opacity <= 0.0 { + if !ink.casts() { continue; } - let faces = caster.revolve(&s.path, vectorcraft_geom::FillRule::NonZero, b, options)?; + 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))) } -/// One object's surface of revolution about the axis of `b`, and each face's depth. `copies` counts +/// One object's surface of revolution about the axis of `b`, and each face it draws ([`Drawn`]), +/// back to front: by depth, and where two faces overlap, by their depths there +/// ([`crate::solids::surface_order`]). `copies` counts /// the bytes of the paint copies of every surface and graphic of the object. Revolve (Classic) draws every face /// 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. +/// 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`]). 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>, @@ -388,25 +479,42 @@ fn surface( blend: vectorcraft_doc::color::BlendMode, expand: bool, copies: &mut Copies, -) -> Option<(Vec, Node)> { + cast: bool, +) -> 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 // of crashing the frame. Commands validate the same evaluator and report its errors. if fx.id == CLASSIC_REVOLVE { - let facets = vectorcraft_three_d::revolve_facets(path, b, options).ok()?; + let (facets, kept) = if cast { + vectorcraft_three_d::revolve_facets_shadowed(path, b, options).ok().map(|(f, kept)| (f, Some(kept)))? + } else { + (vectorcraft_three_d::revolve_facets(path, b, options).ok()?, None) + }; copies.surfaces = copies.surfaces.saturating_add(paint_copies(facets.len(), &paint)); if copies.surfaces > MAX_PAINT_COPIES { return None; } - let depths = facets.iter().map(|f| f.depth).collect(); + let order = crate::solids::surface_order(facets.iter().map(|f| (f.contours.first().map_or(&[][..], Vec::as_slice), f.plane, f.depth))); + let facets = in_order(facets, &order); + 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((depths, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p))); + 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 faces = vectorcraft_three_d::revolve(path, b, options).ok()?; - copies.surfaces = copies.surfaces.saturating_add(paint_copies(faces.len(), &paint)); + 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) + }; + 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; } + let order = crate::solids::surface_order(faces.iter().map(|f| (f.points.as_slice(), f.plane, f.depth))); + let faces = in_order(faces, &order); let graphics = crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params)); let shade = |face: &vectorcraft_three_d::Face, c: Color| graphic_paint(face, c, colored); // Graphics past the limits are left out, and the surface draws without them and their paints' @@ -437,21 +545,28 @@ fn surface( && n.has_default_transparency()) .then(|| vectorcraft_three_d::visible_faces(&faces).ok()) .flatten(); - let faces = visible.unwrap_or_else(|| { - faces - .into_iter() - .map(|f| vectorcraft_three_d::VisibleFace { - path: f.path(), - brightness: f.brightness, - depth: f.depth, - gradient: f.gradient, - illumination: f.illumination, - light_gradient: f.light_gradient, - rgb_gradient: f.rgb_gradient, - }) - .collect() - }); - let depths: Vec = faces.iter().map(|f: &vectorcraft_three_d::VisibleFace| f.depth).collect(); + let (faces, keys): (Vec, Vec) = match visible { + Some(visible) => { + let keys = visible.iter().map(|f| Drawn { depth: f.depth, points: vec![], plane: None }).collect(); + (visible, keys) + } + None => { + let keys = faces.iter().map(|f| Drawn { depth: f.depth, points: f.points.clone(), plane: f.plane }).collect(); + let faces = faces + .into_iter() + .map(|f| vectorcraft_three_d::VisibleFace { + path: f.path(), + brightness: f.brightness, + depth: f.depth, + gradient: f.gradient, + illumination: f.illumination, + light_gradient: f.light_gradient, + rgb_gradient: f.rgb_gradient, + }) + .collect(); + (faces, keys) + } + }; let children = faces .into_iter() .map(|face| { @@ -517,23 +632,104 @@ fn surface( let mut group = Node::group(n.id, children); group.opacity = opacity; group.blend = blend; - Some((depths, group)) + Some((keys, group, kept, seal)) } -/// A surface of one object about the bounds of `path`, built with options derived from `fx`. -/// `copies` is the count [`surface`] adds to; its graphics take the symbols of `doc`. +/// 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 +/// drawing and its plane (none for a face trimmed to the part of it that shows). +struct Drawn { + depth: f64, + points: Vec, + plane: Option, +} + +/// `items` in `order`, a permutation of their indices. +fn in_order(items: Vec, order: &[usize]) -> Vec { + let mut slots: Vec> = items.into_iter().map(Some).collect(); + order.iter().filter_map(|&k| slots.get_mut(k).and_then(Option::take)).collect() +} + +/// 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, copies: &mut Copies, -) -> Option { +) -> Option<(Node, Option)> { let b = path.bounds()?; let (paint, opacity, blend) = paint_of(item); - surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies).map(|(_, art)| art) + let cast = casts(fx, opacity); + 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 @@ -634,12 +830,12 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul /// instances, blends and clipping groups already resolved), in document coordinates: with the /// effect on the object, the surface in its top visible fill (else its stroke); with it on fills and strokes, one surface for each of /// them, reshaped by the geometry effects after each one's Revolve; on a group or layer, one for -/// each member, about one shared axis. The swatches and patterns named by a live-effect plug-in -/// after a fill's or stroke's Revolve are looked up in `doc`. -pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result, String> { - let faces = |path: &PathData, b: Rect, options: Revolve| -> Result, String> { - Ok(vectorcraft_three_d::revolve(path, b, options)?.iter().map(vectorcraft_three_d::Face::path).collect()) - }; +/// each member, about one shared axis. With the effect on the object, group or layer, also the +/// shadow drawn behind them. The swatches and patterns named by a live-effect plug-in after a fill's +/// or stroke's Revolve are looked up in `doc`. Each face carries the width of the stroke the canvas +/// draws around it ([`surface`]). +pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result { + let faces = wire_faces; if is_container(n) { let index = n .appearance @@ -647,27 +843,30 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result, n: &Node) -> Result Result, String> { + if fx.id == CLASSIC_REVOLVE { + let p = merged_params(&fx.id, &fx.params); + let facets = vectorcraft_three_d::revolve_facets(path, b, options)?; + return Ok(facets.iter().map(|f| WireFace { path: f.path(), stroke: crate::solids::classic::stroke_width(f, &p) }).collect()); + } + 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`, 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, 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) } /// [`revolve_meshes`] of group or layer `n`: one mesh for each member, about one shared axis. @@ -727,13 +949,18 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let paints = solid_paints(n); let item = surface_item(&paints)?; let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); - let surface = object_surface(doc, n, &path, 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)).ok()? - { - children.push(Arc::new(shadow)); + if crate::solids::renders_wireframe(fx) { + // In wireframe mode the edges of the faces, with no shadow. + children.push(wire_art(n.id, [(&path, rule)], path.bounds()?, fx, fx_options(fx))?); + } else { + 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, rule_options(fx, rule), kept).ok()? + { + children.push(Arc::new(shadow)); + } + children.push(Arc::new(surface)); } - children.push(Arc::new(surface)); // Later geometry acts on the projected art as a whole through container evaluation. remaining = past_effect(&n.appearance.effects, index); remaining.retain(|e| !is_revolve(&e.id)); @@ -753,12 +980,20 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let fx = item.effects().get(index)?; 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)); - let mut art = object_surface(doc, n, &p, fx, item, expand, &mut copies)?; + if crate::solids::renders_wireframe(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, 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)).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)); @@ -902,25 +1137,47 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes); let b = union_bounds(&shapes)?; 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, 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(); + return Some(art); + } let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); let mut copies = Copies::default(); 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. let mapped = fx.id == REVOLVE && !crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params)).is_empty(); let longest = if mapped { graphics_member(&shapes, b, options) } else { None }; for (k, s) in shapes.iter().enumerate() { - let Some(item) = surface_item(&s.items) else { continue }; + let Some(item) = surface_item(&s.items) else { + kept.push(None); + continue; + }; // The opacity and blending of the member and the groups it is in apply through its scopes. let (paint, opacity, blend) = paint_of(item); opaque &= opacity >= 1.0 && blend == Default::default() && s.scopes.is_empty(); // A member with transparency of its own keeps every face, as a transparent object does. let expand = expand && s.scopes.is_empty(); let doc = doc.filter(|_| longest == Some(k)); - let (depths, art) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies)?; + let cast = casts(fx, opacity * s.opacity); + let options = Revolve { fill_rule: s.rule, ..options }; + let (depths, art, faces, seal) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies, cast)?; surfaces.push((depths, art, s.scopes.as_slice())); + kept.push(faces); + 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; } @@ -934,16 +1191,19 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { } else { let count = surfaces.len(); let mut faces = vec![]; - for (member, (depths, s, scopes)) in surfaces.into_iter().enumerate() { + for (member, (drawn, s, scopes)) in surfaces.into_iter().enumerate() { let (opacity, blend) = (s.opacity, s.blend); if let NodeKind::Group { children, .. } = s.kind { - faces.extend(depths.into_iter().zip(children).map(|(depth, face)| (depth, member, opacity, blend, scopes, face))); + faces.extend(drawn.into_iter().zip(children).map(|(drawn, face)| (drawn, member, opacity, blend, scopes, face))); } } - // A stable sort: faces at the same depth keep the members' order. - faces.sort_by(|a, b| a.0.total_cmp(&b.0)); + // A stable sort: faces at the same depth keep the members' order. Overlapping faces, of one + // member or of two, then go in the order of their depths where they overlap. + faces.sort_by(|a, b| a.0.depth.total_cmp(&b.0.depth)); + 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 @@ -952,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>, @@ -967,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| { @@ -995,29 +1257,54 @@ 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. let mut children = children; - children.splice(0..0, group_shadow(n.id, fx, &shapes, b, options).ok()?); + children.splice(0..0, group_shadow(n.id, fx, &shapes, b, options, kept).ok()?); let remaining = past_effect(&n.appearance.effects, index); let mut art = n.clone(); art.kind = NodeKind::Group { children, clip: false }; @@ -1535,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] @@ -1642,6 +2079,116 @@ mod tests { } assert_eq!(expand_revolve_art(&sample), revolve_art(&sample)); } + + /// The settings the shadows are compared with: the defaults, a partial sweep turned with + /// perspective, and an open surface away from its axis under a colored light. + fn shadow_settings() -> [Value; 3] { + [ + json!({"shadow": true}), + json!({"shadow": true, "rotationX": -25, "rotationY": 35, "perspective": 50, "angle": 220, "shadowDistance": 40}), + json!({"shadow": true, "shadowDistance": 30, "lightColor": "#ff8040", "offset": 20, "cap": false}), + ] + } + + /// The shadow of the faces Revolve and Revolve (Classic) kept when they swept their surfaces, + /// to the bit: the shadow of surfaces swept for the shadow alone, for one object, for an + /// object whose fill is half transparent, and for a group of two members, one at half opacity. + #[test] + fn the_shadow_cast_from_the_surfaces_drawn_is_the_shadow_of_surfaces_swept_for_it() { + for id in [REVOLVE, CLASSIC_REVOLVE] { + for params in shadow_settings() { + // Revolve (Classic) takes no shadow settings from commands, but a file can carry them. + let mut fx = crate::new_effect(id, &json!({})).unwrap(); + fx.params = params.clone(); + let n = profile_node(); + 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] { + f.opacity = 0.5; + } + for n in [n, half] { + let item = surface_item(&n.appearance.items).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}"); + } + let mut other = profile_node(); + other.id = NodeId(2); + other.transform(Affine::translate((120.0, 0.0)), false); + other.opacity = 0.5; + let mut g = Node::group(NodeId(9), vec![Arc::new(profile_node()), Arc::new(other)]); + g.appearance.effects.push(fx.clone()); + let shapes = members(&g, "").unwrap(); + let b = union_bounds(&shapes).unwrap(); + let options = shared_options(&shapes, fx_options(&fx)).unwrap(); + let kept: Vec> = shapes + .iter() + .map(|s| { + let (paint, opacity, blend) = paint_of(surface_item(&s.items).unwrap()); + let cast = casts(&fx, opacity * s.opacity); + surface(None, &g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast).unwrap().2 + }) + .collect(); + assert!(kept.iter().all(Option::is_some), "{id} {params}"); + let drawn = group_shadow(g.id, &fx, &shapes, b, options, kept).unwrap(); + let alone = group_shadow(g.id, &fx, &shapes, b, options, vec![]).unwrap(); + assert!(!alone.is_empty() || id == CLASSIC_REVOLVE, "{id} {params}"); + assert_eq!(format!("{drawn:?}"), format!("{alone:?}"), "{id} {params}"); + } + } + } + + /// A surface whose fill, or whose member, is at NaN or infinite opacity casts no shadow, as one + /// at 0 % does, whether the shadow is cast from the surface drawn or swept for it alone; the + /// member beside it still casts its part. + #[test] + fn a_surface_whose_opacity_is_not_a_finite_number_casts_no_shadow() { + let fx = crate::new_effect(REVOLVE, &json!({"shadow": true})).unwrap(); + let group = |opacity: f32| { + let mut other = profile_node(); + other.id = NodeId(2); + other.transform(Affine::translate((120.0, 0.0)), false); + other.opacity = opacity; + let mut g = Node::group(NodeId(9), vec![Arc::new(profile_node()), Arc::new(other)]); + g.appearance.effects.push(fx.clone()); + g + }; + let group_shadows = |g: &Node| { + let shapes = members(g, "").unwrap(); + let b = union_bounds(&shapes).unwrap(); + let options = shared_options(&shapes, fx_options(&fx)).unwrap(); + let kept: Vec> = shapes + .iter() + .map(|s| { + let (paint, opacity, blend) = paint_of(surface_item(&s.items).unwrap()); + let cast = casts(&fx, opacity * s.opacity); + surface(None, g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast).unwrap().2 + }) + .collect(); + [group_shadow(g.id, &fx, &shapes, b, options, kept).unwrap(), group_shadow(g.id, &fx, &shapes, b, options, vec![]).unwrap()] + .map(|art| format!("{art:?}")) + }; + let expected = group_shadows(&group(0.0)); + for bad in [f32::NAN, f32::INFINITY] { + let mut n = profile_node(); + if let AppearanceItem::Fill(f) = &mut n.appearance.items[0] { + f.opacity = bad; + } + 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, 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)); + assert!(!expected[0].is_empty() && expected[0] != "[]", "the opaque member casts"); + assert_eq!(shadows, expected, "{bad}: only the opaque member casts"); + } + } } #[cfg(test)] diff --git a/crates/effects/src/revolve/classic.rs b/crates/effects/src/revolve/classic.rs index 1881381567..4aefb13eef 100644 --- a/crates/effects/src/revolve/classic.rs +++ b/crates/effects/src/revolve/classic.rs @@ -23,7 +23,7 @@ const RANGES: [(&str, f64, f64, bool); 13] = [ ("blendSteps", 1.0, 256.0, true), ]; -const FLAGS: [&str; 2] = ["cap", "lightBehind"]; +const FLAGS: [&str; 3] = ["cap", "lightBehind", "preserveSpotColors"]; /// The surface Revolve (Classic)'s parameters `p` sweep: Revolve's angle, cap, offset, edge, /// rotation and perspective, built unshaded, since the classic surfaces light its faces. @@ -118,6 +118,87 @@ mod tests { } } + /// With Preserve Spot Colors, a fill linked to a spot swatch stays linked on every face: the + /// highlight lowers its tint, and the shadow is black multiplied and overprinting over it. + #[test] + fn preserve_spot_colors_keeps_the_swatch_on_every_face() { + let ink = Color::cmyk(0.0, 1.0, 0.0, 0.2); + let spot = |params: Value| { + let mut n = profile(); + *n.appearance = Appearance::basic(Paint::Solid { color: ink, swatch: Some("Ink".into()), tint: 0.5 }, Paint::None, 0.0); + n.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, ¶ms).unwrap()); + crate::revolve_art(&n).unwrap() + }; + let art = spot(json!({"preserveSpotColors": true})); + let mut darkened = 0; + for face in faces(&art) { + let mut fills = face.appearance.items.iter().filter_map(|i| match i { + AppearanceItem::Fill(f) => Some(f), + AppearanceItem::Stroke(_) => None, + }); + match fills.next().map(|f| &f.paint) { + Some(Paint::Solid { color, swatch: Some(name), tint }) => { + assert_eq!(name, "Ink"); + assert!(*tint > 0.0 && *tint <= 0.5, "{tint}"); + assert_eq!(*color, ink.tinted(*tint / 0.5), "the color is the swatch at the face's tint"); + } + other => panic!("the face keeps its swatch: {other:?}"), + } + if let Some(shadow) = fills.next() { + assert!(matches!(shadow.paint.color(), Some(Color::Gray { .. })), "{:?}", shadow.paint); + assert_eq!((shadow.blend, shadow.overprint), (vectorcraft_doc::color::BlendMode::Multiply, true)); + darkened += 1; + } + } + assert!(darkened > 0, "faces turned from the light are darkened"); + // Off, and with a custom shading color, the faces are process mixes again. + for params in [json!({}), json!({"preserveSpotColors": true, "shadingColor": "custom", "shadingCustom": "#336699"})] { + let art = spot(params.clone()); + let linked = faces(&art) + .iter() + .filter(|f| { + f.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if matches!(f.paint, Paint::Solid { swatch: Some(_), .. }))) + }) + .count(); + assert!(linked < faces(&art).len(), "{params}: shaded faces lose the swatch"); + } + } + + /// 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(); @@ -207,6 +288,7 @@ mod tests { (json!({"rotationY": -181}), "`rotationY` must be between -180 and 180"), (json!({"blendSteps": 2.5}), "`blendSteps` must be a whole number"), (json!({"lightBehind": 1}), "`lightBehind` must be true or false"), + (json!({"preserveSpotColors": "on"}), "`preserveSpotColors` must be true or false"), (json!({"surface": "glossy"}), "`surface` must be one of"), (json!({"shadingColor": "white"}), "`shadingColor` must be one of"), (json!({"shadingCustom": "red"}), "`shadingCustom` must be a #rrggbb color"), 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 ac9de02cad..19b134f53b 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -7,7 +7,9 @@ use vectorcraft_doc::color::{BlendMode, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId, NodeKind, OpacityMask}; use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect, Vec2}; use vectorcraft_pathops::BoolOp; -use vectorcraft_three_d::{Bevel, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, MeshedSolid, PlanarFace, View}; +use vectorcraft_three_d::{ + Bevel, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, MeshedSolid, PlanarFace, SolidFaces, View, +}; #[cfg(test)] use vectorcraft_doc::color::Color; @@ -34,7 +36,7 @@ pub use graphics::{ pub(crate) mod shadow; pub(crate) mod wireframe; -pub use wireframe::three_d_wireframe_in; +pub use wireframe::{RENDER, RENDER_MODES, renders_wireframe, three_d_wireframe_in}; pub const EXTRUDE: &str = "threeD.extrude"; pub const INFLATE: &str = "threeD.inflate"; @@ -100,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 @@ -223,6 +240,10 @@ pub(crate) fn solid_paint_sources(n: &Node) -> (Vec>, Ve } fn facets(id: &str, path: &PathData, rule: FillRule, bounds: Rect, p: &Value) -> Result, String> { + #[cfg(test)] + if !is_plane(id) { + SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1)); + } let view = view_options(p); match id { EXTRUDE => vectorcraft_three_d::extrude(path, rule, bounds, extrude_options(p), view), @@ -232,6 +253,30 @@ fn facets(id: &str, path: &PathData, rule: FillRule, bounds: Rect, p: &Value) -> } } +/// [`facets`], and with `cast` for Extrude & Bevel or Rotate the faces the solid's shadow is cast +/// from, from the same build. Inflate's solids are built together ([`built_solids_cast`]), and the +/// classic effects cast no shadow: they keep no faces. +fn facets_and_faces( + id: &str, + path: &PathData, + rule: FillRule, + bounds: Rect, + p: &Value, + cast: bool, +) -> Result<(Vec, Option), String> { + let view = view_options(p); + #[cfg(test)] + if cast && id == EXTRUDE { + SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1)); + } + let built = match id { + EXTRUDE if cast => vectorcraft_three_d::extrude_shadowed(path, rule, bounds, extrude_options(p), view), + ROTATE if cast => vectorcraft_three_d::plane_shadowed(path, rule, bounds, view), + _ => return facets(id, path, rule, bounds, p).map(|f| (f, None)), + }; + built.map(|(f, faces)| (f, Some(faces))) +} + /// Check solid `id`'s parameter values `p` alone: the part of [`validate_solid`] that does not /// need the object. fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> { @@ -244,6 +289,7 @@ fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> { crate::lighting::validate(p)?; shadow::validate(p)?; graphics::validate(id, p)?; + wireframe::validate_render(id, p)?; if let Some(v) = p.get("bevel") && !v.as_str().is_some_and(|s| s == "none" || BevelShape::parse(s).is_some()) { @@ -292,9 +338,8 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: let mut shapes = members(n, label)?; reshape_members(n, before, &mut shapes); let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?; - shapes.iter().try_for_each(|s| facets(id, &s.path, s.rule, b, p).map(|_| ()))?; - check_solids(id, p, &shapes)?; - return cast_shadow(id, p, &shapes).map(|_| ()); + check_profiles(id, p, &shapes, b)?; + return check_solids(id, p, &shapes); } let (path, rule) = object_profile(n, label)?; let anchors = || format!("{label} requires a shape with at least two anchors"); @@ -309,19 +354,70 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: None => (geometry(&path, before, &ctx), solid_paints(n)), }; let b = path.bounds().ok_or_else(anchors)?; - facets(id, &path, rule, b, p)?; let shapes = [Profile { path, rule, items, opacity: 1.0, scopes: vec![] }]; - check_solids(id, p, &shapes)?; - cast_shadow(id, p, &shapes).map(|_| ()) + check_profiles(id, p, &shapes, b)?; + check_solids(id, p, &shapes) +} + +/// Does 3D effect `id` with parameters `p` cast a shadow: is it Extrude & Bevel, Inflate or Rotate +/// with Shadows on, shaded? In wireframe mode no shadow is drawn, and none is checked. +fn casts_shadow(id: &str, p: &Value) -> bool { + !is_classic_three_d(id) && shadow::options(p).is_some() && !wireframe::wireframe_params(id, p) +} + +/// Does `item` of a shape with opacity `member` paint anything, and so cast a shadow? +fn visible(item: &AppearanceItem, member: f32) -> bool { + paint_of(item, member).1 > 0.0 +} + +/// Do the solids 3D effect `id` with parameters `p` builds from the profiles of `shapes` about `b` +/// build? Only the profiles no solid of [`check_solids`] is built from are built here: for Rotate +/// every shape's, except with its shadow cast that of a shape with a visible fill, whose plane is +/// the fill's; for Extrude & Bevel and Inflate the profile of a shape with no fill, whose solids +/// are its strokes' outlines or none. A filled shape's profile is its fill's solid, which +/// [`check_solids`] builds once, about the bounds the effect draws it about. +fn check_profiles(id: &str, p: &Value, shapes: &[Profile], b: Rect) -> Result<(), String> { + let cast = casts_shadow(id, p); + let fill = |s: &Profile| s.items.iter().any(|i| matches!(i, AppearanceItem::Fill(_)) && (!is_plane(id) || visible(i, s.opacity))); + shapes.iter().filter(|s| if is_plane(id) { !(cast && fill(s)) } else { !fill(s) }).try_for_each(|s| facets(id, &s.path, s.rule, b, p).map(|_| ())) } /// Do the solids 3D effect `id` with parameters `p` builds from the fills and strokes of `shapes` -/// fit, each on its own and all of them together ([`built_solids`])? Rotate's planes are not -/// counted. +/// fit, each on its own and all of them together ([`built_solids`]), and with its shadow cast, does +/// the shadow fit? The shadow is cast from the faces those same builds kept ([`cast_built`]), as +/// [`art_for`] casts it: Extrude & Bevel and Inflate build each solid once, and Rotate builds the +/// plane of each visible fill and stroke once. Rotate's planes are not counted, and without its +/// shadow Rotate builds no plane here. fn check_solids(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> { - let Some(b) = union_bounds(shapes).filter(|_| !is_plane(id)) else { return Ok(()) }; + let Some(b) = union_bounds(shapes) else { return Ok(()) }; + let cast = casts_shadow(id, p); + if is_plane(id) { + if !cast { + return Ok(()); + } + let mut built = vec![]; + for s in shapes { + for item in &s.items { + if !visible(item, s.opacity) { + built.push(None); + continue; + } + let (area, rule) = region(&s.path, s.rule, item); + #[cfg(test)] + SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); + built.push(facets_and_faces(ROTATE, &area, rule, b, p, true)?.1); + } + } + return cast_built(id, p, shapes, built).map(|_| ()); + } let (parts, bounds) = solid_parts(shapes, b); - built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ())) + if !cast { + return built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ())); + } + let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true) + .map(|r| r.map(|solid| solid.and_then(|(_, faces)| faces))) + .collect::, String>>()?; + cast_built(id, p, shapes, built).map(|_| ()) } /// [`profile`], or the error a command reports for object `n`: type with no outlines to build from @@ -544,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); @@ -553,16 +651,14 @@ 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() .map(|face| { // Adjacent facets, antialiased on their own, would leave hairline seams: a narrow - // stroke of the same paint closes them. No wider than the facet is thick, though: seen - // at a grazing angle a facet can be thinner than the stroke, and its stroke would then - // paint over its neighbours. - let seam = (face.thickness() / 2.0).clamp(0.05, 0.75); + // stroke of the same paint closes them ([`seam_width`]). + let seam = seam_width(&face); if let Some(g) = face.rgb_gradient && (paint.color().is_some() || matches!(paint, Paint::Gradient(_))) { @@ -592,6 +688,18 @@ 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. +pub(crate) fn seam_width(face: &Facet) -> f64 { + (face.thickness() / 2.0).clamp(0.05, 0.75) +} + /// Is a surface of `facets` in `paint` one composite of all its facets when [`surface`] draws it /// whole: a solid color under colored lights with smooth shading? fn composites_facets(facets: &[Facet], paint: &Paint, colored: bool) -> bool { @@ -614,11 +722,26 @@ fn paint_ref(item: &AppearanceItem) -> &Paint { } } -/// Paint copies `surface` makes for `facets`: two per facet (fill and seam stroke), six when colored -/// lights give each facet derived paints (`lighting::solid_surface`, or `lighting::facet_art` for -/// each face). +/// Are `facets` drawn over an underlay of themselves ([`crate::lighting::sealed`], +/// [`crate::lighting::solid_surface`])? Under colored lights, when any facet takes a smooth light +/// ramp. +fn underlaid(facets: &[Facet], colored: bool) -> bool { + colored && facets.iter().any(|f| f.rgb_gradient.is_some()) +} + +/// The most paint copies `surface` makes for one facet ([`facet_copies`]). +const MAX_FACET_COPIES: usize = 12; + +/// Paint copies `surface` makes for `facets`: two per facet (fill and seam stroke), twice that when +/// the facets lie over an underlay of themselves, and [`MAX_FACET_COPIES`] when colored lights also +/// give each facet derived paints in three channels (`lighting::solid_surface`). fn facet_copies(facets: &[Facet], paint: &Paint, colored: bool) -> usize { - facets.len().saturating_mul(if composites_facets(facets, paint, colored) { 6 } else { 2 }) + let per_facet = match (underlaid(facets, colored), paint.color().is_some()) { + (true, true) => MAX_FACET_COPIES, + (true, false) => 4, + (false, _) => 2, + }; + facets.len().saturating_mul(per_facet) } /// The area `item` paints on `path`, and the rule that fills it: the path itself for a fill, the @@ -657,7 +780,13 @@ fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec>, Rect) { #[cfg(test)] thread_local! { /// How many solids [`built_solids`] and [`meshes_for`] have built on this thread, for the tests. - static SOLIDS_BUILT: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Rotate's planes drawn, the solids built to cast a shadow ([`cast_shadow`]) and Revolve's + /// surfaces count too. + pub(crate) static SOLIDS_BUILT: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How many Extrude & Bevel (Classic included) and Inflate solids [`facets`] and + /// [`built_solids`] have built on this thread, for the tests. The solids built to cast a shadow + /// ([`cast_shadow`]) count too. + static SOLID_GEOMETRY_BUILT: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// The solids Extrude & Bevel (Classic included) or Inflate `id` with parameters `p` builds from @@ -673,10 +802,35 @@ fn built_solids<'a>( bounds: Rect, limit: usize, ) -> impl Iterator>, String>> + 'a { + built_solids_cast(id, p, parts, bounds, limit, false).map(|r| r.map(|s| s.map(|(f, _)| f))) +} + +/// One solid's facets and, when its shadow is cast, the faces it is cast from. +type CastingSolid = (Vec, Option); + +/// The surfaces of an object's solids, and the faces each solid kept for its shadow +/// ([`surfaces_for`]). +type SurfacesAndFaces = (Vec>, Vec>); + +/// [`built_solids`], and with `cast` for Extrude & Bevel or Inflate each solid's faces its shadow +/// is cast from, from the same build ([`SolidFaces`]). +fn built_solids_cast<'a>( + id: &'a str, + p: &'a Value, + parts: &'a [Part<'a>], + bounds: Rect, + limit: usize, + cast: bool, +) -> impl Iterator, String>> + 'a { // Inflate's eye is placed for every puff together, as far away as the highest needs. - let mut inflated = (id == INFLATE).then(|| { + let mut inflated = (id == INFLATE).then(|| -> Box>> { let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect(); - vectorcraft_three_d::inflate_each(&shapes, bounds, inflate_options(p), view_options(p)) + let (o, view) = (inflate_options(p), view_options(p)); + if cast { + Box::new(vectorcraft_three_d::inflate_shadowed(&shapes, bounds, o, view).map(|r| r.map(|(f, faces)| (f, Some(faces))))) + } else { + Box::new(vectorcraft_three_d::inflate_each(&shapes, bounds, o, view).map(|r| r.map(|f| (f, None)))) + } }); let mut kept = 0usize; let mut ended = false; @@ -687,12 +841,16 @@ fn built_solids<'a>( #[cfg(test)] SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); let built = match inflated.as_mut() { - Some(each) => each.next().unwrap_or_else(|| Ok(vec![])), - None => facets(id, area, *rule, bounds, p), + Some(each) => { + #[cfg(test)] + SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1)); + each.next().unwrap_or_else(|| Ok((vec![], None))) + } + None => facets_and_faces(id, area, *rule, bounds, p, cast), }; let result = match built { Ok(f) => { - kept = kept.saturating_add(f.len()); + kept = kept.saturating_add(f.0.len()); if kept > limit { Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string()) } else { Ok(Some(f)) } } Err(_) if matches!(item, AppearanceItem::Stroke(_)) => Ok(None), @@ -804,14 +962,14 @@ fn rects_overlap(a: Rect, b: Rect) -> bool { /// How many faces [`cut_stroke_faces`] may add to solids painted by `items` that hold `faces` faces /// and whose paint copies take `paint_bytes` so far: as many as keep the faces within -/// [`MAX_OBJECT_FACES`] and the copies within the allowance, each added face counted as six copies -/// of the costliest stroke's paint. +/// [`MAX_OBJECT_FACES`] and the copies within the allowance, each added face counted as +/// [`MAX_FACET_COPIES`] copies of the costliest stroke's paint. fn cut_room<'a>(items: impl Iterator, faces: usize, paint_bytes: usize) -> usize { let per_face = items .filter(|item| matches!(item, AppearanceItem::Stroke(_))) .map(|item| { let mut copies = 0usize; - crate::revolve::paint_copies_add(&mut copies, 6, paint_ref(item)); + crate::revolve::paint_copies_add(&mut copies, MAX_FACET_COPIES, paint_ref(item)); copies }) .max() @@ -1261,6 +1419,35 @@ fn draw_order(faces: &[Placed], sealed: bool) -> Vec { local_order(faces, order) } +/// The order, back to front, of the faces of one or more Revolve surfaces `faces`, given back to +/// front by depth: each face's polygon on the drawing, its plane and its depth. When two +/// overlapping faces are drawn the wrong way round for their depths where they overlap, every pair +/// of overlapping faces with a convex polygon and a plane goes in the order of its depths there, +/// the face nearer the viewer after the other ([`local_order`]), and each step draws the face that +/// comes first in the given order of those whose faces before are drawn, so a face without a plane +/// or a convex polygon can also move. Otherwise the order given. +pub(crate) fn surface_order<'a>(faces: impl IntoIterator, f64)>) -> Vec { + let placed: Vec = faces + .into_iter() + .map(|(points, plane, depth)| { + let local = plane.is_some() && convex(points).is_some(); + // Every face counts as one of a stroke's on one shape, so each overlapping pair is compared. + Placed { + depth, + side: true, + away: false, + bounds: polygon_bounds(points), + member: 0, + paints: Paints::Other, + outline: if local { points.to_vec() } else { vec![] }, + plane: plane.filter(|_| local), + } + }) + .collect(); + let order = (0..placed.len()).collect(); + local_order(&placed, order) +} + /// `shapes`, the members of group or layer `n`, reshaped by the visible geometry effects `before` /// its 3D effect, about the bounds of all of them. pub(crate) fn reshape_members(n: &Node, before: &[Effect], shapes: &mut [Profile]) { @@ -1292,18 +1479,38 @@ type ShadowAndSurfaces = (Vec>, Vec>); /// otherwise each solid is a surface of its own, in that order. A member's opacity mask and /// blending mode, and those of a group it is in, apply to the surfaces of the members it holds /// ([`masked`]). The art comes in two parts: the effect's shadow ([`cast_shadow`], none with it -/// off), to be drawn behind every surface of the object, and the surfaces. +/// off), cast from the faces the solids drawn kept ([`cast_built`]), to be drawn behind every +/// surface of the object, and the surfaces. fn art_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option { - let art = surfaces_for(doc, n, fx, shapes)?; + // In wireframe mode the effect draws the edges of the faces it builds, with no shadow. + if wireframe::renders_wireframe(fx) { + return Some((vec![], wireframe::wire_surfaces(n.id, fx, shapes)?)); + } + let p = crate::merged_params(&fx.id, &fx.params); + let cast = casts_shadow(&fx.id, &p); + let (art, built) = surfaces_for(doc, n, fx, shapes, cast)?; // A shadow past the limits draws the source path, as a solid past them does; commands report // the error ([`validate_solid_in`]). - let shadow = match cast_shadow(&fx.id, &crate::merged_params(&fx.id, &fx.params), shapes).ok()? { + let shadow = if cast { cast_built(&fx.id, &p, shapes, built) } else { Ok(None) }; + let shadow = match shadow.ok()? { Some((caster, settings, cast)) => shadow::scoped_art(n.id, &caster, settings, cast, has_masks(shapes)), None => vec![], }; Some((shadow, art)) } +/// The shadow [`art_for`] draws for effect `fx` on `shapes` behind the surfaces of object `id`: +/// none with the shadow off or in wireframe mode, and an error when it is past the limits. +pub(crate) fn shadow_for(id: NodeId, fx: &Effect, shapes: &[Profile]) -> Result>, String> { + if wireframe::renders_wireframe(fx) { + return Ok(vec![]); + } + Ok(match cast_shadow(&fx.id, &crate::merged_params(&fx.id, &fx.params), shapes)? { + Some((caster, settings, cast)) => shadow::scoped_art(id, &caster, settings, cast, has_masks(shapes)), + None => vec![], + }) +} + /// What the shadow of the solids [`surfaces_for`] builds for effect `id` with parameters `p` on /// `shapes` is cast from, on one plane: the faces of every solid, the shadow's settings and the /// faces of each solid of visible art with its member's scopes and ink. `None` with the shadow @@ -1319,8 +1526,8 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result = vec![]; let ink = |item: &AppearanceItem, member: f32| { let (_, opacity, blend) = paint_of(item, member); @@ -1328,8 +1535,10 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result 0.0) { + for item in s.items.iter().filter(|i| ink(i, s.opacity).casts()) { let (area, rule) = region(&s.path, s.rule, item); + #[cfg(test)] + SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); let faces = caster.plane(&area, rule, b, view)?; cast.push((s.scopes.as_slice(), ink(item, s.opacity), faces)); } @@ -1340,17 +1549,25 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result, String>> = if id == INFLATE { let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect(); - let casts: Vec = inks.iter().map(|i| i.opacity > 0.0).collect(); + let casts: Vec = inks.iter().map(|i| i.casts()).collect(); + #[cfg(test)] + SOLIDS_BUILT.with(|n| n.set(n.get() + shapes.len())); + #[cfg(test)] + SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + casts.iter().filter(|c| **c).count())); caster.inflate(&shapes, &casts, bounds, inflate_options(p), view) } else { let mut added = vec![]; for ((_, _, area, rule, _, _), ink) in parts.iter().zip(&inks) { - added.push(if ink.opacity > 0.0 { caster.extrude(area, *rule, bounds, extrude_options(p), view) } else { Ok(0..0) }); + #[cfg(test)] + SOLIDS_BUILT.with(|n| n.set(n.get() + usize::from(ink.casts()))); + #[cfg(test)] + SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + usize::from(ink.casts()))); + added.push(if ink.casts() { caster.extrude(area, *rule, bounds, extrude_options(p), view) } else { Ok(0..0) }); } added }; for (((item, _, _, _, scopes, _), ink), faces) in parts.iter().zip(inks).zip(added) { - if ink.opacity <= 0.0 { + if !ink.casts() { continue; } // A stroke whose own solid is past the limits is left out; past the shadow's limit for @@ -1366,6 +1583,57 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result(id: &str, p: &Value, shapes: &'a [Profile], built: Vec>) -> Result>, String> { + if id == CLASSIC_EXTRUDE || id == CLASSIC_ROTATE { + return Ok(None); + } + let (Some(settings), Some(b)) = (shadow::options(p), union_bounds(shapes)) else { return Ok(None) }; + let mut caster = vectorcraft_three_d::ShadowCaster::new(); + let mut cast: Vec = vec![]; + let ink = |item: &AppearanceItem, member: f32| { + let (_, opacity, blend) = paint_of(item, member); + shadow::Ink { opacity, blend } + }; + if id == ROTATE { + let items: Vec<(&Profile, &AppearanceItem)> = shapes.iter().flat_map(|s| s.items.iter().map(move |item| (s, item))).collect(); + if items.len() != built.len() { + return cast_shadow(id, p, shapes); + } + for ((s, item), kept) in items.into_iter().zip(built) { + let ink = ink(item, s.opacity); + if !ink.casts() { + continue; + } + let Some(kept) = kept else { continue }; + cast.push((s.scopes.as_slice(), ink, caster.add_solid(kept)?)); + } + return Ok(Some((caster, settings, cast))); + } + let (parts, _) = solid_parts(shapes, b); + if parts.len() != built.len() { + return cast_shadow(id, p, shapes); + } + for ((item, member, _, _, scopes, _), kept) in parts.iter().zip(built) { + let ink = ink(item, *member); + // A fully transparent solid, or a stroke's solid left out of the art, casts nothing. + let Some(kept) = kept.filter(|_| ink.casts()) else { continue }; + // A stroke whose own solid is past the limits is left out; past the shadow's limit for all + // the solids together, the shadow is refused. + let faces = match caster.add_solid(kept) { + Ok(faces) => faces, + Err(e) if matches!(item, AppearanceItem::Stroke(_)) && e != vectorcraft_three_d::TOO_COMPLEX_SHADOW => continue, + Err(e) => return Err(e), + }; + cast.push((*scopes, ink, faces)); + } + Ok(Some((caster, settings, cast))) +} + /// The faces a shadow is cast from, its settings, and the faces of each solid of visible art with /// its member's scopes and ink ([`cast_shadow`]). type Cast<'a> = (vectorcraft_three_d::ShadowCaster, vectorcraft_three_d::Shadow, Vec>); @@ -1424,31 +1692,31 @@ fn masks_surface(paint: &Paint, colored: bool) -> bool { colored && crate::lighting::opaque_paint(paint).1.is_some() } +/// A graphic of [`placed_graphics`]: the index of the first surface of the solids that share it, +/// the index of the surface it is drawn right after, its face and its art. +type Placement = (usize, usize, PlanarFace, Arc); + /// The graphics of the solids `filled` ([`graphic_art`]), each with the index of the surface it is /// drawn right after (the last of those solids holding its face) and its face. Solids in a run -/// with the same opacity and blending mode share their graphics. With `per_member` -/// (a member's opacity mask or blending mode applies to its surfaces) each member's solids get -/// graphics of their own, clipped to that member's caps, so they stay in that member's scopes. -/// All the groups share one limit on the path elements drawn: once it is reached, later groups -/// draw no graphics. -fn placed_graphics( - doc: Option<&Document>, - id: NodeId, - effect: (&str, &Value), - bounds: Rect, - filled: &[Filled], - per_member: bool, -) -> Vec<(usize, PlanarFace, Arc)> { +/// with the same opacity and blending mode share their graphics, one on each face. With +/// `per_member` (a member's opacity mask or blending mode applies to its surfaces) each member's +/// solids get graphics of their own, clipped to that member's caps, so they stay in that member's +/// scopes. All the groups share one limit on the path elements drawn: once it is reached, later +/// groups draw no graphics. +fn placed_graphics(doc: Option<&Document>, id: NodeId, effect: (&str, &Value), bounds: Rect, filled: &[Filled], per_member: bool) -> Vec { let mut groups: Vec> = vec![]; for f in filled { // Solids whose fills or strokes differ in opacity or blending mode get graphics of their - // own, each drawn as its fill or stroke is. A solid whose surface carries an opacity mask - // gets its own too, which takes that mask ([`with_graphics`]). A solid joins only the - // group of the solid before it, so a graphic is never drawn past a solid painted between. - let joins = |first: &Filled| { - (!per_member || first.member == f.member) && first.opacity == f.opacity && first.blend == f.blend && !first.masked && !f.masked + // own, each drawn as its fill or stroke is. One member's solids share their graphics + // whether or not their surfaces carry an opacity mask, and each graphic takes the mask of + // the surface it is drawn after ([`with_graphics`]). Solids of different members share + // them only when neither surface carries a mask. A solid joins only the group of the solid + // before it, so a graphic is never drawn past a solid painted between. + let joins = |g: &&Filled| { + let member = g.member == f.member; + (member || !per_member && !g.masked && !f.masked) && g.opacity == f.opacity && g.blend == f.blend }; - match groups.last_mut().filter(|g| g.first().is_some_and(|first| joins(first))) { + match groups.last_mut().filter(|g| g.iter().all(joins)) { Some(g) => g.push(f), None => groups.push(vec![f]), } @@ -1457,12 +1725,13 @@ fn placed_graphics( let mut elements = 0usize; for group in groups { let caps: Vec<&Facet> = group.iter().flat_map(|f| &f.caps).collect(); + let first = group.first().map_or(0, |f| f.at); let opacity = group.first().map_or(1.0, |f| f.opacity); let blend = group.first().map_or(BlendMode::Normal, |f| f.blend); for (face, mut art) in graphic_art(doc, id, effect, bounds, &caps, opacity, &mut elements) { if let Some(f) = group.iter().rev().find(|f| f.caps.iter().any(|c| c.end == Some(face))) { Arc::make_mut(&mut art).blend = blend; - out.push((f.at, face, art)); + out.push((first, f.at, face, art)); } } } @@ -1474,23 +1743,19 @@ fn placed_graphics( type BuiltSurface<'s> = (Vec, Node, &'s [Scope], Vec>); /// [`with_graphics`] of built surfaces, each drawn whole. -fn whole_surfaces<'s>(surfaces: Vec>, arts: &[(usize, PlanarFace, Arc)]) -> Vec<(&'s [Scope], Arc)> { +fn whole_surfaces<'s>(surfaces: Vec>, arts: &[Placement]) -> Vec<(&'s [Scope], Arc)> { with_graphics(surfaces.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), 0, arts) } /// `surfaces` (those from index `first`) drawn whole, each with its scopes, and the graphics `arts` /// ([`placed_graphics`]) of those surfaces each right after its surface, with that surface's scopes /// and its opacity mask (a gradient's transparency), so a graphic is hidden where its cap is. -fn with_graphics<'s>( - surfaces: Vec<(&'s [Scope], Arc)>, - first: usize, - arts: &[(usize, PlanarFace, Arc)], -) -> Vec<(&'s [Scope], Arc)> { +fn with_graphics<'s>(surfaces: Vec<(&'s [Scope], Arc)>, first: usize, arts: &[Placement]) -> Vec<(&'s [Scope], Arc)> { let mut out = Vec::with_capacity(surfaces.len() + arts.len()); for (k, (scopes, s)) in surfaces.into_iter().enumerate() { let mask = s.extras().mask.clone(); out.push((scopes, s)); - out.extend(arts.iter().filter(|(at, ..)| *at == first + k).map(|(.., art)| { + out.extend(arts.iter().filter(|(_, at, ..)| *at == first + k).map(|(.., art)| { let mut art = art.clone(); if let Some(mask) = &mask { Arc::make_mut(&mut art).extras_mut().mask = Some(mask.clone()); @@ -1507,8 +1772,10 @@ fn seen_ends(f: &[Facet]) -> impl Iterator { } /// [`art_for`] without the shadow: the solids' surfaces, with the graphics mapped onto their planar -/// faces drawn right after the last of the solids' surfaces that holds that face. -fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option>> { +/// faces drawn right after the last of the solids' surfaces that holds that face. With `cast`, each +/// solid built also keeps the faces its shadow is cast from, from the same build, in the order the +/// solids are built ([`cast_built`]); `None` for a stroke's solid left out of the art. +fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile], cast: bool) -> Option { let b = union_bounds(shapes)?; let p = crate::merged_params(&fx.id, &fx.params); let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE; @@ -1523,11 +1790,15 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile // the centre of theirs), so they stay together. let mut out = vec![]; let mut filled = vec![]; + let mut built = vec![]; for (member, s) in shapes.iter().enumerate() { for item in &s.items { let (paint, opacity, blend) = paint_of(item, s.opacity); let (area, rule) = region(&s.path, s.rule, item); - let f = facets(ROTATE, &area, rule, b, &p).ok()?; + #[cfg(test)] + SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); + let (f, faces) = facets_and_faces(ROTATE, &area, rule, b, &p, cast).ok()?; + built.push(faces); if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, &paint, colored), &paint) { return None; } @@ -1544,19 +1815,23 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile } let arts = placed_graphics(doc, n.id, (ROTATE, &p), b, &filled, masks); let out = with_graphics(out, 0, &arts); - return Some(if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() }); + return Some((if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() }, built)); } let (parts, bounds) = solid_parts(shapes, b); let mut solids = vec![]; - for ((item, opacity, _, _, scopes, member), f) in parts.iter().zip(built_solids(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES)) { + let mut built = vec![]; + for ((item, opacity, _, _, scopes, member), f) in parts.iter().zip(built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast)) { let item: &AppearanceItem = item; match f { - Ok(Some(f)) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => { + Ok(Some((f, _))) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => { return None; } - Ok(Some(f)) => solids.push((item, *opacity, *scopes, f, *member)), + Ok(Some((f, faces))) => { + solids.push((item, *opacity, *scopes, f, *member)); + built.push(faces); + } // A stroke's outline past the limits is left out; the fill's solid still draws. - Ok(None) => {} + Ok(None) => built.push(None), // A loaded file or a shape edited past the limits (its own, or those of the object's // solids together) keeps drawing its source path instead of failing the frame; // commands validate the same evaluator and report its errors. @@ -1636,6 +1911,10 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile let split = split && solids.iter().filter(|(item, _, _, f, _)| composite(item, f)).map(|(.., f, _)| f.len()).sum::() <= MAX_FACE_COMPOSITES; let members: Vec = solids.iter().map(|s| s.4).collect(); + // Which surfaces lie over an underlay of their facets, in one order or whole + // ([`in_one_order`], [`underlaid_surface`]). + let seals: Vec = solids.iter().map(|(.., f, _)| underlaid(f, colored)).collect(); + let seal = |range: std::ops::Range| seals.get(range).is_some_and(|s| s.iter().any(|s| *s)); let surfaces: Vec = solids .into_iter() .map(|(item, member, scopes, f, shape)| { @@ -1671,19 +1950,37 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile run.push(s); } let flat = run.iter().all(|s| plain(s) && s.1.opacity >= 1.0 && s.1.blend == BlendMode::Normal && s.1.extras().mask.is_none()); + let range = first..first + run.len(); if ordered(member) && flat { let scopes = run.first().map_or(&[][..], |s| s.2); - out.push((scopes, Arc::new(Node::group(n.id, in_one_order(n.id, run, first, &arts, sealed))))); + let seals = seals.get(range).unwrap_or_default(); + out.push((scopes, Arc::new(Node::group(n.id, in_one_order(n.id, run, first, &arts, sealed, seals))))); } else { - out.extend(with_graphics(run.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), first, &arts)); + let run = run.into_iter().zip(range).map(|((_, s, scopes, _), k)| (scopes, Arc::new(underlaid_surface(n.id, s, seal(k..k + 1))))); + out.extend(with_graphics(run.collect(), first, &arts)); } } - return Some(masked(n.id, out)); + return Some((masked(n.id, out), built)); } if !opaque || !surfaces.iter().all(plain) { - return Some(whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect()); + let surfaces = + surfaces.into_iter().enumerate().map(|(k, (d, s, scopes, e))| (d, underlaid_surface(n.id, s, seal(k..k + 1)), scopes, e)).collect(); + return Some((whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect(), built)); } - Some(vec![Arc::new(Node::group(n.id, in_one_order(n.id, surfaces, 0, &arts, sealed)))]) + Some((vec![Arc::new(Node::group(n.id, in_one_order(n.id, surfaces, 0, &arts, sealed, &seals)))], built)) +} + +/// A plain `surface` ([`surface`]: a group of its facets) over an underlay of its facets when +/// `seal`, keeping the surface's opacity, blend mode and opacity mask. +fn underlaid_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(|| crate::lighting::sealed(id, children)).flatten() else { return surface }; + out.opacity = surface.opacity; + out.blend = surface.blend; + if let Some(mask) = surface.extras().mask.clone() { + out.extras_mut().mask = Some(mask); + } + out } /// The faces of `surfaces` (plain groups of their faces, [`surfaces_for`]'s from index `first`) in @@ -1691,9 +1988,11 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile /// surfaces right after the last face it is drawn on, of the surfaces that share it. A surface in a gradient with transparent stops /// carries an opacity mask: its faces go in runs ([`in_runs`]), each carrying the mask, and each of /// its graphics carries the mask too ([`with_graphics`]), so a graphic is hidden where its cap is. -fn in_one_order(id: NodeId, surfaces: Vec>, first: usize, arts: &[(usize, PlanarFace, Arc)], sealed: bool) -> Vec> { +/// The faces of the surfaces that `seals` marks lie over underlays of themselves +/// ([`underlaid_runs`], [`underlaid_surface`]). +fn in_one_order(id: NodeId, surfaces: Vec>, first: usize, arts: &[Placement], sealed: bool, seals: &[bool]) -> Vec> { let masks: Vec>> = surfaces.iter().map(|(_, s, _, _)| s.extras().mask.clone()).collect(); - let arts: Vec<&(usize, PlanarFace, Arc)> = arts.iter().filter(|(at, ..)| (first..first + surfaces.len()).contains(at)).collect(); + let arts: Vec<&Placement> = arts.iter().filter(|(_, at, ..)| (first..first + surfaces.len()).contains(at)).collect(); let (mut placed, mut faces, mut ends) = (vec![], vec![], vec![]); for (surface, (depths, s, _, e)) in surfaces.into_iter().enumerate() { if let NodeKind::Group { children, .. } = s.kind { @@ -1704,24 +2003,18 @@ fn in_one_order(id: NodeId, surfaces: Vec>, first: usize, arts: } let order = draw_order(&placed, sealed); // Each graphic goes right after the last of the faces it is drawn on, among the surfaces that - // share it ([`placed_graphics`]): a masked surface's own, or else the run of surfaces without a - // mask that ends at its surface. + // share it ([`placed_graphics`]): those from the first of them to its own. let last: Vec> = arts .iter() - .map(|(at, face, _)| { - let at = at - first; - let from = if masks.get(at).is_some_and(Option::is_some) { - at - } else { - masks.get(..at).and_then(|before| before.iter().rposition(Option::is_some)).map_or(0, |k| k + 1) - }; + .map(|(from, at, face, _)| { + let (from, at) = (from.saturating_sub(first), at - first); order.iter().rposition(|k| ends.get(*k).copied().flatten().is_some_and(|(surface, end)| end == *face && (from..=at).contains(&surface))) }) .collect(); let mut drawn: Vec<(usize, Arc)> = Vec::with_capacity(order.len() + arts.len()); for (at, k) in order.into_iter().enumerate() { drawn.extend(faces.get_mut(k).and_then(Option::take)); - drawn.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (surface, .., art))| { + drawn.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (_, surface, _, art))| { let mut art = art.clone(); if let Some(mask) = masks.get(surface - first).cloned().flatten() { Arc::make_mut(&mut art).extras_mut().mask = Some(mask); @@ -1730,7 +2023,46 @@ fn in_one_order(id: NodeId, surfaces: Vec>, first: usize, arts: (masks.len(), art) })); } - if masks.iter().any(Option::is_some) { in_runs(id, drawn, &masks) } else { drawn.into_iter().map(|(_, face)| face).collect() } + let takes_underlay = |surface: usize| seals.get(surface) == Some(&true); + if masks.iter().any(Option::is_some) { + // The faces of a surface without a mask are sealed run by run before the masked surfaces' + // faces go in runs of their own, each holding one surface's faces, sealed with its mask. + let unmasked = underlaid_runs(id, drawn, |s| takes_underlay(s) && masks.get(s).is_some_and(Option::is_none)); + return in_runs(id, unmasked, &masks) + .into_iter() + .map(|run| match &run.kind { + NodeKind::Group { clip: false, .. } if seals.iter().any(|s| *s) && run.extras().mask.is_some() => { + Arc::new(underlaid_surface(id, (*run).clone(), true)) + } + _ => run, + }) + .collect(); + } + underlaid_runs(id, drawn, takes_underlay).into_iter().map(|(_, face)| face).collect() +} + +/// `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, clipped to their +/// outline ([`crate::lighting::sealed`]), so no underlay reaches under another surface's faces or a +/// graphic drawn between them. A sealed run keeps its surface's index. +fn underlaid_runs(id: NodeId, faces: Vec<(usize, Arc)>, seal: impl Fn(usize) -> bool) -> Vec<(usize, Arc)> { + 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(|| crate::lighting::sealed(id, &run)).flatten() { + Some(sealed) => { + out.push((surface, Arc::new(sealed))); + run.clear(); + } + None => out.extend(run.drain(..).map(|face| (surface, face))), + } + } + out } /// `faces` in their back-to-front order, each with the index of its surface, where some surfaces @@ -1845,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() }; @@ -2178,3 +2514,6 @@ mod tests_sources; #[cfg(test)] mod tests_shadow; + +#[cfg(test)] +mod tests_revolve_order; diff --git a/crates/effects/src/solids/classic.rs b/crates/effects/src/solids/classic.rs index 23d8d0ffad..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, @@ -102,7 +102,7 @@ const RANGES: [(&str, f64, f64, bool); 13] = [ ("blendSteps", 1.0, 256.0, true), ]; -const FLAGS: [&str; 4] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces"]; +const FLAGS: [&str; 5] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces", "preserveSpotColors"]; /// Check Extrude & Bevel (Classic)'s parameters `p` (its defaults filled in): every key is one of /// its parameters, numbers are in range, flags are true or false, and `surface`, `shadingColor` and @@ -127,7 +127,7 @@ const ROTATE_RANGES: [(&str, f64, f64, bool); 9] = [ /// Check Rotate (Classic)'s parameters `p` (its defaults filled in) as [`validate`] checks Extrude & /// Bevel (Classic)'s, with `surface` No Shading or Diffuse only. pub fn validate_rotate(p: &Value) -> Result<(), String> { - validate_classic(CLASSIC_ROTATE, p, &ROTATE_RANGES, &["lightBehind"])?; + validate_classic(CLASSIC_ROTATE, p, &ROTATE_RANGES, &["lightBehind", "preserveSpotColors"])?; if p.get("surface").is_some_and(|v| !v.as_str().is_some_and(|s| ROTATE_SURFACES.contains(&s))) { return Err(format!("`surface` must be one of {}", ROTATE_SURFACES.join(", "))); } @@ -192,16 +192,83 @@ fn shaded(c: Color, tone: f64, spec: f64, shade: Option) -> Color { Color::rgb(r, g, b) } +/// Whether Preserve Spot Colors applies with parameters `p`: `preserveSpotColors` is on and the +/// shading color is not Custom, which cannot keep a spot color. +fn preserves_spot_colors(p: &Value) -> bool { + flag(p, "preserveSpotColors", false) && text(p, "shadingColor", "black") != "custom" +} + +/// 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 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() { + 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 { + if classic_shading(p).surface == ClassicSurface::Wireframe { WIRE } else { super::seam_width(face) } +} + /// 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. 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() @@ -213,7 +280,11 @@ 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 = (face.thickness() / 2.0).clamp(0.05, 0.75); + 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. @@ -223,6 +294,10 @@ pub(crate) fn surface(n: &Node, facets: Vec, source: &Paint, opacity: f32 AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam)), ] } + // Preserve Spot Colors: a color linked to a swatch stays a tint of that swatch. + Some(_) if preserve && matches!(paint, Paint::Solid { swatch: Some(_), .. }) && !paint.is_registration() => { + linked_face(paint, tone, spec, shade, seam) + } Some(c) => { let fill = Paint::solid(shaded(c, tone, spec, shade)); vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(fill, seam))] diff --git a/crates/effects/src/solids/shadow.rs b/crates/effects/src/solids/shadow.rs index 3906ac2d3c..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), }) } @@ -50,9 +56,23 @@ pub(crate) struct Ink { pub(crate) blend: BlendMode, } +impl Ink { + /// Whether art in this ink casts part of a shadow ([`casts`]). + pub(crate) fn casts(self) -> bool { + casts(self.opacity) + } +} + +/// Whether art at `opacity` casts part of a shadow: its opacity is a finite number above zero. +/// Art at zero, negative, NaN or infinite opacity casts nothing. +pub(crate) fn casts(opacity: f32) -> bool { + opacity.is_finite() && opacity > 0.0 +} + /// 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); @@ -65,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 eb9e81bbc0..378299d514 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -1,5 +1,5 @@ use serde_json::json; -use vectorcraft_doc::{Document, NodeId, StrokeLayer}; +use vectorcraft_doc::{Document, FillLayer, NodeId, StrokeLayer}; use vectorcraft_geom::{Affine, BezPath, Point, Shape}; use super::*; @@ -535,14 +535,53 @@ fn a_colored_inflate_in_gradients_draws_its_faces_in_one_order() { assert_eq!(drawn(&solid, Some(colored)).0, 1); } +/// The faces `run` stands for: a run of faces over an underlay of themselves ([`crate::lighting::sealed`]: +/// a clip and a group of the underlay's copies followed by the faces) gives its faces, any other +/// node gives itself. +fn unsealed(run: &Arc) -> Vec> { + if let NodeKind::Group { clip: true, children } = &run.kind + && let [clip, inner] = children.as_slice() + && matches!(clip.kind, NodeKind::Path { .. }) + && let NodeKind::Group { clip: false, children: kids } = &inner.kind + && !kids.is_empty() + && kids.len() % 2 == 0 + { + let (under, faces) = kids.split_at(kids.len() / 2); + let underlay = |k: &Arc| match &k.kind { + NodeKind::Group { clip, .. } => *clip, + _ => k.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.width == crate::lighting::UNDERLAY_SEAM)), + }; + if under.first().is_some_and(underlay) { + return faces.to_vec(); + } + } + vec![run.clone()] +} + +/// The bounds of every face under `n`, a sealed run's faces one by one ([`unsealed`]). +fn face_bounds_under(n: &Arc, out: &mut Vec) { + let faces = unsealed(n); + if faces.len() != 1 || !Arc::ptr_eq(&faces[0], n) { + out.extend(faces.iter().map(|f| drawn_face_bounds(f))); + return; + } + if let NodeKind::Group { clip: true, .. } = &n.kind { + out.push(drawn_face_bounds(n)); + } + for child in n.children().into_iter().flatten() { + face_bounds_under(child, out); + } +} + /// The bounds of face `f` of 3D art: its path's, or for a clipped colored composite -/// ([`crate::lighting::facet_art`]) its color cover's, which is the face's bounds grown by 1 pt. +/// ([`crate::lighting::facet_art`]) its color cover's, which is the face's bounds grown by 2 pt (a +/// point past the seam and half the underlay's seam). fn drawn_face_bounds(f: &Node) -> Rect { match &f.kind { NodeKind::Path { .. } => f.path_data().and_then(PathData::bounds).unwrap(), NodeKind::Group { clip: true, children } => { let cover = &children[1].children().unwrap()[0]; - cover.path_data().and_then(PathData::bounds).unwrap().inflate(-1.0, -1.0) + cover.path_data().and_then(PathData::bounds).unwrap().inflate(-2.0, -2.0) } _ => panic!("a face is a path or a clipped composite"), } @@ -587,7 +626,7 @@ fn colored_solid_fills_and_strokes_share_face_depth_order() { let art = solid_art(&with).unwrap(); let surfaces = art.children().unwrap(); assert_eq!(surfaces.len(), 1, "{what}: one order"); - let faces = surfaces[0].children().unwrap(); + let faces: Vec> = surfaces[0].children().unwrap().iter().flat_map(unsealed).collect(); assert_eq!(faces.len(), parts.len(), "{what}: one face per facet"); for (k, (face, (facet, ..))) in faces.iter().zip(&parts).enumerate() { let (a, b) = (drawn_face_bounds(face), facet.path().bounds().unwrap()); @@ -616,11 +655,9 @@ fn colored_solid_fills_and_strokes_share_face_depth_order() { g.appearance.effects.push(fx(id, params.clone())); let bounds = |art: &Node| { let mut out = vec![]; - art.walk(&mut |n| { - if let NodeKind::Group { clip: true, .. } = &n.kind { - out.push(drawn_face_bounds(n)); - } - }); + for child in art.children().into_iter().flatten() { + face_bounds_under(child, &mut out); + } out }; let (plain, scoped) = (solid_art(&plain).unwrap(), solid_art(&g).unwrap()); @@ -637,6 +674,89 @@ fn colored_solid_fills_and_strokes_share_face_depth_order() { assert!(whole_misdrawn > 0, "whole surfaces show farther faces"); } +/// Under a colored light, the faces of an Inflate in gradients, in one order, lie over underlays +/// run by run: each run of consecutive faces of one surface (the fill's or the dashed stroke's) +/// over an underlay of its own faces, so no underlay reaches under the other surface's faces. +#[test] +fn a_colored_inflate_in_gradients_lies_over_underlays_of_each_surfaces_runs() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let gradient = |c: Color| { + Paint::Gradient(Box::new(GradientPaint::new(Gradient::new( + GradientKind::Linear, + vec![GradientStop::new(0.0, c), GradientStop::new(1.0, Color::WHITE)], + )))) + }; + let mut n = stroked(&letter_c()); + for item in &mut n.appearance.items { + match item { + AppearanceItem::Fill(f) => f.paint = gradient(RED), + AppearanceItem::Stroke(s) => { + s.paint = gradient(BLUE); + s.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false }); + } + } + } + let p = json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60}); + let cut = drawn_parts(&n, INFLATE, &p).len(); + let mut lit = p.clone(); + lit["lights"] = json!([{"color": "#ff8080"}]); + n.appearance.effects.push(fx(INFLATE, lit)); + // Which surface a face belongs to, by the first stop of its paint (a composed face's own paint, + // or a path face's shaded one): red for the fill's, blue for the stroke's. + fn surface_of(face: &Node) -> Option { + let item = match &face.kind { + NodeKind::Path { .. } => face.appearance.items.first()?, + _ => face.children()?.get(1)?.children()?.first()?.appearance.items.first()?, + }; + let Paint::Gradient(g) = item.paint() else { return None }; + let [r, _, b] = g.gradient.stops.first()?.color.to_rgb(); + Some(if r > b { RED } else { BLUE }) + } + // The faces in `order`, and the surface of each run over an underlay, looking into the groups + // that carry a surface's opacity mask. + fn runs(order: &[Arc], faces: &mut usize, surfaces: &mut Vec) { + for child in order { + let NodeKind::Group { children, clip } = &child.kind else { + assert!(surface_of(child).is_some(), "a face"); + *faces += 1; + continue; + }; + if !clip { + assert!(child.extras().mask.is_some(), "a masked run"); + runs(children, faces, surfaces); + continue; + } + // A composed face isolates its colors; a run's faces are not isolated together. + if children[1].isolate { + assert!(surface_of(child).is_some(), "a composed face"); + *faces += 1; + continue; + } + let stack = children[1].children().unwrap(); + let (under, own) = stack.split_at(stack.len() / 2); + assert_eq!(under.len(), own.len(), "one underlay face for each face"); + let colors: Vec<_> = own.iter().map(|f| surface_of(f).unwrap()).collect(); + assert!(colors.iter().all(|c| *c == colors[0]), "a run holds one surface's faces"); + surfaces.push(colors[0]); + *faces += own.len(); + } + } + let (mut faces, mut surfaces) = (0, vec![]); + runs(solid_art(&n).unwrap().children().unwrap()[0].children().unwrap(), &mut faces, &mut surfaces); + assert!(faces >= cut, "{faces} faces, {cut} under a white light, whose cells are not triangulated"); + assert!(surfaces.contains(&RED) && surfaces.contains(&BLUE), "{surfaces:?}"); + // With transparent stops in the fill's gradient, the fill's faces go in masked runs; the + // stroke's faces, without a mask, still lie over underlays of their own runs. + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))) + && let Paint::Gradient(g) = &mut f.paint + { + g.gradient.stops.iter_mut().for_each(|s| s.opacity = 0.5); + } + let (mut faces, mut surfaces) = (0, vec![]); + runs(solid_art(&n).unwrap().children().unwrap()[0].children().unwrap(), &mut faces, &mut surfaces); + assert!(faces >= cut && surfaces.contains(&RED) && surfaces.contains(&BLUE), "{faces} faces, {surfaces:?}"); +} + /// A face of a stroke that leaves gaps passing through the plane of its fill's wall where they /// overlap is cut along the line where their depths meet, into the piece in front of the wall and /// the piece behind it; a face on one side of the wall, another shape's stroke, a covering stroke @@ -724,7 +844,7 @@ fn cutting_stays_within_the_face_limit_and_the_paint_allowance() { let items = stroked(&letter_c()).appearance.items.clone(); let stroke = items.iter().find(|i| matches!(i, AppearanceItem::Stroke(_))).unwrap(); let mut one = 0usize; - crate::revolve::paint_copies_add(&mut one, 6, paint_ref(stroke)); + crate::revolve::paint_copies_add(&mut one, MAX_FACET_COPIES, paint_ref(stroke)); let max = crate::revolve::MAX_PAINT_COPIES; assert_eq!(cut_room(items.iter(), 10, 0), (MAX_OBJECT_FACES - 10).min(max / one)); assert_eq!(cut_room(items.iter(), MAX_OBJECT_FACES + 5, 0), 0); @@ -953,6 +1073,92 @@ fn an_objects_solids_count_their_faces_together() { } } +/// How many Extrude & Bevel and Inflate solids `check` builds, and its result. +fn geometry_builds(check: impl FnOnce() -> Result<(), String>) -> (usize, Result<(), String>) { + SOLID_GEOMETRY_BUILT.with(|b| b.set(0)); + let result = check(); + (SOLID_GEOMETRY_BUILT.with(std::cell::Cell::get), result) +} + +/// The check builds each solid the effect draws once, about the bounds it draws it about: one for +/// a fill and one for each stroke, on an object, on a group's members and on an appearance item, +/// with the shadow on or off. With the shadow on, the shadow is cast from the faces those builds +/// kept, so no solid is built again for it. +#[test] +fn the_check_builds_each_drawn_solid_once() { + for id in [EXTRUDE, CLASSIC_EXTRUDE, INFLATE] { + let n = square_node(); + assert_eq!(geometry_builds(|| validate_solid(&n, id, &json!({}))), (2, Ok(())), "{id}: a fill and a stroke"); + let mut other = square_node(); + other.id = NodeId(2); + let g = Node::group(NodeId(9999), vec![Arc::new(square_node()), Arc::new(other)]); + assert_eq!(geometry_builds(|| validate_solid(&g, id, &json!({}))), (4, Ok(())), "{id}: two members' fills and strokes"); + } + for id in [EXTRUDE, INFLATE] { + let n = square_node(); + assert_eq!(geometry_builds(|| validate_three_d_at(&n, id, &json!({}), (Some(0), 0))), (1, Ok(())), "{id}: on the fill"); + let shadow = json!({"shadow": true}); + assert_eq!(geometry_builds(|| validate_solid(&n, id, &shadow)), (2, Ok(())), "{id}: with the shadow on"); + let mut other = square_node(); + other.id = NodeId(2); + let g = Node::group(NodeId(9999), vec![Arc::new(square_node()), Arc::new(other)]); + assert_eq!(geometry_builds(|| validate_solid(&g, id, &shadow)), (4, Ok(())), "{id}: a group with the shadow on"); + assert_eq!(geometry_builds(|| validate_three_d_at(&n, id, &shadow, (Some(0), 0))), (1, Ok(())), "{id}: the fill with the shadow on"); + } +} + +/// A shape with no fill draws no solid of its profile, so the check builds the profile on its own +/// as well as the strokes' solids, and an unpainted shape's profile alone. +#[test] +fn the_check_builds_the_profile_of_a_shape_with_no_fill() { + for id in [EXTRUDE, CLASSIC_EXTRUDE, INFLATE] { + let mut stroked = square_node(); + stroked.appearance.items.retain(|i| matches!(i, AppearanceItem::Stroke(_))); + assert_eq!(geometry_builds(|| validate_solid(&stroked, id, &json!({}))), (2, Ok(())), "{id}: a stroke alone"); + let mut bare = square_node(); + bare.appearance.items.clear(); + assert_eq!(geometry_builds(|| validate_solid(&bare, id, &json!({}))), (1, Ok(())), "{id}: no paint"); + } +} + +/// A filled shape is checked about the bounds the effect draws its solid about, which take in the +/// strokes beside it. A shape of many small curves is too complex for Extrude & Bevel about the +/// shapes' own bounds, where its curves are sampled more finely, and passes about the bounds of a +/// wide stroke in its group, as its solid draws there. +#[test] +fn the_check_builds_a_filled_shape_about_the_bounds_its_solid_draws_about() { + // 900 curves about (100, 100), each bulging 1 pt out from a side of a polygon 80 pt across. + let corners = 900; + let center = Point::new(100.0, 100.0); + let corner = |k: usize| { + let (s, c) = (k as f64 * std::f64::consts::TAU / corners as f64).sin_cos(); + Point::new(center.x + 40.0 * c, center.y + 40.0 * s) + }; + let mut b = BezPath::new(); + b.move_to(corner(0)); + for k in 0..corners { + let (p0, p3) = (corner(k), corner(k + 1)); + let out = p0.midpoint(p3) - center; + let out = out / out.hypot(); + b.curve_to(p0 + (p3 - p0) / 3.0 + out, p0 + (p3 - p0) * (2.0 / 3.0) + out, p3); + } + b.close_path(); + let filled = Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0)); + let mut line = BezPath::new(); + line.move_to((80.0, 100.0)); + line.line_to((120.0, 100.0)); + let mut wide = Node::path(NodeId(2), PathData::from_bezpath(&line), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2000.0)); + wide.appearance.items.retain(|i| matches!(i, AppearanceItem::Stroke(_))); + let p = json!({"bevel": "rounded", "bevelRepeat": 6}); + let (path, rule) = profile(&filled).unwrap(); + let own = path.bounds().unwrap().union(wide.path_data().unwrap().bounds().unwrap()); + assert_eq!(facets(EXTRUDE, &path, rule, own, &p).map(|_| ()), Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string()), "about its own bounds"); + let mut g = Node::group(NodeId(9999), vec![Arc::new(filled), Arc::new(wide)]); + assert_eq!(validate_solid(&g, EXTRUDE, &p), Ok(())); + g.appearance.effects.push(fx(EXTRUDE, p)); + assert!(solid_art(&g).is_some(), "the solid draws"); +} + /// A convex polygon of `corners` corners about (20,000, 20,000), filled red, with no stroke. fn polygon_node(id: u64, corners: usize) -> Node { let points: Vec = (0..corners) @@ -1553,16 +1759,31 @@ fn a_colored_solid_face_on_its_own_keeps_the_composites_colors() { assert_eq!(one[0], paint, "the paint"); // The composite: its paint cover, then each channel's black backdrop and the face's ramp. let all_fills = fills(&batch); - let ramps: Vec<&Paint> = all_fills.iter().filter(|p| **p != Paint::solid(Color::BLACK)).skip(1).collect(); + let mut ramps: Vec<&Paint> = all_fills.iter().filter(|p| **p != Paint::solid(Color::BLACK)).skip(1).collect(); + // Each channel's ramp is drawn twice, in the underlay and in the facet itself. + ramps.dedup(); assert_eq!(all_fills.first(), Some(&paint)); 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).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`. @@ -1700,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(); @@ -1752,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 @@ -1813,15 +2168,74 @@ fn a_member_in_a_transparent_gradient_keeps_the_shared_face_order() { } } +/// The fills of each face of `art`: the first is the face's paint, a second the shadow over it. +fn face_fills(art: &Node) -> Vec> { + faces(art) + .iter() + .map(|f| { + f.appearance + .items + .iter() + .filter_map(|i| match i { + AppearanceItem::Fill(f) => Some(f.clone()), + AppearanceItem::Stroke(_) => None, + }) + .collect() + }) + .collect() +} + +#[test] +fn classic_preserve_spot_colors_keeps_a_linked_fill_on_every_face() { + let ink = Color::cmyk(0.0, 1.0, 0.0, 0.2); + let art = |params: Value| { + let mut n = classic(params); + n.appearance.items = vec![AppearanceItem::Fill(FillLayer::new(Paint::Solid { color: ink, swatch: Some("Ink".into()), tint: 1.0 }))]; + solid_art(&n).unwrap() + }; + let lit = json!({"preserveSpotColors": true, "highlightIntensity": 100, "highlightSize": 100, "lightHeight": 60}); + let (mut highlighted, mut shaded) = (false, false); + for layers in face_fills(&art(lit)) { + let Paint::Solid { color, swatch: Some(name), tint } = &layers[0].paint else { panic!("the swatch is kept: {layers:?}") }; + assert_eq!(name, "Ink"); + assert_eq!(*color, ink.tinted(*tint), "the color is the swatch at the face's tint"); + highlighted |= *tint < 1.0; + if let Some(shadow) = layers.get(1) { + let Some(Color::Gray { k }) = shadow.paint.color() else { panic!("black shading: {:?}", shadow.paint) }; + assert!(k > 0.0 && k <= 1.0, "{k}"); + assert_eq!((shadow.blend, shadow.overprint, shadow.opacity), (BlendMode::Multiply, true, 1.0)); + shaded = true; + } + assert!(layers.len() <= 2, "{layers:?}"); + } + assert!(highlighted && shaded, "the highlight lowers the tint and the shadow adds black"); + // No shading color: the highlight only, as tints of the swatch. + for layers in face_fills(&art(json!({"preserveSpotColors": true, "shadingColor": "none"}))) { + assert!(matches!(&layers[..], [f] if matches!(&f.paint, Paint::Solid { swatch: Some(_), .. })), "{layers:?}"); + } + // Off, or with a custom shading color, shaded faces are process mixes, as before. + for params in [json!({}), json!({"preserveSpotColors": true, "shadingColor": "custom", "shadingCustom": "#3366cc"})] { + let unlinked = face_fills(&art(params.clone())).iter().filter(|l| matches!(l[0].paint, Paint::Solid { swatch: None, .. })).count(); + assert!(unlinked > 0, "{params}"); + } + // An unlinked fill is shaded as it is with the option off. + let off: Vec<[f32; 3]> = classic_faces(json!({})).iter().map(fill_rgb).collect(); + let on: Vec<[f32; 3]> = classic_faces(json!({"preserveSpotColors": true})).iter().map(fill_rgb).collect(); + assert_eq!(off, on); +} + #[test] fn classic_parameters_are_checked() { let n = classic(json!({})); 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)"), @@ -1832,6 +2246,7 @@ fn classic_parameters_are_checked() { (json!({"highlightSize": "big"}), "`highlightSize` must be a number"), (json!({"cap": "yes"}), "`cap` must be true or false"), (json!({"drawHiddenFaces": 1}), "`drawHiddenFaces` must be true or false"), + (json!({"preserveSpotColors": "yes"}), "`preserveSpotColors` must be true or false"), (json!({"bevel": "fancy"}), "bevel must be none or one of"), (json!({"twist": 10}), "unknown parameter `twist`"), (json!({"lights": []}), "lights must contain one to ten lights"), @@ -1897,17 +2312,19 @@ 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)"), (json!({"lightIntensity": 101}), "`lightIntensity` must be between 0 and 100 (got 101)"), (json!({"blendSteps": 0}), "`blendSteps` must be a whole number between 1 and 256 (got 0)"), (json!({"lightBehind": 1}), "`lightBehind` must be true or false"), + (json!({"preserveSpotColors": null}), "`preserveSpotColors` must be true or false"), (json!({"highlightSize": 50}), "unknown parameter `highlightSize`"), (json!({"drawHiddenFaces": true}), "unknown parameter `drawHiddenFaces`"), (json!({"shadow": true}), "unknown parameter `shadow`"), diff --git a/crates/effects/src/solids/tests_graphics.rs b/crates/effects/src/solids/tests_graphics.rs index e0935a43e7..f0da6b992b 100644 --- a/crates/effects/src/solids/tests_graphics.rs +++ b/crates/effects/src/solids/tests_graphics.rs @@ -617,10 +617,11 @@ fn a_solid_in_a_transparent_gradient_keeps_its_graphic() { }; // The graphic carries the cap's mask, so it is hidden where the gradient is transparent. assert_eq!(masks(&art), vec![true]); - // With an opaque stroke drawn after the fill, the fill's cap keeps a masked graphic of its own - // and the stroke's outline gets an unmasked one. + // With an opaque stroke drawn after the fill, the fill and the stroke share one graphic, drawn + // after the stroke's cap as for a fill without a mask, and it takes the stroke's surface, + // which carries no mask. n.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0))); - assert_eq!(masks(&solid_art_in(Some(&d), &n).unwrap()), vec![true, false]); + assert_eq!(masks(&solid_art_in(Some(&d), &n).unwrap()), vec![false]); } /// The paths of `art`'s faces in drawing order (a face lit by a colored light is a clip group: its @@ -649,23 +650,56 @@ fn face_paths(art: &Node) -> Vec { out } +/// The graphics in `art` (clip groups of solid-color paths), in drawing order: for each, how many +/// faces ([`face_paths`]) are drawn before it, whether it carries an opacity mask, its opacity and +/// its blending mode. +fn graphic_places(art: &Node) -> Vec<(usize, bool, f32, BlendMode)> { + fn walk(n: &Node, faces: &mut usize, out: &mut Vec<(usize, bool, f32, BlendMode)>) { + match &n.kind { + NodeKind::Group { children, clip: true } => { + let graphic = children.get(1).is_some_and(|inner| match &inner.kind { + NodeKind::Group { children: paths, clip: false } => paths.iter().all(|p| { + p.path_data().is_some() + && p.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.paint.color().is_some())) + }), + _ => false, + }); + if graphic { + out.push((*faces, n.extras().mask.is_some(), n.opacity, n.blend)); + } else if children.first().and_then(|c| c.path_data()).is_some() { + *faces += 1; + } + } + NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, faces, out)), + _ => *faces += usize::from(n.path_data().is_some()), + } + } + let mut out = vec![]; + walk(art, &mut 0, &mut out); + out +} + /// A turned solid in a gradient with transparent stops under a colored light, with a dashed stroke /// and a graphic, draws its fill's and its stroke's faces in the one order it draws them in without -/// the graphic, and the graphic keeps the cap's mask and goes after the fill's cap, not the stroke's. +/// the graphic, and draws the graphic once, where it goes in a gradient without transparent stops: +/// after the stroke's cap, without a mask. #[test] fn a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order() { use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; let d = document(); - let mut stop = GradientStop::new(1.0, red()); - stop.opacity = 0.25; - let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop])); - let solid = |graphics: Value| { + // A red gradient whose last stop has opacity `last`. + let gradient = |last: f32| { + let mut stop = GradientStop::new(1.0, red()); + stop.opacity = last; + GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop])) + }; + let solid = |fill: &GradientPaint, graphics: Value| { let mut n = object( EXTRUDE, json!({"rotationX": -20.0, "rotationY": -40.0, "depth": 60.0, "shade": true, "lights": [{"color": "#ff8080"}], "graphics": graphics}), ); if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { - f.paint = Paint::Gradient(Box::new(gradient.clone())); + f.paint = Paint::Gradient(Box::new(fill.clone())); } // A gradient stroke: a solid color under the colored light would be one composite. let blues = Gradient::new( @@ -677,54 +711,76 @@ fn a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order() { n.appearance.items.push(AppearanceItem::Stroke(stroke)); solid_art_in(Some(&d), &n).unwrap() }; - let with = solid(json!([{"symbol": "Mark"}])); - let without = solid(json!([])); + let masked = gradient(0.25); + let with = solid(&masked, json!([{"symbol": "Mark"}])); + let without = solid(&masked, json!([])); assert!(face_paths(&without).len() > 20, "the faces are found"); assert_eq!(face_paths(&with), face_paths(&without), "the faces in one order"); - // The graphic is drawn on the fill's cap and on the stroke's (the clip groups holding the - // symbol's red square); the fill's, whose surface carries the mask, carries it too. - let mut masked = vec![]; - with.walk(&mut |c| { - if let NodeKind::Group { children, clip: true } = &c.kind - && let [_, inner] = children.as_slice() - && let NodeKind::Group { children: paths, clip: false } = &inner.kind - && paths.iter().any(|p| { - p.appearance.items.iter().any(|i| match i { - AppearanceItem::Fill(f) => f.paint.color().is_some_and(|c| c.to_rgb()[1] < 0.1 && c.to_rgb()[0] > 0.3), - AppearanceItem::Stroke(_) => false, - }) - }) - { - masked.push(c.extras().mask.is_some()); - } - }); - masked.sort_unstable(); - assert_eq!(masked, [false, true], "the fill's graphic carries the cap's mask"); - // The fill's graphic goes right after the fill's cap, so the dashes on the cap's edge, drawn - // after it, cover it. Drawn in order: the fill's graphic (the masked clip group), and each face, - // the fill's or the stroke's by its gradient's first stop (red or blue), with its bounds. - let mut drawn: Vec<(&str, Rect)> = vec![]; - with.walk(&mut |c| { - if let NodeKind::Group { children, clip: true } = &c.kind - && c.extras().mask.is_some() - && let Some(bounds) = children.first().and_then(|clip| clip.path_data()).and_then(PathData::bounds) - { - drawn.push(("graphic", bounds)); - } - let first_stop = c.appearance.items.iter().find_map(|i| match i { - AppearanceItem::Fill(f) => match &f.paint { - Paint::Gradient(g) => g.gradient.stops.first().map(|s| s.color.to_rgb()), - _ => None, - }, - AppearanceItem::Stroke(_) => None, - }); - if let (Some(rgb), Some(bounds)) = (first_stop, c.path_data().and_then(PathData::bounds)) { - drawn.push((if rgb[0] > rgb[2] { "fill" } else { "stroke" }, bounds)); - } - }); - let graphic = drawn.iter().position(|(kind, _)| *kind == "graphic").unwrap(); - let covering = |(kind, b): &(&str, Rect)| *kind == "stroke" && b.intersect(drawn[graphic].1).area() > 0.0; - assert!(drawn[graphic..].iter().any(covering), "a dash on the cap's edge is drawn over the fill's graphic"); + let mut mask = false; + with.walk(&mut |c| mask |= c.extras().mask.is_some()); + assert!(mask, "the fill's faces carry the gradient's mask"); + let opaque = solid(&gradient(1.0), json!([{"symbol": "Mark"}])); + assert_eq!(face_paths(&opaque), face_paths(&with)); + let places = graphic_places(&with); + assert_eq!(places.iter().map(|(_, mask, opacity, blend)| (*mask, *opacity, *blend)).collect::>(), [(false, 1.0, BlendMode::Normal)]); + assert_eq!(places, graphic_places(&opaque), "drawn where a fill without a mask draws it"); +} + +/// A plane in a gradient with transparent stops under a colored light draws its graphic with the +/// fill's mask, and with a dashed stroke draws it once, after the stroke, without a mask. +#[test] +fn a_plane_in_a_transparent_gradient_with_a_stroke_draws_its_graphic_once() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let d = document(); + let mut stop = GradientStop::new(1.0, red()); + stop.opacity = 0.25; + let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop])); + let mut n = object(ROTATE, json!({"shade": true, "lights": [{"color": "#ff8080"}], "graphics": [{"symbol": "Mark"}]})); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.paint = Paint::Gradient(Box::new(gradient)); + } + let places = graphic_places(&solid_art_in(Some(&d), &n).unwrap()); + assert_eq!(places.iter().map(|(_, mask, ..)| *mask).collect::>(), [true]); + let mut stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 6.0); + stroke.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false }); + n.appearance.items.push(AppearanceItem::Stroke(stroke)); + let art = solid_art_in(Some(&d), &n).unwrap(); + let places = graphic_places(&art); + assert_eq!(places, [(face_paths(&art).len(), false, 1.0, BlendMode::Normal)], "one graphic, drawn after every face"); +} + +/// Members of a group share a graphic only when neither surface carries an opacity mask, while +/// one member's fill and stroke share theirs. +#[test] +fn members_in_transparent_gradients_keep_graphics_of_their_own() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let d = document(); + let mut stop = GradientStop::new(1.0, red()); + stop.opacity = 0.25; + let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop])))); + let gray = Paint::solid(Color::rgb(0.5, 0.5, 0.5)); + let (left, right) = (Rect::new(0.0, 0.0, 50.0, 100.0), Rect::new(50.0, 0.0, 100.0, 100.0)); + // Whether each graphic drawn on the group of `members` carries an opacity mask, in order. + let masks = |members: Vec| { + let mut group = Node::group(NodeId(3), members.into_iter().map(Arc::new).collect()); + let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": true, "lights": [{"color": "#ff8080"}], "graphics": [{"symbol": "Mark", "scale": 1000.0}]}); + group.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap()); + let mut masks: Vec = graphic_places(&solid_art_in(Some(&d), &group).unwrap()).iter().map(|(_, mask, ..)| *mask).collect(); + masks.sort_unstable(); + masks + }; + assert_eq!(masks(vec![square(1, left, gradient.clone()), square(2, right, gradient.clone())]), [true, true]); + // With a dashed stroke, the first member's fill and stroke share one graphic, without a mask. + let mut stroked = square(1, left, gradient.clone()); + let mut stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 6.0); + stroke.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false }); + stroked.appearance.items.push(AppearanceItem::Stroke(stroke)); + assert_eq!(masks(vec![stroked, square(2, right, gradient.clone())]), [false, true]); + // A member with a gray stroke listed before its fill in the gradient does not share its + // graphic with the gray member after it. + let mut layered = square(1, left, gradient); + layered.appearance.items.insert(0, AppearanceItem::Stroke(StrokeLayer::new(gray.clone(), 6.0))); + assert_eq!(masks(vec![layered, square(2, right, gray)]), [false, true]); } #[test] diff --git a/crates/effects/src/solids/tests_revolve_order.rs b/crates/effects/src/solids/tests_revolve_order.rs new file mode 100644 index 0000000000..96650cf2f8 --- /dev/null +++ b/crates/effects/src/solids/tests_revolve_order.rs @@ -0,0 +1,183 @@ +use serde_json::json; + +use super::*; +use crate::revolve::{CLASSIC_REVOLVE, REVOLVE, revolve_art, revolve_options}; + +/// The first pair of faces `(polygon, plane)`, in the order given, drawn the wrong way round where +/// their polygons overlap: the earlier one nearer the viewer at the middle of the overlap. +fn misordered(faces: &[(Vec, Option)]) -> Option<(usize, usize)> { + for (i, (a, pa)) in faces.iter().enumerate() { + let Some(pa) = pa.filter(|_| convex(a).is_some()) else { continue }; + for (j, (b, pb)) in faces.iter().enumerate().skip(i + 1) { + let Some(pb) = pb else { continue }; + let Some(turn) = convex(b) else { continue }; + if !rects_overlap(polygon_bounds(a), polygon_bounds(b)) { + continue; + } + let Some(mid) = centroid(&clip_convex(a, b, turn)) else { continue }; + let (Some(da), Some(db)) = (pa.depth_at(mid), pb.depth_at(mid)) else { continue }; + if da - db > 1e-6 * (1.0 + da.abs().max(db.abs())) { + return Some((i, j)); + } + } + } + None +} + +/// An open, vase-like profile of straight edges. +fn vase() -> PathData { + let mut b = BezPath::new(); + b.move_to((30.0, 20.0)); + for p in [(90.0, 20.0), (55.0, 65.0), (95.0, 110.0), (30.0, 145.0)] { + b.line_to(p); + } + PathData::from_bezpath(&b) +} + +/// The `k`th of five closed 14 × 20 pt rectangles stepping down and away from the axis, as the +/// dashes of a dashed line's outline do. +fn dash(k: usize) -> PathData { + let (x, y) = (30.0 + 12.0 * k as f64, 20.0 + 26.0 * k as f64); + let mut b = BezPath::new(); + b.move_to((x, y)); + b.line_to((x + 14.0, y)); + b.line_to((x + 14.0, y + 20.0)); + b.line_to((x, y + 20.0)); + b.close_path(); + PathData::from_bezpath(&b) +} + +/// The five [`dash`]es as one compound path. +fn dashes() -> PathData { + PathData::new((0..5).flat_map(|k| dash(k).subpaths).collect()) +} + +/// A tilted three-quarter turn of [`vase`], whose faces sorted by their middles' depths draw a +/// nearer face under a farther one where the two overlap. +fn params() -> Value { + json!({"angle": 270, "offset": 12, "rotationX": -30, "rotationY": 0, "perspectiveAngle": 0, "segments": 24, "cap": true}) +} + +/// A three-quarter turn of [`dashes`], steeply tilted and in wide perspective, whose classic facets +/// sorted by their middles' depths draw a nearer facet under a farther one where the two overlap. +fn classic_params() -> Value { + json!({"angle": 270, "offset": 12, "rotationX": -60, "rotationY": 0, "perspectiveAngle": 80, "cap": true}) +} + +fn node(path: PathData) -> Node { + Node::path(NodeId(1), path, Appearance::basic(Paint::solid(Color::rgb(0.1, 0.7, 0.8)), Paint::None, 0.0)) +} + +/// The faces of `faces` (polygon, plane and outline) in the order `art` draws their outlines. +fn drawn_order(art: &Node, faces: &[(Vec, Option, PathData)]) -> Vec<(Vec, Option)> { + let mut out = vec![]; + art.walk(&mut |n| { + if let Some(path) = n.path_data() + && let Some((points, plane, _)) = faces.iter().find(|(.., outline)| outline == path) + { + out.push((points.clone(), *plane)); + } + }); + out +} + +/// Of a tilted, revolved vase, a face sorted by the depth of its middle goes under a farther face +/// that it is in front of where the two overlap. The surface draws the nearer face last there, on +/// its own and as a member of a revolved group. +#[test] +fn a_revolved_surface_draws_the_nearer_of_two_overlapping_faces_last() { + let path = vase(); + let faces = vectorcraft_three_d::revolve(&path, path.bounds().unwrap(), revolve_options(¶ms())).unwrap(); + let by_depth: Vec<_> = faces.iter().map(|f| (f.points.clone(), f.plane)).collect(); + assert!(misordered(&by_depth).is_some(), "the faces by depth are drawn the wrong way round somewhere"); + let keyed: Vec<_> = faces.iter().map(|f| (f.points.clone(), f.plane, f.path())).collect(); + let mut n = node(path.clone()); + n.appearance.effects.push(crate::new_effect(REVOLVE, ¶ms()).unwrap()); + let drawn = drawn_order(&revolve_art(&n).unwrap(), &keyed); + assert_eq!(drawn.len(), faces.len()); + assert_eq!(misordered(&drawn), None, "an object"); + let mut g = Node::group(NodeId(9), vec![Arc::new(node(path))]); + g.appearance.effects.push(crate::new_effect(REVOLVE, ¶ms()).unwrap()); + let drawn = drawn_order(&revolve_art(&g).unwrap(), &keyed); + assert_eq!(drawn.len(), faces.len()); + assert_eq!(misordered(&drawn), None, "a group's member"); +} + +/// The faces of a group's members, sorted together by the depths of their middles, go in the order +/// of their depths where they overlap, those of two members as well as those of one. +#[test] +fn a_revolved_groups_members_draw_the_nearer_of_two_overlapping_faces_last() { + let p = json!({"angle": 270, "offset": 12, "rotationX": -30, "rotationY": 0, "perspectiveAngle": 0, "segments": 16, "cap": true}); + let members: Vec = (0..5).map(dash).collect(); + let b = dashes().bounds().unwrap(); + let mut faces: Vec<_> = members.iter().flat_map(|m| vectorcraft_three_d::revolve(m, b, revolve_options(&p)).unwrap()).collect(); + faces.sort_by(|a, b| a.depth.total_cmp(&b.depth)); + let by_depth: Vec<_> = faces.iter().map(|f| (f.points.clone(), f.plane)).collect(); + assert!(misordered(&by_depth).is_some(), "the faces by depth are drawn the wrong way round somewhere"); + let keyed: Vec<_> = faces.iter().map(|f| (f.points.clone(), f.plane, f.path())).collect(); + let mut g = Node::group(NodeId(9), members.into_iter().map(|m| Arc::new(node(m))).collect()); + g.appearance.effects.push(crate::new_effect(REVOLVE, &p).unwrap()); + let drawn = drawn_order(&revolve_art(&g).unwrap(), &keyed); + assert_eq!(drawn.len(), faces.len()); + assert_eq!(misordered(&drawn), None); +} + +/// Revolve (Classic) draws the nearer of two overlapping facets last where they overlap, too. +#[test] +fn a_classic_revolved_surface_draws_the_nearer_of_two_overlapping_facets_last() { + let path = dashes(); + // Revolve (Classic) sweeps its surface unshaded, with one facet for each cell. + let classic = vectorcraft_three_d::Revolve { + shade: false, + smooth_shading: false, + lights: None, + light_color: [1.0; 3], + ..revolve_options(&crate::merged_params(CLASSIC_REVOLVE, &classic_params())) + }; + let facets = vectorcraft_three_d::revolve_facets(&path, path.bounds().unwrap(), classic).unwrap(); + let by_depth: Vec<_> = facets.iter().map(|f| (f.contours[0].clone(), f.plane)).collect(); + assert!(misordered(&by_depth).is_some(), "the facets by depth are drawn the wrong way round somewhere"); + let keyed: Vec<_> = facets.iter().map(|f| (f.contours[0].clone(), f.plane, f.path())).collect(); + let mut n = node(path); + n.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, &classic_params()).unwrap()); + let drawn = drawn_order(&revolve_art(&n).unwrap(), &keyed); + assert_eq!(drawn.len(), facets.len()); + assert_eq!(misordered(&drawn), None); +} + +/// A surface whose faces by depth are already drawn the right way round wherever they overlap keeps +/// that order. +#[test] +fn a_surface_already_in_order_keeps_it() { + let path = vase(); + let p = json!({"angle": 360, "offset": 12, "rotationX": 0, "rotationY": 0, "segments": 24, "cap": true}); + let faces = vectorcraft_three_d::revolve(&path, path.bounds().unwrap(), revolve_options(&p)).unwrap(); + let by_depth: Vec<_> = faces.iter().map(|f| (f.points.clone(), f.plane)).collect(); + assert_eq!(misordered(&by_depth), None); + let order = surface_order(faces.iter().map(|f| (f.points.as_slice(), f.plane, f.depth))); + assert_eq!(order, (0..faces.len()).collect::>()); +} + +/// Of two overlapping faces, the one nearer the viewer where they overlap goes after the other, +/// whatever their depths; a face without a plane, and one that overlaps neither, keep their places. +/// Two faces at the same depth there keep their order. +#[test] +fn surface_order_puts_the_nearer_face_where_they_overlap_last() { + let square = |x: f64| vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)]; + // z = 10 - x: at the middle of its overlap with the next square (x 7.5) it is at z 2.5. + let r = std::f64::consts::FRAC_1_SQRT_2; + let sloped = Some(DepthPlane { normal: [r, 0.0, r], offset: 10.0 * r, center: Point::ZERO, eye: None }); + let flat = |z: f64| Some(DepthPlane { normal: [0.0, 0.0, 1.0], offset: z, center: Point::ZERO, eye: None }); + let (a, b, apart) = (square(0.0), square(5.0), square(40.0)); + let faces = [(&a[..], sloped, 5.0), (&apart[..], flat(0.0), 1.0), (&b[..], flat(3.0), 3.0)]; + assert_eq!(surface_order(faces), vec![0, 1, 2], "the flat face, nearer at the overlap, is already last"); + let faces = [(&b[..], flat(2.0), 2.0), (&apart[..], flat(0.0), 3.0), (&a[..], sloped, 5.0)]; + assert_eq!(surface_order(faces), vec![0, 1, 2], "the sloped face, nearer at the overlap, is already last"); + // The sloped face's middle (x 5) is at z 5, but the flat face at z 3 is nearer at the overlap. + let faces = [(&b[..], flat(3.0), 3.0), (&apart[..], flat(0.0), 4.0), (&a[..], sloped, 5.0)]; + assert_eq!(surface_order(faces), vec![1, 2, 0], "the flat face is nearer at the overlap"); + let faces = [(&b[..], None, 3.0), (&apart[..], flat(0.0), 4.0), (&a[..], sloped, 5.0)]; + assert_eq!(surface_order(faces), vec![0, 1, 2], "no plane"); + let faces = [(&b[..], flat(2.5), 3.0), (&a[..], sloped, 5.0)]; + assert_eq!(surface_order(faces), vec![0, 1], "the same depth there"); +} diff --git a/crates/effects/src/solids/tests_shadow.rs b/crates/effects/src/solids/tests_shadow.rs index 7e7d2e1595..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 { @@ -223,3 +277,214 @@ fn expand_appearance_keeps_the_shadow_as_a_path() { assert!((after.x0 - before.x0 - 40.0).abs() < 1e-6, "{id}: {before:?} {after:?}"); } } + +/// A square filled red and stroked blue, its stroke as opaque as `stroke`. +fn stroked_square(id: u64, dx: f64, stroke: f32) -> Node { + let mut n = square_node(id, dx); + n.appearance = Appearance::basic(Paint::solid(RED), Paint::solid(Color::rgb(0.1, 0.2, 0.9)), 6.0).into(); + for item in &mut n.appearance.items { + if let AppearanceItem::Stroke(s) = item { + s.opacity = stroke; + } + } + n +} + +/// Objects with 3D effect `id` and its shadow on (`params`): a filled and stroked square, one whose +/// stroke is half transparent, one whose stroke is fully transparent, and a group of two members, +/// one of them at half opacity. +fn shadowed(id: &str, params: &Value) -> Vec { + let with = |mut n: Node| { + n.appearance.effects.push(crate::new_effect(id, params).unwrap()); + n + }; + let mut half = stroked_square(2, 200.0, 1.0); + half.opacity = 0.5; + let group = Node::group(NodeId(9), vec![Arc::new(stroked_square(1, 0.0, 1.0)), Arc::new(half)]); + vec![with(stroked_square(1, 0.0, 1.0)), with(stroked_square(1, 0.0, 0.5)), with(stroked_square(1, 0.0, 0.0)), with(group)] +} + +/// The settings the shadows of effect `id` are compared with: the defaults, turned with +/// perspective, and under a colored light, below the object for Extrude & Bevel, Inflate and +/// Rotate and behind it for Revolve. +fn shadow_settings(id: &str) -> [Value; 3] { + let position = if id == crate::REVOLVE { "behind" } else { "below" }; + [ + json!({"shadow": true}), + json!({"shadow": true, "rotationX": -25, "rotationY": 35, "perspective": 50, "shadowDistance": 40}), + json!({"shadow": true, "shadowPosition": position, "shadowDistance": 30, "lightColor": "#ff8040", "twist": 30}), + ] +} + +/// How many solids drawing the art of `n` with effect `id` builds. +fn solids_built(n: &Node, id: &str) -> usize { + let start = SOLIDS_BUILT.with(std::cell::Cell::get); + assert!(art(n, id).is_some(), "{id}"); + SOLIDS_BUILT.with(std::cell::Cell::get) - start +} + +/// Drawing a 3D object with its shadow on builds each of its solids once: the shadow is cast from +/// the faces the solids drawn kept, so it builds no more solids than the art without a shadow. +#[test] +fn a_shadowed_3d_object_builds_each_solid_once() { + for id in CASTING { + for params in shadow_settings(id) { + for (lit, mut plain) in shadowed(id, ¶ms).into_iter().zip(shadowed(id, ¶ms)) { + plain.appearance.effects.iter_mut().for_each(|e| e.params["shadow"] = json!(false)); + let mut cast = 0; + art(&lit, id).unwrap().walk(&mut |c| cast += usize::from(shadow_opacity(c).is_some())); + assert!(cast > 0, "{id} {params}"); + let built = solids_built(&plain, id); + assert!(built > 0, "{id}"); + assert_eq!(solids_built(&lit, id), built, "{id} {params}: the shadow builds no solid of its own"); + } + } + } +} + +/// The shadow of the faces Extrude & Bevel, Inflate and Rotate kept when they drew their solids, +/// to the bit: the shadow [`cast_shadow`] casts from solids built for the shadow alone. +#[test] +fn the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it() { + for id in [EXTRUDE, INFLATE, ROTATE] { + for params in shadow_settings(id) { + for n in shadowed(id, ¶ms) { + let (_, fx) = solid(&n.appearance.effects).unwrap(); + let shapes = if is_container(&n) { + members(&n, "").unwrap() + } else { + let (path, rule) = profile(&n).unwrap(); + vec![Profile { path, rule, items: solid_paint_sources(&n).1, opacity: 1.0, scopes: vec![] }] + }; + let (drawn, _) = art_for(None, &n, fx, &shapes).unwrap(); + let p = crate::merged_params(&fx.id, &fx.params); + let (caster, settings, cast) = cast_shadow(&fx.id, &p, &shapes).unwrap().unwrap(); + let alone = shadow::scoped_art(n.id, &caster, settings, cast, has_masks(&shapes)); + assert!(!alone.is_empty(), "{id} {params}"); + assert_eq!(format!("{drawn:?}"), format!("{alone:?}"), "{id} {params}"); + } + } + } +} + +/// A stroke's solid left out of the art (past its own limits) keeps no faces, and the shadow cast +/// from the faces the solids kept leaves it out without building it: it casts nothing, as it draws +/// nothing, and the fill's solid still casts. +#[test] +fn a_stroke_left_out_of_the_art_casts_no_shadow() { + for id in [EXTRUDE, INFLATE] { + let n = stroked_square(1, 0.0, 1.0); + let (path, rule) = profile(&n).unwrap(); + let shapes = [Profile { path, rule, items: solid_paints(&n), opacity: 1.0, scopes: vec![] }]; + let p = crate::merged_params(id, &json!({"shadow": true})); + let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap()); + let mut built: Vec> = + built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect(); + let stroke = parts.iter().position(|(item, ..)| matches!(item, AppearanceItem::Stroke(_))).unwrap(); + assert!(built.len() == 2 && built.iter().all(Option::is_some), "{id}"); + let (both, _, cast) = cast_built(id, &p, &shapes, built.clone()).unwrap().unwrap(); + assert_eq!(cast.len(), 2, "{id}: the fill and the stroke cast"); + built[stroke] = None; + let start = SOLIDS_BUILT.with(std::cell::Cell::get); + let (fill, _, cast) = cast_built(id, &p, &shapes, built).unwrap().unwrap(); + assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get), start, "{id}: no solid is built for the shadow"); + assert_eq!(cast.len(), 1, "{id}: the stroke left out casts nothing"); + assert!(!fill.is_empty() && fill.len() < both.len(), "{id}: only the fill's faces are cast"); + } +} + +/// A command accepts each shadowed object that draws with its shadow, and with Rotate builds the +/// plane of each visible fill and stroke once for the shadow: a fully transparent one casts nothing. +#[test] +fn the_check_accepts_the_shadowed_objects_that_draw() { + for id in [EXTRUDE, INFLATE, ROTATE] { + for params in shadow_settings(id) { + for n in shadowed(id, ¶ms) { + let mut drawn = 0; + art(&n, id).unwrap().walk(&mut |c| drawn += usize::from(shadow_opacity(c).is_some())); + assert!(drawn > 0, "{id} {params}"); + assert_eq!(validate_solid(&n, id, ¶ms), Ok(()), "{id} {params}"); + } + } + } + let shadow = json!({"shadow": true}); + for (stroke, planes) in [(1.0, 2), (0.5, 2), (0.0, 1)] { + let n = stroked_square(1, 0.0, stroke); + let start = SOLIDS_BUILT.with(std::cell::Cell::get); + assert_eq!(validate_solid(&n, ROTATE, &shadow), Ok(()), "{stroke}"); + assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get) - start, planes, "Rotate, a stroke at {stroke}"); + } +} + +/// In wireframe mode no shadow is drawn, so the check casts none: with Shadows on, Rotate builds no +/// plane for a shadow, and Extrude & Bevel and Inflate build each solid once, as with the shadow off. +#[test] +fn the_check_casts_no_shadow_in_wireframe_mode() { + let n = stroked_square(1, 0.0, 1.0); + let wire = json!({"shadow": true, "render": {"mode": "wireframe"}}); + for (id, solids) in [(ROTATE, 0), (EXTRUDE, 2), (INFLATE, 2)] { + let start = SOLIDS_BUILT.with(std::cell::Cell::get); + assert_eq!(validate_solid(&n, id, &wire), Ok(()), "{id}"); + assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get) - start, solids, "{id}"); + } +} + +/// The opacity of each part of the shadow of `n` (its 3D effect's shadow on) and the shadow's art, +/// as [`cast_shadow`] casts it from solids built for the shadow alone and as [`cast_built`] casts +/// it from the faces the solids drawn kept. +fn cast_parts(n: &Node) -> [(Vec, String); 2] { + let (_, fx) = solid(&n.appearance.effects).unwrap(); + let shapes = if is_container(n) { + members(n, "").unwrap() + } else { + let (path, rule) = profile(n).unwrap(); + vec![Profile { path, rule, items: solid_paint_sources(n).1, opacity: 1.0, scopes: vec![] }] + }; + let p = crate::merged_params(&fx.id, &fx.params); + let (_, built) = surfaces_for(None, n, fx, &shapes, true).unwrap(); + [cast_shadow(&fx.id, &p, &shapes), cast_built(&fx.id, &p, &shapes, built)].map(|c| { + let (caster, settings, cast) = c.unwrap().unwrap(); + let inks = cast.iter().map(|(_, ink, _)| ink.opacity).collect(); + (inks, format!("{:?}", shadow::scoped_art(n.id, &caster, settings, cast, has_masks(&shapes)))) + }) +} + +/// A fill, a stroke or a member whose opacity is NaN or infinite casts no part of the shadow, as one +/// at 0 % does, whether the shadow is cast from solids built for it or from the solids drawn; the +/// art beside it still casts its part. +#[test] +fn art_whose_opacity_is_not_a_finite_number_casts_no_shadow() { + // The art with opacity `opacity` in one place: a square's stroke, the fill of a group's second + // member, and a group's second member. + let objects = |opacity: f32| { + let mut fill = square_node(2, 200.0); + for item in &mut fill.appearance.items { + if let AppearanceItem::Fill(f) = item { + f.opacity = opacity; + } + } + let mut member = square_node(2, 200.0); + member.opacity = opacity; + [ + stroked_square(1, 0.0, opacity), + Node::group(NodeId(9), vec![Arc::new(square_node(1, 0.0)), Arc::new(fill)]), + Node::group(NodeId(9), vec![Arc::new(square_node(1, 0.0)), Arc::new(member)]), + ] + }; + for id in [EXTRUDE, INFLATE, ROTATE] { + for bad in [f32::NAN, f32::INFINITY] { + for (i, (mut n, mut clear)) in objects(bad).into_iter().zip(objects(0.0)).enumerate() { + n.appearance.effects.push(crate::new_effect(id, &json!({"shadow": true})).unwrap()); + clear.appearance.effects.push(crate::new_effect(id, &json!({"shadow": true})).unwrap()); + let expected = cast_parts(&clear); + for (k, (inks, shadow)) in cast_parts(&n).into_iter().enumerate() { + assert_eq!(inks, vec![1.0], "{id} {bad} object {i} cast {k}: only the opaque art casts"); + assert_eq!(shadow, expected[k].1, "{id} {bad} object {i} cast {k}"); + } + let mut opacities = vec![]; + art(&n, id).unwrap().walk(&mut |c| opacities.extend(shadow_opacity(c))); + assert_eq!(opacities, vec![0.5], "{id} {bad} object {i}"); + } + } + } +} diff --git a/crates/effects/src/solids/wireframe.rs b/crates/effects/src/solids/wireframe.rs index e6e7d89ab5..65ac8b0f7e 100644 --- a/crates/effects/src/solids/wireframe.rs +++ b/crates/effects/src/solids/wireframe.rs @@ -1,22 +1,91 @@ //! Expand as Wireframes: the edges of the faces a 3D effect draws, as open and closed paths that -//! can be edited on their own. +//! can be edited on their own. Also the 3D and Materials panel's Render Settings › Wireframe, which +//! draws those edges in place of the shaded faces while the effect stays live. use std::collections::{HashMap, HashSet, VecDeque}; use std::sync::Arc; +use serde_json::Value; use vectorcraft_doc::color::{Color, Paint}; -use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, LineJoin, Node, NodeId, StrokeLayer}; use vectorcraft_geom::{Anchor, CubicBez, PathData, Point, SubPath}; use vectorcraft_three_d::Facet; use super::{ - Profile, ROTATE, built_solids, facets, geometry, has_solid, is_container, is_plane, is_three_d, label_of, members, object_profile, region, - reshape_members, resolve, resolve_for, solid, solid_paint_sources, solid_parts, union_bounds, + CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, INFLATE, Profile, ROTATE, built_solids, facets, geometry, has_solid, is_container, is_plane, + is_three_d, label_of, members, object_profile, region, reshape_members, resolve, resolve_for, solid, solid_paint_sources, solid_parts, + union_bounds, }; use crate::{GeomContext, is_geometry}; /// The most distinct edges one object's wireframe may have. pub(crate) const MAX_WIRE_EDGES: usize = 1_000_000; +/// The parameter that holds a 3D effect's render settings: an object whose `mode` is one of +/// [`RENDER_MODES`]. +pub const RENDER: &str = "render"; + +/// The render modes of a 3D effect: `shaded` draws the lit faces, `wireframe` the edges of every +/// face ([`renders_wireframe`]). +pub const RENDER_MODES: [&str; 2] = ["shaded", "wireframe"]; + +/// The 3D effects that take [`RENDER`]: the 3D and Materials panel's Extrude & Bevel, Revolve, +/// Inflate and Rotate. The 3D (Classic) effects have their own Wireframe surface. +const TAKES_RENDER: [&str; 4] = [EXTRUDE, crate::REVOLVE, INFLATE, ROTATE]; + +/// The weight of a rendered wireframe edge, in points: the weight Expand as Wireframes strokes its +/// edges with (VectorCraft's own). +pub(crate) const WIRE_WEIGHT: f64 = 0.5; + +/// Does effect `fx` draw as a wireframe: is it one of the effects that take [`RENDER`], with its +/// `render.mode` set to `wireframe`? +pub fn renders_wireframe(fx: &Effect) -> bool { + wireframe_params(&fx.id, &fx.params) +} + +/// Do 3D effect `id`'s parameters `p` set it to draw as a wireframe ([`renders_wireframe`])? A +/// command that sets them is checked against the art that mode draws: the faces' edges, with no +/// shadow, graphics or paint copies. +pub(crate) fn wireframe_params(id: &str, p: &Value) -> bool { + TAKES_RENDER.contains(&id) && p.get(RENDER).and_then(|r| r.get("mode")).and_then(Value::as_str) == Some("wireframe") +} + +/// Check the render settings in 3D effect `id`'s parameters `p`: `render`, when given to one of the +/// effects in [`TAKES_RENDER`], is an object that holds only `mode`, one of [`RENDER_MODES`] (a +/// missing `mode` is `shaded`). The 3D (Classic) effects refuse it as a parameter they do not take. +pub(crate) fn validate_render(id: &str, p: &Value) -> Result<(), String> { + let Some(render) = p.get(RENDER).filter(|_| TAKES_RENDER.contains(&id)) else { return Ok(()) }; + let valid = render + .as_object() + .is_some_and(|fields| fields.iter().all(|(key, value)| key == "mode" && value.as_str().is_some_and(|m| RENDER_MODES.contains(&m)))); + if !valid { + return Err("`render` must be an object holding only `mode`, set to shaded or wireframe".into()); + } + Ok(()) +} + +/// The art a 3D effect in wireframe mode draws for object `id` in place of its shaded faces: a group +/// of the edges of `faces`, each edge once ([`edges`]), stroked [`WIRE_WEIGHT`] black with round +/// joins and no fill, as Expand as Wireframes strokes them. Like Expand as Wireframes and the +/// Outline view, the mesh shows every edge whatever the opacity, blending mode or opacity mask of +/// the fills, strokes and group members it is built from; the object's own transparency applies to +/// the art as a whole. `None` past [`MAX_WIRE_EDGES`] edges, when the canvas draws the source art, +/// as it does for a solid past its limits. +pub(crate) fn wire_art(id: NodeId, faces: &[PathData]) -> Option> { + let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), WIRE_WEIGHT); + stroke.join = LineJoin::Round; + let appearance = Appearance { items: vec![AppearanceItem::Stroke(stroke)], ..Default::default() }; + let children = edges(faces).ok()?.into_iter().map(|path| Arc::new(Node::path(id, path, appearance.clone()))).collect(); + Some(Arc::new(Node::group(id, children))) +} + +/// The art 3D effect `fx` in wireframe mode draws for object `id` from `shapes`: the edges of the +/// faces it builds ([`wire_art`]). `None` when a solid can't be built or past the edge limit, when +/// the canvas draws the source art. +pub(crate) fn wire_surfaces(id: NodeId, fx: &Effect, shapes: &[Profile]) -> Option>> { + let faces: Vec = facet_paths(fx, shapes).ok()?.into_iter().map(|f| f.path).collect(); + Some(vec![wire_art(id, &faces)?]) +} + /// The grid points are rounded to before edges are compared, in points: two faces that share an /// edge give it once. const GRID: f64 = 1.0 / 1024.0; @@ -53,8 +122,8 @@ pub fn three_d_wireframe_in(doc: Option<&Document>, n: &Node) -> Result = after_geometry(doc, n, faces, shadow, revolve).into_iter().map(|f| f.path).collect(); let wire = edges(&faces)?; if wire.is_empty() { return Err(format!("{label} draws no faces for this object")); @@ -63,44 +132,86 @@ pub fn three_d_wireframe_in(doc: Option<&Document>, n: &Node) -> Result, n: &Node, faces: Vec, revolve: bool) -> Vec { +/// ([`reshaped_beside`]): its first visible Revolve when `revolve` is set, else its first visible +/// Extrude & Bevel, Inflate or Rotate. The effects measure the faces together with `shadow`, the +/// shadow the canvas draws behind them, as they measure the drawn art. +fn after_geometry(doc: Option<&Document>, n: &Node, faces: Vec, shadow: Vec>, revolve: bool) -> Vec { let fx = &n.appearance.effects; let drawn = if revolve { fx.iter().position(|e| e.visible && crate::revolve::is_revolve(&e.id)) } else { solid(fx).map(|(i, _)| i) }; let Some(index) = drawn else { return faces }; - reshaped(faces, fx.get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..GeomContext::of(n) }) + reshaped_beside(faces, shadow, fx.get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..GeomContext::of(n) }) +} + +/// One face of a drawn 3D surface: its outline and the width of the stroke the canvas draws around +/// it (the seam between faces, or a wire edge), which a later Outline Stroke outlines. +pub(crate) struct WireFace { + pub(crate) path: PathData, + pub(crate) stroke: f64, } /// `faces` reshaped by the visible geometry effects in `later` (the effects after a 3D effect), as /// they reshape the faces of the drawn surface ([`crate::reshape::reshape_leaves`]): each effect /// reshapes each face on its own, about the bounds all the faces have before it, and the faces keep -/// to one budget of anchors together. `ctx` gives the object's id, the seed of a random Transform, -/// and the document. -pub(crate) fn reshaped(faces: Vec, later: &[Effect], ctx: &GeomContext) -> Vec { +/// to one budget of anchors together. Each face is filled and carries its round-joined stroke, as on +/// the canvas, so an Outline Stroke outlines that stroke. `ctx` gives the object's id, the seed of a +/// random Transform, and the document. +pub(crate) fn reshaped(faces: Vec, later: &[Effect], ctx: &GeomContext) -> Vec { + reshaped_beside(faces, vec![], later, ctx) +} + +/// The name the faces carry through [`reshaped_beside`], which tells them from the shadow. +const FACE: &str = "face"; + +/// [`reshaped`] with `shadow`, the shadow drawn behind the faces, in the art the effects reshape: +/// each effect measures the faces and the shadow together, and only the faces are returned. +fn reshaped_beside(faces: Vec, shadow: Vec>, later: &[Effect], ctx: &GeomContext) -> Vec { let after: Vec<&Effect> = later.iter().filter(|e| e.visible && is_geometry(&e.id)).collect(); if after.is_empty() { return faces; } let id = NodeId(ctx.seed); - let fill = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0); - let mut art = Node::group(id, faces.into_iter().map(|f| Arc::new(Node::path(id, f, fill.clone()))).collect()); + let paint = Paint::solid(Color::BLACK); + let face = |f: WireFace| { + let items = + vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), f.stroke))]; + let mut face = Node::path(id, f.path, Appearance { items, ..Default::default() }); + face.name = Some(FACE.into()); + Arc::new(face) + }; + let mut art = Node::group(id, shadow.into_iter().chain(faces.into_iter().map(face)).collect()); crate::reshape::reshape_leaves(&mut art, &after, later, ctx.doc); let mut out = vec![]; - art.walk(&mut |c| out.extend(c.path_data().cloned())); + face_paths(&art, false, &mut out); out } +/// The faces in `n` ([`FACE`]), `inside` one or not, each with the width of its stroke: a face that +/// a Transform effect copies or a live-effect plug-in cuts into pieces becomes a group with its name. +fn face_paths(n: &Node, inside: bool, out: &mut Vec) { + let inside = inside || n.name.as_deref() == Some(FACE); + if inside && let Some(path) = n.path_data() { + out.push(WireFace { path: path.clone(), stroke: n.appearance.stroke().map_or(0.0, |s| s.width) }); + } + for c in n.children().into_iter().flatten() { + face_paths(c, inside, out); + } +} + +/// The faces of a 3D effect on an object, group or layer itself, and the shadow the canvas draws +/// behind them (none with the shadow off, or with the effect on fills and strokes). +pub(crate) type FacesAndShadow = (Vec, Vec>); + /// The outline of every face [`super::solid_art`] draws for `n` (already resolved): with the effect /// on the object, its solids; with it on fills and strokes, the solid of each; on a group or layer, -/// the solids of its members, about one shared axis. The swatches and patterns named by a live-effect -/// plug-in after a fill's or stroke's 3D effect are looked up in `doc`. -fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result, String> { +/// the solids of its members, about one shared axis. With the effect on the object, group or layer, +/// also the shadow drawn behind them. The swatches and patterns named by a live-effect plug-in after +/// a fill's or stroke's 3D effect are looked up in `doc`. +fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result { if is_container(n) { let (index, fx) = solid(&n.appearance.effects).ok_or("a 3D effect on a group's fill or stroke draws nothing")?; let mut shapes = members(n, label_of(&fx.id))?; reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes); - return facet_paths(fx, &shapes); + return Ok((facet_paths(fx, &shapes)?, super::shadow_for(n.id, fx, &shapes)?)); } let label = n.appearance.effects.iter().find(|e| e.visible && is_three_d(&e.id)).map_or("This effect", |e| label_of(&e.id)); let (path, rule) = object_profile(n, label)?; @@ -108,7 +219,8 @@ fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result, S let (sources, paints) = solid_paint_sources(n); if let Some((index, fx)) = solid(&n.appearance.effects) { let path = geometry(&path, n.appearance.effects.get(..index).unwrap_or_default(), &ctx); - return facet_paths(fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }]); + let shapes = [Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }]; + return Ok((facet_paths(fx, &shapes)?, super::shadow_for(n.id, fx, &shapes)?)); } let path = geometry(&path, &n.appearance.effects, &ctx); let mut out = vec![]; @@ -119,24 +231,27 @@ fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result, S out.extend(reshaped(faces, item.effects().get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..ctx })); } } - Ok(out) + Ok((out, vec![])) } /// The outlines of the facets effect `fx` builds from `shapes`, as `art_for` builds them: Rotate and /// Rotate (Classic) turn every fill and stroke; Extrude & Bevel and Inflate build a solid from each shape's /// top fill and from the outline of each stroke. A stroke whose solid is past the limits is left out, /// as it is left out of the drawn art; past the limits of the object's solids together, the result -/// is an error, as the canvas draws the source art. -fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result, String> { +/// is an error, as the canvas draws the source art. Each facet carries the width of the stroke the +/// canvas draws around it. +pub(crate) fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result, String> { let label = label_of(&fx.id); let b = union_bounds(shapes).ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?; let p = crate::merged_params(&fx.id, &fx.params); + let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE; + let face = |f: &Facet| WireFace { path: f.path(), stroke: if classic { super::classic::stroke_width(f, &p) } else { super::seam_width(f) } }; let mut out = vec![]; if is_plane(&fx.id) { for s in shapes { for item in &s.items { let (area, rule) = region(&s.path, s.rule, item); - out.extend(facets(ROTATE, &area, rule, b, &p)?.iter().map(Facet::path)); + out.extend(facets(ROTATE, &area, rule, b, &p)?.iter().map(face)); } } return Ok(out); @@ -144,7 +259,7 @@ fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result, String> let (parts, bounds) = solid_parts(shapes, b); // The solids the art draws, each past the limits of the object's solids together as it is. for f in built_solids(&fx.id, &p, &parts, bounds, vectorcraft_three_d::MAX_OBJECT_FACES) { - out.extend(f?.iter().flatten().map(Facet::path)); + out.extend(f?.iter().flatten().map(face)); } Ok(out) } diff --git a/crates/effects/src/solids/wireframe/tests.rs b/crates/effects/src/solids/wireframe/tests.rs index 792fbdb28a..cb92d59e72 100644 --- a/crates/effects/src/solids/wireframe/tests.rs +++ b/crates/effects/src/solids/wireframe/tests.rs @@ -163,13 +163,43 @@ fn revolve_classic_and_rotate_classic_expand_too() { fn later_geometry_effects_reshape_each_face_on_its_own() { let n = solid_square(super::super::EXTRUDE, json!({})); let fx = [crate::new_effect("path.offsetPath", &json!({"offset": 1.0})).unwrap()]; - let out = reshaped(vec![square(0.0, 0.0, 10.0), square(10.0, 0.0, 10.0)], &fx, &GeomContext::of(&n)); - assert_eq!(out.len(), 2, "{out:?}"); - let (a, b) = (out[0].bounds().unwrap(), out[1].bounds().unwrap()); + let faces = [square(0.0, 0.0, 10.0), square(10.0, 0.0, 10.0)].map(|path| WireFace { path, stroke: 0.75 }); + let out = reshaped(faces.into(), &fx, &GeomContext::of(&n)); + assert_eq!(out.len(), 2); + let (a, b) = (out[0].path.bounds().unwrap(), out[1].path.bounds().unwrap()); assert!((a.x0 + 1.0).abs() < 1e-3 && (a.x1 - 11.0).abs() < 1e-3, "{a:?}"); assert!((b.x0 - 9.0).abs() < 1e-3 && (b.x1 - 21.0).abs() < 1e-3, "{b:?}"); } +/// An Outline Stroke after a 3D effect outlines the stroke each face is drawn with (the seam between +/// faces, or a Classic wire edge), not a plain 1 pt stroke: the wireframe covers the outlined faces +/// the canvas draws, in the same place. +#[test] +fn a_later_outline_stroke_outlines_the_stroke_each_face_is_drawn_with() { + let outline = || crate::new_effect("path.outlineStroke", &json!({})).unwrap(); + let cases = [ + (super::super::EXTRUDE, json!({})), + (super::super::CLASSIC_EXTRUDE, json!({})), + (super::super::CLASSIC_EXTRUDE, json!({"surface": "wireframe"})), + (super::super::INFLATE, json!({})), + (ROTATE, json!({})), + (crate::REVOLVE, json!({})), + (crate::CLASSIC_REVOLVE, json!({})), + (crate::CLASSIC_REVOLVE, json!({"surface": "wireframe"})), + ]; + for (id, params) in cases { + let mut n = solid_square(id, params.clone()); + n.appearance.effects.push(outline()); + let wire = three_d_wireframe_in(None, &n).unwrap_or_else(|e| panic!("{id} {params}: {e}")); + let art = if crate::revolve::is_revolve(id) { crate::revolve_art(&n) } else { super::super::solid_art(&n) }.unwrap(); + let drawn = crate::group::shape_art(None, &art, None).unwrap(); + let (w, a) = (bounds(&wire), bounds(&face_paths(&drawn))); + for (x, y) in [(w.x0, a.x0), (w.y0, a.y0), (w.x1, a.x1), (w.y1, a.y1)] { + assert!((x - y).abs() < 1e-6, "{id} {params}: {w:?} {a:?}"); + } + } +} + /// A geometry effect after a fill's 3D effect moves that fill's edges, as it moves its drawn surface. #[test] fn a_geometry_effect_after_a_fill_s_3d_effect_reshapes_its_edges() { @@ -192,6 +222,32 @@ fn a_geometry_effect_after_a_fill_s_3d_effect_reshapes_its_edges() { } } +/// A Transform effect after the 3D effect scales the faces about the center of the drawn art with +/// its shadow, as it scales the surfaces on the canvas. +#[test] +fn a_later_transform_measures_the_faces_with_their_shadow() { + for id in [super::super::EXTRUDE, crate::REVOLVE] { + let scale = crate::new_effect("distort.transform", &json!({"scaleH": 50.0, "scaleV": 50.0})).unwrap(); + let mut n = solid_square(id, json!({"shadow": true, "shadowDistance": 100})); + n.appearance.effects.push(scale.clone()); + let wire = bounds(&three_d_wireframe_in(None, &n).unwrap_or_else(|e| panic!("{id}: {e}"))); + let art = if id == crate::REVOLVE { crate::revolve_art(&n) } else { super::super::solid_art(&n) }.unwrap(); + let mut drawn = art.clone(); + let fx: Vec<&Effect> = art.appearance.effects.iter().collect(); + crate::reshape::reshape_leaves(&mut drawn, &fx, &art.appearance.effects, None); + // The shadow is the art's first member; the surfaces follow it. + let surfaces: Vec = drawn.children().unwrap().iter().skip(1).flat_map(|c| face_paths(c)).collect(); + let a = bounds(&surfaces); + for (x, y) in [(wire.x0, a.x0), (wire.y0, a.y0), (wire.x1, a.x1), (wire.y1, a.y1)] { + assert!((x - y).abs() < 1e-6, "{id}: {wire:?} {a:?}"); + } + // Without the shadow, the faces are scaled about their own center. + let mut alone = solid_square(id, json!({})); + alone.appearance.effects.push(scale); + assert!((bounds(&three_d_wireframe_in(None, &alone).unwrap()).x0 - wire.x0).abs() > 1.0, "{id}"); + } +} + /// With two 3D effects, a geometry effect between them reshapes the faces of the one drawn only /// once: Revolve is drawn, so a Transform before it moves its profile and not its faces again. #[test] @@ -225,6 +281,210 @@ fn a_clipping_group_with_revolve_and_rotate_expands_the_art_revolve_cuts() { assert_eq!(both, alone); } +/// The leaves `art` draws: each path with its fill and stroke. +fn leaves(art: &Node) -> Vec<(PathData, bool, Option)> { + let mut out = vec![]; + art.walk(&mut |c| { + if let Some(p) = c.path_data() { + out.push((p.clone(), c.appearance.fill().is_some(), c.appearance.stroke().cloned())); + } + }); + out +} + +/// The art the canvas draws for `n`: Revolve's, else the other 3D effects'. +fn drawn(n: &Node) -> Node { + crate::revolve_art(n).or_else(|| super::super::solid_art(n)).unwrap_or_else(|| panic!("no art for {n:?}")) +} + +const WIRE: [&str; 4] = [super::super::EXTRUDE, crate::REVOLVE, super::super::INFLATE, ROTATE]; + +/// Render Settings › Wireframe: each of the panel's four effects draws the edges Expand as +/// Wireframes gives, each a 0.5 pt black stroke with round joins and no fill, in place of its +/// shaded faces; shaded again, it draws filled faces. +#[test] +fn wireframe_mode_draws_the_expanded_edges_as_strokes() { + for id in WIRE { + let n = solid_square(id, json!({"render": {"mode": "wireframe"}})); + let art = leaves(&drawn(&n)); + let wire = three_d_wireframe_in(None, &n).unwrap_or_else(|e| panic!("{id}: {e}")); + assert_eq!(art.len(), wire.len(), "{id}"); + for ((path, filled, stroke), edge) in art.iter().zip(&wire) { + assert!(!filled, "{id}: an edge has no fill"); + let stroke = stroke.as_ref().unwrap_or_else(|| panic!("{id}: an edge is stroked")); + assert_eq!((stroke.width, stroke.join, &stroke.paint), (WIRE_WEIGHT, LineJoin::Round, &Paint::solid(Color::BLACK)), "{id}"); + assert_eq!(segments(std::slice::from_ref(path)), segments(std::slice::from_ref(edge)), "{id}"); + } + let shaded = leaves(&drawn(&solid_square(id, json!({"render": {"mode": "shaded"}})))); + assert!(shaded.iter().any(|(_, filled, _)| *filled), "{id}: shaded faces are filled"); + } + // The box turned off axis shows the nine edges of its three faces. + let n = solid_square(super::super::EXTRUDE, json!({"render": {"mode": "wireframe"}})); + let paths: Vec = leaves(&drawn(&n)).into_iter().map(|(p, ..)| p).collect(); + assert_eq!(segments(&paths).len(), 9); +} + +/// The wireframe stays live: a deeper extrusion and a turned view redraw the edges. +#[test] +fn wireframe_mode_follows_the_effects_settings() { + let paths = |p: Value| -> Vec { leaves(&drawn(&solid_square(super::super::EXTRUDE, p))).into_iter().map(|(p, ..)| p).collect() }; + let flat = bounds(&paths(json!({"render": {"mode": "wireframe"}, "depth": 10.0}))); + let deep = bounds(&paths(json!({"render": {"mode": "wireframe"}, "depth": 200.0}))); + assert!(deep.width() > flat.width() + 1.0 || deep.height() > flat.height() + 1.0, "{flat:?} {deep:?}"); + let turned = paths(json!({"render": {"mode": "wireframe"}, "rotationY": 60.0})); + assert_ne!(segments(&turned), segments(&paths(json!({"render": {"mode": "wireframe"}})))); +} + +/// In wireframe mode no shadow and no graphic is drawn: only the edges. +#[test] +fn wireframe_mode_draws_no_shadow() { + for id in WIRE { + let n = solid_square(id, json!({"render": {"mode": "wireframe"}, "shadow": true})); + let art = leaves(&drawn(&n)); + assert!(!art.is_empty() && art.iter().all(|(_, filled, stroke)| !filled && stroke.is_some()), "{id}"); + } +} + +/// The mode works where the effect is on a fill and on a group: the fill's solid and every member's +/// solid draw as edges, and the geometry effects after a fill's effect still apply to them. +#[test] +fn wireframe_mode_on_a_fill_and_on_a_group() { + for id in WIRE { + let mut n = solid_square(id, json!({})); + let mut fx = n.appearance.effects.remove(0); + fx.params["render"] = json!({"mode": "wireframe"}); + let fill = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))).unwrap(); + fill.effects_mut().push(fx.clone()); + fill.effects_mut().push(crate::new_effect("distort.transform", &json!({"moveH": 500.0})).unwrap()); + let art = leaves(&drawn(&n)); + assert!(!art.is_empty() && art.iter().all(|(_, filled, stroke)| !filled && stroke.is_some()), "{id} on a fill"); + + let member = |x: f64, id: u64| { + Arc::new(Node::path(NodeId(id), square(x, 100.0, 50.0), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0))) + }; + let mut g = Node::group(NodeId(1), vec![member(100.0, 2), member(200.0, 3)]); + g.appearance.effects.push(fx); + let art = leaves(&drawn(&g)); + assert!(!art.is_empty() && art.iter().all(|(_, filled, stroke)| !filled && stroke.is_some()), "{id} on a group"); + // Both members' edges are drawn. + let paths: Vec = art.into_iter().map(|(p, ..)| p).collect(); + assert!(bounds(&paths).width() > 100.0, "{id}"); + } +} + +/// The mesh shows every edge, as Expand as Wireframes gives them, whatever the opacity of the fill +/// and the opacity masks of the group's members; the object's own opacity stays on the art. Two +/// members that touch, one at 50% and one masked, draw their shared edge once: seven edges. +#[test] +fn the_mesh_shows_every_edge_whatever_the_members_transparency() { + let member = |x: f64, id: u64, opacity: f32| { + let mut n = Node::path(NodeId(id), square(x, 100.0, 50.0), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))) { + f.opacity = opacity; + } + n + }; + let mut masked = member(150.0, 3, 1.0); + masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(member(0.0, 900, 1.0), true))); + let mut g = Node::group(NodeId(1), vec![Arc::new(member(100.0, 2, 0.5)), Arc::new(masked)]); + g.opacity = 0.75; + g.appearance.effects.push(crate::new_effect(ROTATE, &json!({"render": {"mode": "wireframe"}})).unwrap()); + let art = drawn(&g); + assert_eq!(art.opacity, 0.75); + let paths: Vec = leaves(&art).into_iter().map(|(p, ..)| p).collect(); + assert_eq!(segments(&paths).len(), 7, "{paths:?}"); + assert_eq!(segments(&paths).len(), segments(&three_d_wireframe_in(None, &g).unwrap()).len()); + let mut scoped = 0; + for c in art.children().into_iter().flatten() { + c.walk(&mut |c| scoped += usize::from(c.extras().mask.is_some() || c.opacity < 1.0)); + } + assert_eq!(scoped, 0, "no part of the mesh is masked or faded"); + // A fill at 0% still shows its mesh. + for id in WIRE { + let mut n = solid_square(id, json!({"render": {"mode": "wireframe"}})); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))) { + f.opacity = 0.0; + } + assert!(!leaves(&drawn(&n)).is_empty(), "{id}"); + } +} + +/// Expand Appearance of a Revolve in wireframe mode gives the stroked edges, not the shaded faces. +#[test] +fn expanding_a_revolve_in_wireframe_mode_gives_the_edges() { + let n = solid_square(crate::REVOLVE, json!({"render": {"mode": "wireframe"}})); + let art = leaves(&crate::revolve::expand_revolve_art(&n).unwrap()); + assert_eq!(art.len(), three_d_wireframe_in(None, &n).unwrap().len()); + assert!(art.iter().all(|(_, filled, stroke)| !filled && stroke.as_ref().is_some_and(|s| s.width == WIRE_WEIGHT))); +} + +/// `render` is checked before an edit: an object holding only `mode`, `shaded` or `wireframe`, and +/// only on the panel's four effects. +#[test] +fn render_settings_are_validated() { + for id in WIRE { + for good in [json!({}), json!({"render": {}}), json!({"render": {"mode": "shaded"}}), json!({"render": {"mode": "wireframe"}})] { + assert_eq!(crate::validate_three_d_params(id, &good), Ok(()), "{id} {good}"); + } + for bad in [ + json!({"render": "wireframe"}), + json!({"render": null}), + json!({"render": {"mode": "raytrace"}}), + json!({"render": {"mode": true}}), + json!({"render": {"mode": "wireframe", "quality": "high"}}), + ] { + let e = crate::validate_three_d_params(id, &bad).unwrap_err(); + assert_eq!(e, "`render` must be an object holding only `mode`, set to shaded or wireframe", "{id} {bad}"); + } + // The command check on the object refuses it too. + let n = solid_square(id, json!({})); + assert!(crate::validate_three_d(&n, id, &json!({"render": {"mode": "x"}})).is_err(), "{id}"); + } + for id in [super::super::CLASSIC_EXTRUDE, crate::CLASSIC_REVOLVE, super::super::CLASSIC_ROTATE] { + let e = crate::validate_three_d_params(id, &json!({"render": {"mode": "wireframe"}})).unwrap_err(); + assert!(e.contains("`render`"), "{id}: {e}"); + } +} + +/// A Revolve whose shaded surface is past the budget of paint copies (a gradient with many stops) is +/// refused shaded, but in wireframe mode, which draws only the black edges, it is accepted and drawn: +/// on the object and on a fill. +#[test] +fn wireframe_mode_is_checked_against_the_edges_it_draws() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let n = solid_square(crate::REVOLVE, json!({})); + let path = n.path_data().unwrap().clone(); + let faces = vectorcraft_three_d::revolve(&path, path.bounds().unwrap(), crate::revolve::revolve_options(&json!({}))).unwrap().len(); + let stops = crate::revolve::MAX_PAINT_COPIES / (faces * 4) / std::mem::size_of::() + 1; + let stops = (0..stops).map(|i| GradientStop::new(i as f32 / stops as f32, Color::BLACK)).collect(); + let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let mut n = n; + n.appearance = Appearance::basic(gradient, Paint::None, 0.0).into(); + let shaded = json!({}); + let wire = json!({"render": {"mode": "wireframe"}}); + let refused = crate::validate_revolve(&n, &shaded).unwrap_err(); + assert!(refused.contains("simplify the gradient"), "{refused}"); + assert_eq!(crate::validate_revolve(&n, &wire), Ok(())); + n.appearance.effects.push(crate::new_effect(crate::REVOLVE, &wire).unwrap()); + assert!(leaves(&drawn(&n)).iter().all(|(_, filled, stroke)| !filled && stroke.is_some())); + // On the fill. + let fx = n.appearance.effects.remove(0); + let at = n.appearance.items.iter().position(|i| matches!(i, AppearanceItem::Fill(_))).unwrap(); + assert!(crate::revolve::validate_item_revolve(&n, &shaded, at, 0).is_err()); + assert_eq!(crate::revolve::validate_item_revolve(&n, &wire, at, 0), Ok(())); + n.appearance.items[at].effects_mut().push(fx); + assert!(leaves(&drawn(&n)).iter().all(|(_, filled, stroke)| !filled && stroke.is_some())); +} + +/// A 3D (Classic) effect ignores a `render` it does not take in a loaded file: it draws as before. +#[test] +fn a_classic_effect_is_not_drawn_as_a_render_wireframe() { + let mut n = solid_square(super::super::CLASSIC_EXTRUDE, json!({})); + n.appearance.effects[0].params["render"] = json!({"mode": "wireframe"}); + assert!(!renders_wireframe(&n.appearance.effects[0])); + assert!(leaves(&drawn(&n)).iter().any(|(_, filled, _)| *filled)); +} + #[test] fn an_object_without_a_visible_3d_effect_is_an_error() { let mut n = solid_square(super::super::EXTRUDE, json!({})); diff --git a/crates/effects/src/svg_filter.rs b/crates/effects/src/svg_filter.rs index 3877a60ae9..6cb0c45e65 100644 --- a/crates/effects/src/svg_filter.rs +++ b/crates/effects/src/svg_filter.rs @@ -1,13 +1,15 @@ //! Effect › SVG Filters (`svg.filter`): an SVG `` element applied as a live raster effect. //! The filter runs on the object's pixels as SVG 1.1 describes it //! (), drawn by resvg. Its lengths are in points times -//! the effect's `scale`, its user space starts at the effect's `origin`, its object bounding box is the box of the drawn pixels, and it runs at the +//! the effect's `scale`, its user space starts at the effect's `origin`, its axes point as the effect's `axes` say (a turned or +//! skewed user space), its object bounding box is the box of the drawn pixels, and it runs at the //! Document Raster Effects resolution when the view shows the object at a finer one. 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; @@ -16,6 +18,7 @@ use vectorcraft_geom::{Affine, Rect, Vec2}; use crate::pixel::PixelSpace; use crate::util::{num, text}; +pub mod defaults; #[cfg(test)] mod tests; @@ -622,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)) @@ -1223,13 +1236,16 @@ fn region_length(v: Option<&str>, default: f64, user: bool) -> Length { } /// An SVG filter effect: the filter's XML, how many points one of its units is, where its user -/// space's origin lies in the document, and its region. +/// space's origin lies in the document, which way its axes point, and its region. #[derive(Clone, Debug, PartialEq)] pub struct SvgFilterFx { /// The filter as it is drawn and written ([`rebuilt`]). xml: Arc, scale: f64, origin: Vec2, + /// The directions of the user space's axes in the document, before `scale` ([`axes_param`]): + /// the identity unless the user space is turned, skewed or scaled unevenly. + axes: Affine, /// Its region (filter effects region): x, y, width, height. region: [Length; 4], /// Is the region in user space with a length measured against the object's box? It is then @@ -1249,11 +1265,92 @@ fn origin_param(p: &Value) -> Vec2 { Vec2::new(at(0), at(1)) } +/// The largest magnitude of an entry of an SVG filter effect's `axes`. +pub const MAX_AXIS: f64 = 1000.0; + +/// The smallest magnitude of the determinant of an SVG filter effect's `axes`. +pub const MIN_AXES_DET: f64 = 0.001; + +/// The `axes` of an SVG filter effect's parameters `p`: `[a, b, c, d]`, the document directions +/// of one unit along the filter's x axis (`[a, b]`) and its y axis (`[c, d]`), before `scale`. +/// The identity when absent; `None` when it isn't four numbers from -[`MAX_AXIS`] to [`MAX_AXIS`] +/// whose determinant is at least [`MIN_AXES_DET`] across ([`valid_axes`]). +fn axes_param(p: &Value) -> Option { + match p.get("axes") { + None | Some(Value::Null) => Some(Affine::IDENTITY), + Some(v) => valid_axes(v), + } +} + +/// `v` as the linear map of an SVG filter effect's `axes` ([`axes_param`]), when it is one. +pub fn valid_axes(v: &Value) -> Option { + let n: Vec = v.as_array()?.iter().map(Value::as_f64).collect::>()?; + axes_of(<[f64; 4]>::try_from(n).ok()?) +} + +/// `[a, b, c, d]` as the linear map of an SVG filter effect's `axes`, when the effect takes it ([`valid_axes`]). +fn axes_of([a, b, c, d]: [f64; 4]) -> Option { + let det = a * d - b * c; + ([a, b, c, d].iter().all(|v| v.is_finite() && v.abs() <= MAX_AXIS) && det.abs() >= MIN_AXES_DET).then(|| Affine::new([a, b, c, d, 0.0, 0.0])) +} + +/// A filter's user space as the SVG filter effect stores it ([`user_space`]). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct UserSpace { + /// The effect's `scale`. + pub scale: f64, + /// The effect's `origin`. + pub origin: [f64; 2], + /// The effect's `axes`; `None` when the axes are the document's. + pub axes: Option<[f64; 4]>, +} + +/// `ts`, a user space mapped to the document, as the SVG filter effect's `scale` (the square root +/// of its area scale), `origin` and, when it turns, skews or scales unevenly, `axes`. `None` when +/// it can't be stored: not finite, `scale` outside 0.001..1000, or `axes` the effect refuses +/// ([`valid_axes`]). +pub fn user_space(ts: Affine) -> Option { + let [a, b, c, d, e, f] = ts.as_coeffs(); + if ![a, b, c, d, e, f].iter().all(|v| v.is_finite()) { + return None; + } + let scale = ts.determinant().abs().sqrt(); + if !(0.001..=1000.0).contains(&scale) { + return None; + } + let even = b == 0.0 && c == 0.0 && a > 0.0 && (a - d).abs() <= 1e-9 * a.max(1.0); + if even { + return Some(UserSpace { scale: a, origin: [e, f], axes: None }); + } + let axes = [a, b, c, d].map(|v| v / scale); + axes_of(axes)?; + Some(UserSpace { scale, origin: [e, f], axes: Some(axes) }) +} + +/// The longest a unit vector becomes under the linear part of `a` (its largest singular value). +fn stretch(a: Affine) -> f64 { + let [a, b, c, d, _, _] = a.as_coeffs(); + let sum = a * a + b * b + c * c + d * d; + let det = a * d - b * c; + (0.5 * (sum + (sum * sum - 4.0 * det * det).max(0.0).sqrt())).sqrt() +} + +/// The share of a raster pixel, `space.px` points wide, that a pixel of the Document Raster Effects +/// resolution is (at most 1). +fn raster_resolution(space: &PixelSpace) -> f64 { + if space.line.is_finite() && space.line > 0.0 && space.px.is_finite() && space.px > 0.0 { (space.px / space.line).min(1.0) } else { 1.0 } +} + +/// How many times the raster's pixels a turned filter's canvas may hold ([`SvgFilterFx::turned_canvas`]). +const TURNED_ROOM: f64 = 4.0; + impl SvgFilterFx { - /// The effect's parameters `p` (defaults merged in): `xml`, the `` element, `scale` - /// and `origin`. `None` when `xml` isn't a filter [`check`] takes, however the effect came to - /// hold it (an opened file, a script): the object is then drawn, printed and exported without it. + /// The effect's parameters `p` (defaults merged in): `xml`, the `` element, `scale`, + /// `origin` and `axes`. `None` when `xml` isn't a filter [`check`] takes, or `axes` isn't + /// valid ([`axes_param`]), however the effect came to hold it (an opened file, a script): the + /// object is then drawn, printed and exported without it. pub(crate) fn parse(p: &Value) -> Option { + let axes = axes_param(p)?; let xml = checked(text(p, "xml", ""))?; let (wrapped, _) = wrap(&xml); let doc = roxmltree::Document::parse(&wrapped).ok()?; @@ -1272,7 +1369,17 @@ impl SvgFilterFx { let (window, blur) = (largest(&["radius", "kernelUnitLength"]), largest(&["stdDeviation"])); let box_units = f.attribute("primitiveUnits").is_some_and(|u| u.trim() == "objectBoundingBox"); let scale = num(p, "scale", 1.0).clamp(1e-3, 1e3); - Some(Self { xml, scale, origin: origin_param(p), region, measured, window, blur, box_units }) + Some(Self { xml, scale, origin: origin_param(p), axes, region, measured, window, blur, box_units }) + } + + /// The filter's user space → the document: moved to `origin`, scaled by `scale`, along `axes`. + pub fn to_doc(&self) -> Affine { + Affine::translate(self.origin) * Affine::scale(self.scale) * self.axes + } + + /// The box of `bounds` (document units) in the filter's user space. + fn user_box(&self, bounds: Rect) -> Rect { + self.to_doc().inverse().transform_rect_bbox(bounds) } /// The filter's region in its user space for an object whose box there is `b`: lengths in user @@ -1307,11 +1414,11 @@ impl SvgFilterFx { with_attributes(xml, &[("x", r.x0), ("y", r.y0), ("width", r.width()), ("height", r.height())]) } - /// The filter as SVG output writes it (one unit a point, [`Self::in_points`]) for an object - /// whose box in the document is `bounds`: in its SVG 1.1 form ([`svg11`]), `None` when SVG 1.1 - /// can't hold it ([`Self::writes_as_svg11`]). - pub fn written_xml(&self, bounds: Rect) -> Option { - let out = self.with_region(&self.svg11_form()?, (bounds - self.origin).scale_from_origin(1.0 / self.scale))?; + /// The filter as SVG output writes it, in its user space ([`Self::to_doc`]), for an object + /// whose box in that user space is `user_box`: in its SVG 1.1 form ([`svg11`]), `None` when SVG + /// 1.1 can't hold it ([`Self::writes_as_svg11`]). + pub fn written_xml(&self, user_box: Rect) -> Option { + let out = self.with_region(&self.svg11_form()?, user_box)?; (written_len(&out) <= MAX_WRITTEN_XML).then_some(out) } @@ -1344,10 +1451,11 @@ impl SvgFilterFx { if !(space.px.is_finite() && space.px > 0.0) { return 1.0; } - let mut s: f64 = if space.line.is_finite() && space.line > 0.0 { (space.px / space.line).min(1.0) } else { 1.0 }; - // A length spans length × scale / px raster pixels, or a fraction of the box. + let mut s = raster_resolution(space); + // A length spans at most length × scale × the axes' stretch / px raster pixels, or a fraction of the box. + let reach = self.scale * stretch(self.axes); for (length, most) in [(self.window, MAX_WINDOW_PX), (self.blur, MAX_BLUR_PX)] { - let px = if self.box_units { length * box_px.max(0.0) } else { length * self.scale / space.px }; + let px = if self.box_units { length * box_px.max(0.0) } else { length * reach / space.px }; if px * s > most { s = most / px; } @@ -1373,15 +1481,21 @@ impl SvgFilterFx { self.measured } - /// Does one unit of the filter's user space measure one point (its `scale` is 1)? - pub fn in_points(&self) -> bool { - self.scale == 1.0 + /// Is the filter's user space the document's, only moved: one unit a point, its axes the + /// document's (`scale` 1, no `axes`)? + pub fn moves_only(&self) -> bool { + self.scale == 1.0 && self.axes == Affine::IDENTITY + } + + /// Can SVG import store the filter's user space ([`Self::to_doc`]) again ([`user_space`])? Its + /// `scale` and `axes` together can scale it past what one of them holds alone. + pub fn opens_again(&self) -> bool { + user_space(self.to_doc()).is_some() } /// How far beyond `bounds` (document units) the filter can draw: its region's reach past them. pub fn outset(&self, bounds: Rect) -> f64 { - let b = (bounds - self.origin).scale_from_origin(1.0 / self.scale); - let region = self.region_in(b).scale_from_origin(self.scale) + self.origin; + let region = self.to_doc().transform_rect_bbox(self.region_in(self.user_box(bounds))); let reach = [bounds.x0 - region.x0, bounds.y0 - region.y0, region.x1 - bounds.x1, region.y1 - bounds.y1].into_iter().fold(0.0, f64::max); if reach.is_finite() { reach.min(MAX_OUTSET) } else { 0.0 } } @@ -1396,20 +1510,40 @@ impl SvgFilterFx { } // Art that draws no pixels still has a box: the whole raster stands for it. let (x0, y0, x1, y1) = drawn_box(data, w, h).unwrap_or((0, 0, w, h)); - let s = self.resolution(space, (x1 - x0).max(y1 - y0) as f64); - let (sw, sh) = ((w as f64 * s).ceil().max(1.0) as u32, (h as f64 * s).ceil().max(1.0) as u32); - let Some(png) = png_of(data, w, x0, y0, x1, y1).map(Arc::new) else { return }; - let k = self.scale; - // Filter user space → the small canvas, and the image's pixels → filter user space. - let outer = Affine::scale(s) * space.to_doc.inverse() * Affine::translate(self.origin) * Affine::scale(k); - let place = Affine::scale(1.0 / k) * Affine::translate(-self.origin) * space.to_doc * Affine::translate(Vec2::new(x0 as f64, y0 as f64)); - let b = place.transform_rect_bbox(Rect::new(0.0, 0.0, (x1 - x0) as f64, (y1 - y0) as f64)); + let user = self.to_doc(); + // Filter user space → the small canvas, and the small canvas → the raster's pixels. + let (sw, sh, outer, back) = if self.axes == Affine::IDENTITY { + let s = self.resolution(space, (x1 - x0).max(y1 - y0) as f64); + let (sw, sh) = ((w as f64 * s).ceil().max(1.0) as u32, (h as f64 * s).ceil().max(1.0) as u32); + (sw, sh, Affine::scale(s) * space.to_doc.inverse() * user, Affine::scale(1.0 / s)) + } else { + // The canvas measures the costly lengths in its own pixels. + let drawn = Rect::new(x0 as f64, y0 as f64, x1 as f64, y1 as f64); + let Some(canvas) = self.turned_canvas(w, h, raster_resolution(space), drawn, space) else { return }; + canvas + }; + // The source as an image, its size, and the map from its pixels to filter user space. The + // object's box in user space is the image's box there, which resvg measures the region and + // a primitive's lengths in the object's box against. In a turned or skewed user space the + // source is first drawn onto the canvas's pixels, whose rows and columns run along the user + // space's axes, and cut to the pixels it draws there: the image then lies along those axes, + // and its box is the box of the art in the user space, not of the raster's box turned into it. + let source = if self.axes == Affine::IDENTITY { + let place = user.inverse() * space.to_doc * Affine::translate(Vec2::new(x0 as f64, y0 as f64)); + png_of(data, w, x0, y0, x1, y1).map(|png| (png, x1 - x0, y1 - y0, place)) + } else { + on_canvas(data, w, h, sw, sh, outer * user.inverse() * space.to_doc) + .map(|(png, cx, cy, iw, ih)| (png, iw, ih, outer.inverse() * Affine::translate(Vec2::new(cx as f64, cy as f64)))) + }; + let Some((png, iw, ih, place)) = source else { return }; + let png = Arc::new(png); + let b = place.transform_rect_bbox(Rect::new(0.0, 0.0, iw as f64, ih as f64)); let Some(drawn) = self.drawn_xml(b).and_then(|xml| with_id(&xml, DRAWN_ID)) else { return }; let svg = format!( "{drawn}", matrix(outer), - x1 - x0, - y1 - y0, + iw, + ih, matrix(place), base64(&png) ); @@ -1419,19 +1553,65 @@ impl SvgFilterFx { } let Some(mut small) = tiny_skia::Pixmap::new(sw, sh) else { return }; resvg::render(&tree, tiny_skia::Transform::identity(), &mut small.as_mut()); - let out = if s < 1.0 { + let out = if back == Affine::IDENTITY { + small + } else { let Some(mut full) = tiny_skia::Pixmap::new(w as u32, h as u32) else { return }; let paint = tiny_skia::PixmapPaint { quality: tiny_skia::FilterQuality::Bilinear, ..Default::default() }; - let up = (1.0 / s) as f32; - full.draw_pixmap(0, 0, small.as_ref(), &paint, tiny_skia::Transform::from_scale(up, up), None); + let [a, b, c, d, e, f] = back.as_coeffs().map(|v| v as f32); + full.draw_pixmap(0, 0, small.as_ref(), &paint, tiny_skia::Transform::from_row(a, b, c, d, e, f), None); full - } else { - small }; if out.data().len() == data.len() { data.copy_from_slice(out.data()); } } + + /// The canvas a filter whose user space is turned, skewed or scaled unevenly runs on, for a + /// `w` × `h` raster lying in the document as `space` says, at resolution `s` + /// ([`raster_resolution`]), whose art draws within `drawn` (raster pixels): its axes are the user + /// space's, so the filter's offsets, blurs and other lengths run along them as SVG 1.1 measures + /// them, and it covers what the raster shows. Along each of its axes its pixels are about as + /// large as the raster's at `s`, and coarser when it would hold more than [`TURNED_ROOM`] times + /// as many pixels as the raster does at `s`, and when a morphology radius or kernel unit would + /// span more than 32 of its pixels or a blur's standard deviation more than 512 (a length in the + /// object's box measured against the art's box on the canvas). Returns its size, the map from + /// user space to it, and the map from it to the raster's pixels; `None` when the spaces can't + /// be measured. + fn turned_canvas(&self, w: usize, h: usize, s: f64, drawn: Rect, space: &PixelSpace) -> Option<(u32, u32, Affine, Affine)> { + let to_px = space.to_doc.inverse() * self.to_doc(); + let from_px = to_px.inverse(); + let ub = from_px.transform_rect_bbox(Rect::new(0.0, 0.0, w as f64, h as f64)); + let most = ((w as f64 * s).ceil().max(1.0) * (h as f64 * s).ceil().max(1.0) * TURNED_ROOM).max(1.0); + // Canvas pixels a unit along each axis of the user space: as many as the raster's at `s`. + let [a, b, c, d, _, _] = to_px.as_coeffs(); + let (mut qx, mut qy) = (s * a.hypot(b), s * c.hypot(d)); + let pixels = ub.width() * qx * ub.height() * qy; + if pixels > most { + let k = (most / pixels).sqrt(); + (qx, qy) = (qx * k, qy * k); + } + // A length along an axis spans length × q canvas pixels, or length × the art's box on the + // canvas along that axis: both shrink with q. + let art = from_px.transform_rect_bbox(drawn); + for (length, cap) in [(self.window, MAX_WINDOW_PX), (self.blur, MAX_BLUR_PX)] { + let px = if self.box_units { length * (art.width() * qx).max(art.height() * qy) } else { length * qx.max(qy) }; + if px > cap { + let k = cap / px; + (qx, qy) = (qx * k, qy * k); + } + } + if !(qx.is_finite() && qx > 0.0 && qy.is_finite() && qy > 0.0 && ub.is_finite()) { + return None; + } + let (cw, ch) = ((ub.width() * qx).ceil().max(1.0), (ub.height() * qy).ceil().max(1.0)); + // Rounding up adds at most a row and a column. + if cw * ch > most + cw + ch + 1.0 { + return None; + } + let outer = Affine::scale_non_uniform(qx, qy) * Affine::translate(Vec2::new(-ub.x0, -ub.y0)); + Some((cw as u32, ch as u32, outer, to_px * outer.inverse())) + } } /// The farthest a filter's region reaches beyond the object, in points. @@ -1449,9 +1629,24 @@ fn drawn_box(data: &[u8], w: usize, h: usize) -> Option<(usize, usize, usize, us (x1 > x0 && y1 > y0).then_some((x0, y0, x1, y1)) } +/// The pixels of `data` (premultiplied RGBA8, `w` × `h`) drawn onto a `cw` × `ch` canvas through +/// `to_canvas` (the raster's pixels → the canvas's), cut to the box of the canvas pixels that aren't +/// transparent (the whole canvas when all are): a PNG of them, the box's corner on the canvas, and +/// its size. +fn on_canvas(data: &[u8], w: usize, h: usize, cw: u32, ch: u32, to_canvas: Affine) -> Option<(Vec, usize, usize, usize, usize)> { + let size = tiny_skia::IntSize::from_wh(u32::try_from(w).ok()?, u32::try_from(h).ok()?)?; + let raster = tiny_skia::Pixmap::from_vec(data.to_vec(), size)?; + let mut canvas = tiny_skia::Pixmap::new(cw, ch)?; + let paint = tiny_skia::PixmapPaint { quality: tiny_skia::FilterQuality::Bilinear, ..Default::default() }; + let [a, b, c, d, e, f] = to_canvas.as_coeffs().map(|v| v as f32); + canvas.draw_pixmap(0, 0, raster.as_ref(), &paint, tiny_skia::Transform::from_row(a, b, c, d, e, f), None); + let (cw, ch) = (cw as usize, ch as usize); + let (x0, y0, x1, y1) = drawn_box(canvas.data(), cw, ch).unwrap_or((0, 0, cw, ch)); + Some((png_of(canvas.data(), cw, x0, y0, x1, y1)?, x0, y0, x1 - x0, y1 - y0)) +} + /// 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 { @@ -1461,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/defaults.rs b/crates/effects/src/svg_filter/defaults.rs new file mode 100644 index 0000000000..95a84ca273 --- /dev/null +++ b/crates/effects/src/svg_filter/defaults.rs @@ -0,0 +1,249 @@ +//! The default SVG filters: the filters Effect › SVG Filters and Apply SVG Filter list in every +//! document. The set, the names and the values are VectorCraft's own, written with the filter +//! primitives of SVG 1.1 (). A default is not part of a +//! document until it is applied or edited there: the document then holds a copy under the +//! default's name, and that copy stands in the default's place in the lists. Every default computes +//! in sRGB (`color-interpolation-filters="sRGB"`), so art a filter passes through keeps its colors. + +use vectorcraft_doc::SvgFilter; + +/// A default SVG filter: its name (the `` element's `id`) and the element's XML. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DefaultFilter { + pub name: &'static str, + pub xml: &'static str, +} + +/// The default filters, in the order the lists show them. +pub const DEFAULT_FILTERS: [DefaultFilter; 14] = [ + DefaultFilter { + name: "Soft Blur", + xml: r#""#, + }, + DefaultFilter { + name: "Heavy Blur", + xml: r#""#, + }, + DefaultFilter { + name: "Soft Shadow", + xml: r#""#, + }, + DefaultFilter { + name: "Hard Shadow", + xml: r#""#, + }, + DefaultFilter { + name: "Glow", + xml: r##""##, + }, + DefaultFilter { + name: "Bevel", + xml: r##""##, + }, + DefaultFilter { + name: "Emboss", + xml: r#""#, + }, + DefaultFilter { + name: "Thicken", + xml: r#""#, + }, + DefaultFilter { + name: "Thin", + xml: r#""#, + }, + DefaultFilter { + name: "Rough Edges", + xml: r#""#, + }, + DefaultFilter { + name: "Grain", + xml: r#""#, + }, + DefaultFilter { + name: "Grayscale", + xml: r#""#, + }, + DefaultFilter { + name: "Invert", + xml: r#""#, + }, + DefaultFilter { + name: "Hue Shift", + xml: r#""#, + }, +]; + +/// The default filter named `name`. +pub fn default_filter(name: &str) -> Option { + DEFAULT_FILTERS.iter().copied().find(|f| f.name == name) +} + +impl DefaultFilter { + /// The filter as a document holds it once it is applied or edited there. + pub fn to_filter(self) -> SvgFilter { + SvgFilter { name: self.name.to_string(), xml: self.xml.to_string() } + } +} + +/// A filter of the lists ([`listed`]), and whether it is a default the document does not hold. +#[derive(Clone, Debug, PartialEq)] +pub struct Listed { + pub filter: SvgFilter, + /// A default the document has no filter named for: applying or editing it adds a copy. + pub default: bool, +} + +/// The filters Effect › SVG Filters and Apply SVG Filter list for a document that holds `held`, +/// and how many of them come first as the defaults: each default in [`DEFAULT_FILTERS`]' order (the +/// document's filter of that name in its place), then the document's other filters in their order. +pub fn listed(held: &[SvgFilter]) -> (Vec, usize) { + let mut out: Vec = DEFAULT_FILTERS + .iter() + .map(|d| match held.iter().find(|f| f.name == d.name) { + Some(f) => Listed { filter: f.clone(), default: false }, + None => Listed { filter: d.to_filter(), default: true }, + }) + .collect(); + let defaults = out.len(); + out.extend(held.iter().filter(|f| default_filter(&f.name).is_none()).map(|f| Listed { filter: f.clone(), default: false })); + (out, defaults) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + use vectorcraft_doc::Effect; + use vectorcraft_geom::{Affine, Point}; + + use super::*; + use crate::pixel::{Channels, PixelSpace}; + use crate::svg_filter::{SVG_FILTER, SvgFilterFx, check, with_id}; + use crate::{PixelFx, RasterFx, raster_effects}; + + /// A `w` × `w` raster whose pixels are one point wide. + fn space(w: usize) -> PixelSpace { + let wd = w as f64; + PixelSpace { + to_doc: Affine::scale(1.0), + px: 1.0, + center: Point::new(wd / 2.0, wd / 2.0), + size: vectorcraft_geom::Vec2::new(wd, wd), + channels: Channels::Rgb, + line: 1.0, + extent: 0.5 * wd.hypot(wd), + } + } + + /// The default named `name` as the renderer reads it. + fn fx(name: &str) -> SvgFilterFx { + let d = default_filter(name).unwrap_or_else(|| panic!("no default {name}")); + let e = Effect { id: SVG_FILTER.into(), params: json!({"name": d.name, "xml": d.xml}), visible: true }; + match raster_effects(&[e]).first() { + Some(RasterFx::Pixel(PixelFx::Svg(f))) => f.clone(), + other => panic!("{name}: {other:?}"), + } + } + + /// A 40 × 40 raster with an opaque square of `rgb` from 10 to 30, run through default `name`. + fn run(name: &str, rgb: [u8; 3]) -> Vec { + let mut data: Vec = (0..40usize) + .flat_map(|y| (0..40usize).map(move |x| (x, y))) + .flat_map(|(x, y)| if (10..30).contains(&x) && (10..30).contains(&y) { [rgb[0], rgb[1], rgb[2], 255] } else { [0; 4] }) + .collect(); + fx(name).apply(&mut data, 40, 40, &space(40)); + data + } + + fn at(d: &[u8], x: usize, y: usize) -> [u8; 4] { + let i = (y * 40 + x) * 4; + [d[i], d[i + 1], d[i + 2], d[i + 3]] + } + + #[test] + fn every_default_is_a_filter_the_check_takes_under_its_own_name() { + let mut seen = std::collections::BTreeSet::new(); + for d in DEFAULT_FILTERS { + assert_eq!(check(d.xml), Ok(d.name.to_string()), "{}", d.name); + assert!(seen.insert(d.name), "{} is listed twice", d.name); + assert_eq!(d.name, d.name.trim()); + // Edit SVG Filter keeps the name by writing it as the id: a default's code comes back as it is. + assert_eq!(with_id(d.xml, d.name).as_deref(), Some(d.xml), "{}", d.name); + assert_eq!(default_filter(d.name), Some(d)); + assert!(d.xml.contains(r#" color-interpolation-filters="sRGB""#), "{} computes in sRGB", d.name); + } + assert!(DEFAULT_FILTERS.len() <= SvgFilter::MAX); + assert_eq!(default_filter("soft blur"), None, "names match exactly"); + } + + #[test] + fn every_default_draws_and_is_written_to_svg_as_a_filter() { + let plain = { + let mut d = vec![0u8; 40 * 40 * 4]; + for y in 10..30 { + for x in 10..30 { + d[(y * 40 + x) * 4..(y * 40 + x) * 4 + 4].copy_from_slice(&[200, 60, 20, 255]); + } + } + d + }; + for d in DEFAULT_FILTERS { + assert_ne!(run(d.name, [200, 60, 20]), plain, "{} changes what is drawn", d.name); + assert!(fx(d.name).writes_as_svg11(), "{} is written as SVG 1.1", d.name); + } + } + + /// The color defaults against SVG 1.1's own arithmetic, in sRGB as each filter asks. + #[test] + fn the_color_defaults_compute_what_svg_1_1_defines() { + let near = |got: [u8; 4], want: [u8; 4]| got.iter().zip(want).all(|(g, w)| g.abs_diff(w) <= 1); + // feComponentTransfer, type="table" with values 1 0: C' = 1 - C (§15.11). + let inv = at(&run("Invert", [200, 60, 20]), 20, 20); + assert!(near(inv, [55, 195, 235, 255]), "{inv:?}"); + // feColorMatrix type="saturate" values="0": every channel is 0.213 R + 0.715 G + 0.072 B (§15.10). + let grey = at(&run("Grayscale", [200, 60, 20]), 20, 20); + let l = (0.213 * 200.0 + 0.715 * 60.0 + 0.072 * 20.0f64).round() as u8; + assert!(near(grey, [l, l, l, 255]), "{grey:?} for {l}"); + // feColorMatrix type="hueRotate" values="180" (§15.10): cos = -1 and sin = 0 leave + // R' = (2·0.213 - 1) R + 2·0.715 G + 2·0.072 B, and likewise for G' and B'. + let hue = at(&run("Hue Shift", [200, 60, 20]), 20, 20); + let lum2 = 2.0 * (0.213 * 200.0 + 0.715 * 60.0 + 0.072 * 20.0f64); + let turned = [lum2 - 200.0, lum2 - 60.0, lum2 - 20.0].map(|v| v.round().clamp(0.0, 255.0) as u8); + assert!(near(hue, [turned[0], turned[1], turned[2], 255]), "{hue:?} for {turned:?}"); + } + + /// The shape defaults against what their primitives define: an offset copy of the alpha behind + /// the art (feOffset, §15.21), and a shape grown or shrunk by its radius (feMorphology, §15.20). + #[test] + fn the_shape_defaults_move_and_resize_the_alpha() { + let shadow = run("Hard Shadow", [200, 60, 20]); + assert_eq!(at(&shadow, 20, 20), [200, 60, 20, 255], "the art is on top"); + // Right of and below the art by up to 3: black at 60% alpha (premultiplied 153). + assert_eq!(at(&shadow, 31, 31), [0, 0, 0, 153]); + assert_eq!(at(&shadow, 34, 34)[3], 0, "past the offset"); + assert_eq!(at(&shadow, 8, 8)[3], 0, "nothing up and left"); + let thick = run("Thicken", [200, 60, 20]); + assert_eq!((at(&thick, 9, 20)[3], at(&thick, 7, 20)[3]), (255, 0), "grown by its radius"); + let thin = run("Thin", [200, 60, 20]); + assert_eq!((at(&thin, 10, 20)[3], at(&thin, 13, 20)[3]), (0, 255), "shrunk by its radius"); + let soft = run("Soft Shadow", [200, 60, 20]); + assert_eq!(at(&soft, 20, 20), [200, 60, 20, 255]); + let below = at(&soft, 33, 33); + assert!(below[3] > 0 && below[3] < 128 && below[0] == 0, "a blurred, half-strength shadow: {below:?}"); + } + + #[test] + fn the_lists_show_the_defaults_first_with_the_documents_copy_in_place() { + let (all, defaults) = listed(&[]); + assert_eq!((all.len(), defaults), (DEFAULT_FILTERS.len(), DEFAULT_FILTERS.len())); + assert!(all.iter().all(|l| l.default)); + let mine = SvgFilter { name: "Mine".into(), xml: "".into() }; + let glow = SvgFilter { name: "Glow".into(), xml: "".into() }; + let (all, defaults) = listed(&[mine.clone(), glow.clone()]); + assert_eq!((all.len(), defaults), (DEFAULT_FILTERS.len() + 1, DEFAULT_FILTERS.len())); + let at = DEFAULT_FILTERS.iter().position(|d| d.name == "Glow").unwrap(); + assert_eq!(all[at], Listed { filter: glow, default: false }, "the document's Glow where the default was"); + assert_eq!(all.last(), Some(&Listed { filter: mine, default: false })); + assert_eq!(all.iter().filter(|l| l.default).count(), DEFAULT_FILTERS.len() - 1); + } +} diff --git a/crates/effects/src/svg_filter/tests.rs b/crates/effects/src/svg_filter/tests.rs index df1956f3f0..ddd19f5580 100644 --- a/crates/effects/src/svg_filter/tests.rs +++ b/crates/effects/src/svg_filter/tests.rs @@ -10,7 +10,15 @@ use crate::{PixelFx, RasterFx, raster_effects}; /// resolution whose pixels are `line` points wide. fn space(w: usize, h: usize, px: f64, line: f64) -> PixelSpace { let (wd, hd) = (w as f64 * px, h as f64 * px); - PixelSpace { to_doc: Affine::scale(px), px, center: Point::new(wd / 2.0, hd / 2.0), channels: Channels::Rgb, line, extent: 0.5 * wd.hypot(hd) } + PixelSpace { + to_doc: Affine::scale(px), + px, + center: Point::new(wd / 2.0, hd / 2.0), + size: vectorcraft_geom::Vec2::new(wd, hd), + channels: Channels::Rgb, + line, + extent: 0.5 * wd.hypot(hd), + } } /// `w` × `h` premultiplied pixels: `f(x, y)` each. @@ -214,6 +222,154 @@ fn user_space_starts_at_the_origin() { assert!((filter(json!({ "xml": half, "origin": [-10.0, 0.0] })).outset(b) - 10.0).abs() < 1e-9); } +/// The opacity of `data` (`w` wide) after the filter `xml` with `params` runs on a blue square +/// over 10..20 pt of a 40 pt raster one point a pixel, at each of `points`. +fn turned_run(xml: &str, params: serde_json::Value, points: &[(usize, usize)]) -> Vec { + let w = 40; + let mut data = image(w, w, |x, y| if (10..20).contains(&x) && (10..20).contains(&y) { [0, 0, 255, 255] } else { [0; 4] }); + let mut p = params; + p["xml"] = json!(xml); + filter(p).apply(&mut data, w, w, &space(w, w, 1.0, 1.0)); + points.iter().map(|&(x, y)| at(&data, w, x, y)[3]).collect() +} + +const SHIFT_X: &str = r#""#; + +/// With `axes`, the filter runs in its turned or skewed user space: an offset along its x axis +/// moves the art along that axis in the document (SVG 1.1 measures a primitive's lengths in the +/// user space of the element the filter is on). +#[test] +fn a_turned_user_space_moves_the_art_along_its_own_axes() { + // The square spans 10..20 pt; moved 4 pt along x it covers 14..24 across. + let points = [(22, 15), (15, 22), (12, 11)]; + assert_eq!(turned_run(SHIFT_X, json!({}), &points), [255, 0, 0], "the document's axes: to the right"); + // Turned a quarter turn: the filter's x axis points down the page. + let down = turned_run(SHIFT_X, json!({ "axes": [0.0, 1.0, -1.0, 0.0] }), &points); + assert_eq!(down, [0, 255, 0], "moved down, not to the right"); + // Skewed: one unit along y is one across and one down, so dy 4 moves the art 4 pt each way. + let shift_y = r#""#; + let skewed = turned_run(shift_y, json!({ "axes": [1.0, 0.0, 1.0, 1.0] }), &[(22, 22), (11, 22), (11, 11)]); + assert!(skewed[0] > 200 && skewed[1] < 60 && skewed[2] < 60, "moved across and down: {skewed:?}"); +} + +#[test] +fn axes_the_effect_cannot_measure_are_not_drawn() { + for axes in [json!([0, 0, 0, 0]), json!([1, 2]), json!([1, 0, 0, "1"]), json!([2000, 0, 0, 1]), json!([0.01, 0, 0, 0.01]), json!("turned")] { + let e = Effect { id: SVG_FILTER.into(), params: json!({ "xml": SHIFT_X, "axes": axes }), visible: true }; + assert!(raster_effects(&[e]).is_empty(), "{axes}: drawn without it"); + assert!(valid_axes(&axes).is_none(), "{axes}"); + } + assert_eq!(valid_axes(&json!([0, 1, -1, 0])), Some(Affine::new([0.0, 1.0, -1.0, 0.0, 0.0, 0.0]))); +} + +/// A region measured against the object's box is measured against its box in the turned user +/// space: a diamond turned an eighth of a turn is a square there, and a flood over 0..100% of it +/// covers the diamond alone. +#[test] +fn a_turned_region_is_measured_against_the_box_in_its_user_space() { + let w = 40; + let diamond = |x: usize, y: usize| (x as f64 - 19.5).abs() + (y as f64 - 19.5).abs() <= 10.0; + let mut data = image(w, w, |x, y| if diamond(x, y) { [0, 0, 255, 255] } else { [0; 4] }); + let flood = r##""##; + let h = std::f64::consts::FRAC_1_SQRT_2; + filter(json!({ "xml": flood, "axes": [h, h, -h, h] })).apply(&mut data, w, w, &space(w, w, 1.0, 1.0)); + assert_eq!(at(&data, w, 20, 20), [255, 0, 0, 255], "inside the diamond"); + assert!(at(&data, w, 12, 12)[3] < 40, "outside the diamond, inside its box on the page: {:?}", at(&data, w, 12, 12)); +} + +/// In a turned user space, a region in the object's bounding box (the default `filterUnits`) and a +/// primitive's lengths in it (`primitiveUnits="objectBoundingBox"`) are measured against the +/// object's box there: on a diamond turned an eighth of a turn, a flood over 0..100% of the box +/// covers the diamond alone. +#[test] +fn a_turned_filter_measures_box_units_against_the_box_in_its_user_space() { + let w = 40; + let h = std::f64::consts::FRAC_1_SQRT_2; + let region = r##""##; + let primitive = r##""##; + for xml in [region, primitive] { + let diamond = |x: usize, y: usize| (x as f64 - 19.5).abs() + (y as f64 - 19.5).abs() <= 10.0; + let mut data = image(w, w, |x, y| if diamond(x, y) { [0, 0, 255, 255] } else { [0; 4] }); + filter(json!({ "xml": xml, "axes": [h, h, -h, h] })).apply(&mut data, w, w, &space(w, w, 1.0, 1.0)); + assert_eq!(at(&data, w, 20, 20), [255, 0, 0, 255], "{xml}: inside the diamond"); + assert!(at(&data, w, 12, 12)[3] < 40, "{xml}: outside the diamond, inside its box on the page: {:?}", at(&data, w, 12, 12)); + } +} + +/// SVG import stores a filter's user space again only when `scale` and `axes` together stay within +/// what it holds: each alone can be valid while their product is not. +#[test] +fn a_user_space_opens_again_only_within_what_import_stores() { + let opens = |scale: f64, axes: serde_json::Value| filter(json!({ "xml": SHIFT_X, "scale": scale, "axes": axes })).opens_again(); + assert!(opens(1000.0, json!(null))); + assert!(opens(2.0, json!([0.0, 1.0, -1.0, 0.0]))); + assert!(!opens(1000.0, json!([2.0, 0.0, 0.0, 2.0])), "scale 2000 across"); + assert!(!opens(0.001, json!([0.5, 0.0, 0.0, 0.5])), "scale 0.0005 across"); + let space = user_space(Affine::new([0.0, 2.0, -2.0, 0.0, 5.0, 6.0])).unwrap(); + assert_eq!((space.scale, space.origin, space.axes), (2.0, [5.0, 6.0], Some([0.0, 1.0, -1.0, 0.0]))); +} + +/// The region of a turned filter reaches as far as its turned box does. +#[test] +fn a_turned_region_reaches_along_the_turned_axes() { + let b = Rect::new(0.0, 0.0, 50.0, 50.0); + let user = r#""#; + assert!((filter(json!({ "xml": user })).outset(b) - 45.0).abs() < 1e-9, "45 pt below the box"); + // A quarter turn: user y runs to the left of the page, so -5..95 of it lies 95 pt left of the box. + assert!((filter(json!({ "xml": user, "axes": [0.0, 1.0, -1.0, 0.0] })).outset(b) - 95.0).abs() < 1e-9); +} + +/// A filter skewed as far as `axes` allows runs on a canvas no larger than four times the raster's +/// pixels, however far the skew spreads the raster's box in its user space. +#[test] +fn a_skewed_filter_runs_within_its_pixel_budget() { + let (w, h) = (64, 48); + let f = filter(json!({ "xml": SHIFT_X, "axes": [1.0, 0.0, 999.0, 1.0] })); + let all = Rect::new(0.0, 0.0, w as f64, h as f64); + let (cw, ch, ..) = f.turned_canvas(w, h, 1.0, all, &space(w, h, 1.0, 1.0)).unwrap(); + let (cw, ch) = (f64::from(cw), f64::from(ch)); + assert!(cw * ch <= TURNED_ROOM * (w * h) as f64 + cw + ch + 1.0, "{cw} × {ch}"); + // It still draws. + let mut data = image(w, h, |x, y| if (20..40).contains(&x) && (10..30).contains(&y) { [0, 0, 255, 255] } else { [0; 4] }); + f.apply(&mut data, w, h, &space(w, h, 1.0, 1.0)); + // A plain quarter turn keeps the raster's own pixel size. + let turned = filter(json!({ "xml": SHIFT_X, "axes": [0.0, 1.0, -1.0, 0.0] })); + let (cw, ch, outer, _) = turned.turned_canvas(w, h, 1.0, all, &space(w, h, 1.0, 1.0)).unwrap(); + assert_eq!((cw, ch), (48, 64)); + assert!((outer.determinant() - 1.0).abs() < 1e-9); + // Stretched 100 times across and squeezed 100 times down: each canvas axis keeps the raster's + // detail along it, not one column of it. + let stretched = filter(json!({ "xml": SHIFT_X, "axes": [100.0, 0.0, 0.0, 0.01] })); + let (cw, ch, ..) = stretched.turned_canvas(100, 100, 1.0, Rect::new(0.0, 0.0, 100.0, 100.0), &space(100, 100, 1.0, 1.0)).unwrap(); + assert_eq!((cw, ch), (100, 100)); +} + +/// On a far skewed canvas, a radius or a standard deviation in the object's box spans no more +/// canvas pixels than the caps allow: it is measured against the art's box on the canvas, which the +/// skew spreads far wider than the art's box in the raster. +#[test] +fn a_skewed_filter_keeps_box_lengths_within_the_caps_on_its_canvas() { + let (w, h) = (64, 48); + let sp = space(w, h, 1.0, 1.0); + let drawn = Rect::new(20.0, 10.0, 40.0, 30.0); + for (xml, length, cap) in [ + ("", 1.5, MAX_WINDOW_PX), + ("", 20.0, MAX_BLUR_PX), + ] { + let f = filter(json!({ "xml": xml, "axes": [1.0, 0.0, 999.0, 1.0] })); + let (_, _, outer, _) = f.turned_canvas(w, h, 1.0, drawn, &sp).unwrap(); + // The art's box on the canvas: the drawn pixels taken into user space, then onto the canvas. + let art = (outer * f.to_doc().inverse() * sp.to_doc).transform_rect_bbox(drawn); + let px = length * art.width().max(art.height()); + assert!(px <= cap + 1e-6, "{xml}: {px} canvas pixels"); + } + // A user-space radius spans no more than 32 canvas pixels along either axis. + let f = filter(json!({ "xml": "", "scale": 1000.0, "axes": [1.0, 0.0, 999.0, 1.0] })); + let (_, _, outer, _) = f.turned_canvas(w, h, 1.0, drawn, &sp).unwrap(); + let [qx, _, _, qy, _, _] = outer.as_coeffs(); + assert!(100.0 * qx.max(qy) <= MAX_WINDOW_PX + 1e-6, "{qx} {qy}"); +} + #[test] fn runs_no_finer_than_the_raster_effects_resolution() { let w = 16; @@ -364,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(_)))); @@ -391,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]); @@ -440,7 +599,8 @@ fn a_region_measured_against_the_box_is_written_out() { let far = r#""#; let f = filter(json!({ "xml": far, "origin": [10.0, 0.0] })); assert_eq!( - f.written_xml(Rect::new(10.0, 0.0, 30.0, 10.0)).as_deref(), + // The object over 10..30 pt of the page: 0..20 of the user space that starts at the origin. + f.written_xml(Rect::new(0.0, 0.0, 20.0, 10.0)).as_deref(), Some(r#""#) ); let plain = filter(json!({ "xml": RED_FLOOD })); diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index 0023fc5b16..ac340224c6 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -4,12 +4,14 @@ use vectorcraft_geom::{Affine, PathData, Point, Rect, Shape, SubPath, shapes}; use super::*; +mod clipfx; mod imageoutline; mod painted; mod rasterfollow; mod scale; mod solidcontext; mod transformfx; +mod typestroke; fn fx(id: &str, params: Value) -> Effect { Effect { id: id.into(), params, visible: true } @@ -1849,6 +1851,7 @@ fn rasterize_compose_leaves_the_raster_alone_when_the_sizes_do_not_fit() { to_doc: Affine::IDENTITY, px: 1.0, center: Point::new(1.0, 1.0), + size: vectorcraft_geom::Vec2::new(2.0, 2.0), channels: pixel::Channels::Rgb, line: 1.0, extent: std::f64::consts::SQRT_2, diff --git a/crates/effects/src/tests/clipfx.rs b/crates/effects/src/tests/clipfx.rs new file mode 100644 index 0000000000..57566fbb28 --- /dev/null +++ b/crates/effects/src/tests/clipfx.rs @@ -0,0 +1,545 @@ +//! Live effects on the clipping path of a clip group: the region it clips to takes the shape its +//! geometry effects give it, on the canvas as in an export. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Rect, Shape, shapes}; + +use crate::{bake_document, clip_outline}; + +fn fx(id: &str, params: Value) -> Effect { + Effect { id: id.into(), params, visible: true } +} + +/// A 100 pt square clipping path at (50, 50) with `effects`. +fn clipping_path(id: u64, effects: Vec) -> Node { + let mut p = Node::path(NodeId(id), shapes::rectangle(Rect::new(50.0, 50.0, 150.0, 150.0)), Appearance::default()); + if let NodeKind::Path { clipping, .. } = &mut p.kind { + *clipping = true; + } + p.appearance.effects = effects; + p +} + +/// A clip group: `clip` clipping a red 200 pt square at the origin. +fn clip_group(id: u64, clip: Node) -> Node { + let art = Node::path( + NodeId(id + 100), + shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), + Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0), + ); + Node::new(NodeId(id), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(art)], clip: true }) +} + +fn bounds(n: &Node) -> Rect { + clip_outline(n).map(|(bp, _)| bp.bounding_box()).unwrap() +} + +/// The clipping path of the first clip group in `doc` after an export bakes it. +fn baked_clip(doc: &Document) -> Arc { + fn first(n: &Arc) -> Option> { + match &n.kind { + NodeKind::Group { children, clip: true } => children.first().cloned(), + _ => n.children()?.iter().find_map(first), + } + } + let baked = bake_document(doc).unwrap(); + baked.layers.iter().find_map(first).unwrap() +} + +#[test] +fn transform_moves_the_clip() { + let clip = clipping_path(1, vec![fx("distort.transform", json!({"moveH": 60}))]); + let b = bounds(&clip); + assert!((b.x0 - 110.0).abs() < 1e-6 && (b.x1 - 210.0).abs() < 1e-6, "the clip moves with the clipping path: {b:?}"); + assert!((b.y0 - 50.0).abs() < 1e-6 && (b.y1 - 150.0).abs() < 1e-6, "{b:?}"); +} + +#[test] +fn roughen_clips_as_an_export_does() { + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + let group = clip_group(1, clipping_path(2, vec![fx("distort.roughen", json!({"size": 10, "detail": 10, "relative": false}))])); + d.insert(Some(layer), 0, group.clone()).unwrap(); + let NodeKind::Group { children, .. } = &group.kind else { panic!("not a group") }; + let live = clip_outline(&children[0]).unwrap(); + let exported = clip_outline(&baked_clip(&d)).unwrap(); + assert_eq!(live.1, exported.1); + assert_eq!(live.0, exported.0, "the canvas clips by the outline the export writes"); + assert_ne!(live.0.bounding_box(), Rect::new(50.0, 50.0, 150.0, 150.0), "the roughened outline, not the plain square"); +} + +#[test] +fn nested_members_keep_their_effects() { + // A group as the clipping path: its member's Transform effect moves its part of the region. + let moved = clipping_path(2, vec![fx("distort.transform", json!({"moveV": 60}))]); + let group = Node::group(NodeId(1), vec![Arc::new(moved)]); + let b = bounds(&group); + assert!((b.y0 - 110.0).abs() < 1e-6 && (b.y1 - 210.0).abs() < 1e-6, "{b:?}"); + // A clip group as the clipping path clips by its own clipping path, effects and all. + let nested = clip_group(3, clipping_path(4, vec![fx("distort.transform", json!({"moveH": -30}))])); + let b = bounds(&nested); + assert!((b.x0 - 20.0).abs() < 1e-6 && (b.x1 - 120.0).abs() < 1e-6, "{b:?}"); + // So does the nested clip group's own effect. + let mut nested = clip_group(7, clipping_path(8, vec![])); + nested.appearance.effects.push(fx("distort.transform", json!({"moveH": 30}))); + let b = bounds(&nested); + assert!((b.x0 - 80.0).abs() < 1e-6 && (b.x1 - 180.0).abs() < 1e-6, "{b:?}"); + // The group's own Transform effect applies on top of its members'. + let mut group = Node::group(NodeId(5), vec![Arc::new(clipping_path(6, vec![fx("distort.transform", json!({"moveV": 60}))]))]); + group.appearance.effects.push(fx("distort.transform", json!({"moveH": 10}))); + let b = bounds(&group); + assert!((b.x0 - 60.0).abs() < 1e-6 && (b.y0 - 110.0).abs() < 1e-6, "{b:?}"); +} + +#[test] +fn a_roughened_group_clips_as_an_export_does() { + // Two members side by side, Roughen on the group: each member is roughened, as in the export. + let member = |id: u64, x: f64| { + Arc::new(Node::path( + NodeId(id), + shapes::rectangle(Rect::new(x, 50.0, x + 40.0, 150.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + )) + }; + let mut clip = Node::group(NodeId(2), vec![member(3, 50.0), member(4, 110.0)]); + clip.appearance.effects.push(fx("distort.roughen", json!({"size": 10, "detail": 10, "relative": false}))); + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, clip_group(1, clip.clone())).unwrap(); + let live = clip_outline(&clip).unwrap(); + assert_eq!(live.0, clip_outline(&baked_clip(&d)).unwrap().0, "the canvas clips by the outline the export writes"); + assert_ne!(live.0.bounding_box(), Rect::new(50.0, 50.0, 150.0, 150.0)); +} + +#[test] +fn a_compound_paths_member_keeps_its_effect() { + // A ring whose hole a Transform effect moves 20 pt right, as the export bakes it. + let ring = |effects: Vec| { + let outer = Node::path(NodeId(3), shapes::rectangle(Rect::new(50.0, 50.0, 150.0, 150.0)), Appearance::default()); + let mut hole = Node::path(NodeId(4), shapes::rectangle(Rect::new(75.0, 75.0, 125.0, 125.0)), Appearance::default()); + hole.appearance.effects = effects; + Node::new(NodeId(2), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(hole)], rule: vectorcraft_geom::FillRule::EvenOdd }) + }; + let moved = ring(vec![fx("distort.transform", json!({"moveH": 20}))]); + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, clip_group(1, moved.clone())).unwrap(); + let live = clip_outline(&moved).unwrap(); + assert_eq!(live, clip_outline(&baked_clip(&d)).unwrap(), "the canvas clips by the outline the export writes"); + assert_ne!(live, clip_outline(&ring(vec![])).unwrap(), "the hole moves"); + // With a Transform of the compound path's own moving the whole ring 10 pt down after it. + let mut both = moved.clone(); + both.appearance.effects.push(fx("distort.transform", json!({"moveV": 10}))); + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, clip_group(1, both.clone())).unwrap(); + let live = clip_outline(&both).unwrap(); + assert_eq!(live, clip_outline(&baked_clip(&d)).unwrap(), "the canvas clips by the outline the export writes"); + assert_ne!(live.0.bounding_box(), clip_outline(&moved).unwrap().0.bounding_box(), "the ring moves down"); +} + +#[test] +fn the_clipping_paths_effects_apply_before_the_clip_groups() { + // Scale 50 % on the clipping path, then Offset Path 10 on its clip group: the region is the + // half-size square grown by 10, as if the clipping path had been drawn at half size. + let group = |clip: Node| { + let mut g = clip_group(1, clip); + g.appearance.effects.push(fx("path.offsetPath", json!({"offset": 10}))); + g + }; + let scaled = group(clipping_path(2, vec![fx("distort.transform", json!({"scaleH": 50, "scaleV": 50}))])); + let mut half = clipping_path(2, vec![]); + if let NodeKind::Path { path, .. } = &mut half.kind { + *path = shapes::rectangle(Rect::new(75.0, 75.0, 125.0, 125.0)); + } + let want = bounds(&group(half)); + let got = bounds(&scaled); + assert!((got.x0 - want.x0).abs() < 0.5 && (got.x1 - want.x1).abs() < 0.5, "{got:?} against {want:?}"); + assert!((want.x0 - 65.0).abs() < 0.5, "{want:?}"); + // The clip group as the canvas evaluates it for its effect, and as an export bakes it. + let evaluated = crate::evaluate_container(None, &scaled).unwrap(); + let NodeKind::Group { children, clip: true } = &evaluated.kind else { panic!("not a clip group") }; + let b = clip_outline(&children[0]).unwrap().0.bounding_box(); + assert!((b.x0 - want.x0).abs() < 0.5 && (b.x1 - want.x1).abs() < 0.5, "evaluated: {b:?} against {want:?}"); + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, scaled).unwrap(); + let b = clip_outline(&baked_clip(&d)).unwrap().0.bounding_box(); + assert!((b.x0 - want.x0).abs() < 0.5 && (b.x1 - want.x1).abs() < 0.5, "exported: {b:?} against {want:?}"); +} + +#[test] +fn a_clip_group_with_a_fill_or_stroke_of_its_own_clips_as_the_canvas_does() { + // A clip group with a fill or a stroke of its own and no effects: the export turns its paint + // into art and still clips by the outline the canvas clips by, Transform copies included. + let items = [ + vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK))), + vectorcraft_doc::AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::BLACK), 2.0)), + ]; + let copies = || fx("distort.transform", json!({"moveH": 60, "copies": 1})); + let roughen = fx("distort.roughen", json!({"size": 10, "detail": 10, "relative": false})); + // A ring: a compound path of two squares with effects `own`, its hole with effects `hole_fx`. + let ring = |hole_fx: Vec, own: Vec| { + let outer = Node::path(NodeId(3), shapes::rectangle(Rect::new(50.0, 50.0, 150.0, 150.0)), Appearance::default()); + let mut hole = Node::path(NodeId(4), shapes::rectangle(Rect::new(75.0, 75.0, 125.0, 125.0)), Appearance::default()); + hole.appearance.effects = hole_fx; + let mut c = + Node::new(NodeId(2), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(hole)], rule: vectorcraft_geom::FillRule::EvenOdd }); + c.appearance.effects = own; + c + }; + let clips = [ + ("copies", clipping_path(2, vec![copies()])), + ("roughen", clipping_path(2, vec![roughen])), + ("a compound path's copies", ring(vec![], vec![copies()])), + ("a compound path member's copies", ring(vec![copies()], vec![])), + ]; + for item in &items { + for (what, clip) in &clips { + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + let live = clip_outline(clip).unwrap(); + let mut group = clip_group(1, clip.clone()); + group.appearance.items.push(item.clone()); + d.insert(Some(layer), 0, group).unwrap(); + let exported = clip_outline(&baked_clip(&d)).unwrap(); + assert_eq!(live, exported, "{what} with {item:?}: the canvas clips by the outline the export writes"); + } + } + let b = bounds(&clips[0].1); + assert!((b.x0 - 50.0).abs() < 1e-6 && (b.x1 - 210.0).abs() < 1e-6, "the clip covers both copies: {b:?}"); +} + +#[test] +fn nested_effects_apply_before_the_clip_groups() { + // The clip group grows its clipping path by 10 (Offset Path). Inside the clipping path a + // Transform moves a member 60 pt right: the region grows from the moved member. + let evaluated = |clip: Node| { + let mut g = clip_group(1, clip); + g.appearance.effects.push(fx("path.offsetPath", json!({"offset": 10}))); + let e = crate::evaluate_container(None, &g).unwrap(); + let NodeKind::Group { children, clip: true } = &e.kind else { panic!("not a clip group") }; + clip_outline(&children[0]).unwrap().0.bounding_box() + }; + let moved = || clipping_path(3, vec![fx("distort.transform", json!({"moveH": 60}))]); + let close = |a: Rect, b: Rect| (a.x0 - b.x0).abs() < 0.5 && (a.x1 - b.x1).abs() < 0.5 && (a.y0 - b.y0).abs() < 0.5; + let want = Rect::new(100.0, 40.0, 220.0, 160.0); + // A group holding the member. + let b = evaluated(Node::group(NodeId(2), vec![Arc::new(moved())])); + assert!(close(b, want), "group: {b:?}"); + // A compound path of the member, with a Transform of its own moving it 10 pt down. + let mut compound = Node::new(NodeId(2), NodeKind::Compound { children: vec![Arc::new(moved())], rule: vectorcraft_geom::FillRule::NonZero }); + compound.appearance.effects.push(fx("distort.transform", json!({"moveV": 10}))); + let b = evaluated(compound); + assert!(close(b, Rect::new(100.0, 50.0, 220.0, 170.0)), "compound: {b:?}"); +} + +#[test] +fn clipping_type_keeps_its_effect_where_other_type_stays_type() { + // Type moved 30 pt right by its Transform clips a red square, beside other type, in a group + // that a Transform moves 10 pt down: the export keeps the other type as type and outlines the + // clipping type, which still clips where the canvas clips. + use vectorcraft_doc::text::{CharStyle, TextObject}; + let text = |id: u64, effects: Vec| { + let style = CharStyle { size: 40.0, fill: Paint::solid(Color::BLACK), ..Default::default() }; + let mut t = Node::new(NodeId(id), NodeKind::Text(Box::new(TextObject::point(vectorcraft_geom::Point::new(5.0, 60.0), "IIII", style)))); + t.appearance.effects = effects; + t + }; + let clipped = clip_group(2, text(3, vec![fx("distort.transform", json!({"moveH": 30}))])); + let mut outer = Node::group(NodeId(1), vec![Arc::new(clipped), Arc::new(text(5, vec![]))]); + outer.appearance.effects.push(fx("distort.transform", json!({"moveV": 10}))); + fn clip_of(n: &Node) -> Option { + match &n.kind { + NodeKind::Group { children, clip: true } => Some(clip_outline(children.first()?)?.0.bounding_box()), + _ => n.children()?.iter().find_map(|c| clip_of(c)), + } + } + if vectorcraft_text::CRAFT_FONTS.is_empty() { + eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)"); + return; + } + let plain = clip_outline(&text(3, vec![])).unwrap().0.bounding_box(); + let canvas = clip_of(&crate::evaluate_container(None, &outer).unwrap()).unwrap(); + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, outer).unwrap(); + let baked = bake_document(&d).unwrap(); + let mut exported = None; + for l in &baked.layers { + exported = exported.or_else(|| clip_of(l)); + } + let exported = exported.unwrap(); + assert!((canvas.x0 - plain.x0 - 30.0).abs() < 0.5 && (canvas.y0 - plain.y0 - 10.0).abs() < 0.5, "{canvas:?} from {plain:?}"); + assert!((exported.x0 - canvas.x0).abs() < 0.5 && (exported.y0 - canvas.y0).abs() < 0.5, "exported {exported:?}, canvas {canvas:?}"); + // The outlined clipping type keeps its black fill, which paints behind the clipped art. + let outlined = crate::reshape::clipping_text_outline(&text(3, vec![fx("distort.transform", json!({"moveH": 30}))])).unwrap(); + fn fills(n: &Node) -> usize { + n.appearance.items.iter().filter(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(f) if f.paint != Paint::None)).count() + + n.children().into_iter().flatten().map(|c| fills(c)).sum::() + } + assert!(fills(&outlined) > 0, "{outlined:?}"); +} + +#[test] +fn a_painted_clipping_paths_gradient_follows_its_effect() { + // A clipping path filled with a gradient placed across it, moved 60 pt right by its Transform + // effect, in a clip group with an effect of its own: the gradient moves with the path. + use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + let geom = GradientGeom { start: (50.0, 100.0).into(), end: (150.0, 100.0).into(), aspect: 1.0, focal: None }; + let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..GradientPaint::new(Gradient::new(GradientKind::Linear, stops)) })); + let mut clip = clipping_path(2, vec![fx("distort.transform", json!({"moveH": 60}))]); + clip.appearance = Appearance { effects: clip.appearance.effects.clone(), ..Appearance::basic(placed, Paint::None, 0.0) }.into(); + let mut group = clip_group(1, clip); + group.appearance.effects.push(fx("path.offsetPath", json!({"offset": 0}))); + let evaluated = crate::evaluate_container(None, &group).unwrap(); + let NodeKind::Group { children, clip: true } = &evaluated.kind else { panic!("not a clip group") }; + let Paint::Gradient(g) = children[0].appearance.fill_paint() else { panic!("no gradient") }; + let start = g.geom.unwrap().start; + assert!((start.x - 110.0).abs() < 1e-6, "the gradient starts at the moved path's left edge: {start:?}"); +} + +#[test] +fn a_nested_clip_groups_hidden_clipping_path_keeps_its_effect() { + // A clip group used as a clipping path clips by its clipping path whether it is shown or not. + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + let mut hidden = clipping_path(4, vec![fx("distort.transform", json!({"moveH": -30}))]); + hidden.visible = false; + let outer = clip_group(1, clip_group(3, hidden)); + d.insert(Some(layer), 0, outer.clone()).unwrap(); + let NodeKind::Group { children, .. } = &outer.kind else { panic!("not a group") }; + let b = bounds(&children[0]); + assert!((b.x0 - 20.0).abs() < 1e-6 && (b.x1 - 120.0).abs() < 1e-6, "{b:?}"); + assert_eq!(clip_outline(&children[0]), clip_outline(&baked_clip(&d)), "the canvas clips by the outline the export writes"); +} + +#[test] +fn a_fills_geometry_effect_shapes_the_clip_as_an_export_does() { + // The clipping path's fill has a Transform effect moving it 60 pt right; the path has none. + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + let mut clip = clipping_path(2, vec![]); + clip.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::None, 0.0).into(); + for item in &mut clip.appearance.items { + if let vectorcraft_doc::AppearanceItem::Fill(f) = item { + f.effects.push(fx("distort.transform", json!({"moveH": 60}))); + } + } + let group = clip_group(1, clip); + d.insert(Some(layer), 0, group.clone()).unwrap(); + let NodeKind::Group { children, .. } = &group.kind else { panic!("not a group") }; + let live = clip_outline(&children[0]).unwrap(); + let exported = clip_outline(&baked_clip(&d)).unwrap(); + assert_eq!(live.0.bounding_box(), exported.0.bounding_box(), "the canvas clips by the outline the export writes"); + assert!((live.0.bounding_box().x1 - 210.0).abs() < 1e-6, "the moved fill reaches 210: {:?}", live.0.bounding_box()); + // A path of a compound clipping path with a fill effect of its own stays part of the region. + let mut member = clipping_path(4, vec![]); + member.appearance = children[0].appearance.clone(); + let other = Node::path(NodeId(5), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default()); + let compound = + Node::new(NodeId(3), NodeKind::Compound { children: vec![Arc::new(member), Arc::new(other)], rule: vectorcraft_geom::FillRule::NonZero }); + assert_eq!(bounds(&compound), Rect::new(0.0, 0.0, 150.0, 150.0)); +} + +#[test] +fn a_fills_geometry_effect_shapes_the_clip_before_the_effects_around_it() { + // Offset Path 10 on the fill of an unpainted clipping path, in a group that its Transform + // scales to 50 %: the region is the grown square at half size, 60 pt across, as it is when the + // clipping path is the member of a group that clips by its members. + let clip_with = |fill: Paint| { + let mut clip = clipping_path(3, vec![]); + clip.appearance = Appearance::basic(fill, Paint::None, 0.0).into(); + for item in &mut clip.appearance.items { + if let vectorcraft_doc::AppearanceItem::Fill(f) = item { + f.effects.push(fx("path.offsetPath", json!({"offset": 10}))); + } + } + clip + }; + let scaled = |clip: Node| { + let mut outer = Node::group(NodeId(1), vec![Arc::new(clip_group(2, clip))]); + outer.appearance.effects.push(fx("distort.transform", json!({"scaleH": 50, "scaleV": 50}))); + outer + }; + fn first_clip(n: &Node) -> Option> { + match &n.kind { + NodeKind::Group { children, clip: true } => children.first().cloned(), + _ => n.children()?.iter().find_map(|c| first_clip(c)), + } + } + let clip_of = |n: &Node| clip_outline(&first_clip(n).unwrap()).unwrap().0.bounding_box(); + let close = |r: Rect| (r.width() - 60.0).abs() < 0.5 && (r.height() - 60.0).abs() < 0.5; + let nested = clip_of(&crate::evaluate_container(None, &scaled(Node::group(NodeId(4), vec![Arc::new(clip_with(Paint::None))]))).unwrap()); + assert!(close(nested), "nested: {nested:?}"); + let outer = scaled(clip_with(Paint::None)); + let canvas = clip_of(&crate::evaluate_container(None, &outer).unwrap()); + assert!(close(canvas), "canvas: {canvas:?}"); + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, outer).unwrap(); + let baked = bake_document(&d).unwrap(); + let exported = baked.layers.iter().find_map(|l| first_clip(l)).map(|c| clip_outline(&c).unwrap().0.bounding_box()).unwrap(); + assert!(close(exported), "exported: {exported:?}"); + // A clipping path that paints its fill clips alike and paints the fill it clips by. + let painted = first_clip(&crate::evaluate_container(None, &scaled(clip_with(Paint::solid(Color::BLACK)))).unwrap()).unwrap(); + assert!(close(clip_outline(&painted).unwrap().0.bounding_box()), "painted: {painted:?}"); + let fill = painted.clip_paint().fill.unwrap(); + assert!(close(fill.geometric_bounds().unwrap()), "painted fill: {fill:?}"); +} + +#[test] +fn a_painted_clipping_paths_fill_and_stroke_effects_apply_before_the_effects_around_it() { + // A clipping path with a black fill grown by Offset Path 10 and a 2 pt blue stroke moved 30 pt + // right by a Transform, in a group that its Transform scales to 50 %: the fill paints the grown + // square at half size, 60 pt across, and the stroke the square at half size, 15 pt right of + // it, on the canvas and in an export alike. + let mut clip = clipping_path(3, vec![]); + clip.appearance = Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 2.0).into(); + for item in &mut clip.appearance.items { + match item { + vectorcraft_doc::AppearanceItem::Fill(f) => f.effects.push(fx("path.offsetPath", json!({"offset": 10}))), + vectorcraft_doc::AppearanceItem::Stroke(s) => s.effects.push(fx("distort.transform", json!({"moveH": 30}))), + } + } + let mut outer = Node::group(NodeId(1), vec![Arc::new(clip_group(2, clip.clone()))]); + outer.appearance.effects.push(fx("distort.transform", json!({"scaleH": 50, "scaleV": 50}))); + fn first_clip(n: &Node) -> Option> { + match &n.kind { + NodeKind::Group { children, clip: true } => children.first().cloned(), + _ => n.children()?.iter().find_map(|c| first_clip(c)), + } + } + let check = |what: &str, c: &Node| { + let paint = c.clip_paint(); + let fill = paint.fill.as_ref().and_then(Node::geometric_bounds).unwrap(); + assert!((fill.width() - 60.0).abs() < 0.5 && (fill.height() - 60.0).abs() < 0.5, "{what} fill: {fill:?}"); + let stroke = paint.stroke.as_ref().and_then(Node::geometric_bounds).unwrap(); + assert!((stroke.width() - 50.0).abs() < 0.5 && (stroke.x0 - fill.x0 - 20.0).abs() < 0.5, "{what} stroke: {stroke:?} fill: {fill:?}"); + }; + let evaluated = crate::evaluate_container(None, &outer).unwrap(); + let canvas = first_clip(&evaluated).unwrap(); + check("canvas", &canvas); + // The clip group's box takes in the stroke's width, as for a path that paints its stroke. + let stroke = canvas.clip_paint().stroke.as_ref().and_then(Node::geometric_bounds).unwrap(); + let visual = evaluated.children().and_then(|ch| ch.first()).and_then(|g| g.visual_bounds()).unwrap(); + assert!(visual.x1 > stroke.x1 + 0.25, "{visual:?} {stroke:?}"); + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, outer).unwrap(); + check("exported", &baked_clip(&d)); + // Without effects around it, the export paints the fill and the stroke as the canvas does. + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, clip_group(2, clip.clone())).unwrap(); + let paint = baked_clip(&d).clip_paint(); + let fill = paint.fill.as_ref().and_then(Node::geometric_bounds); + let stroke = paint.stroke.as_ref().and_then(Node::geometric_bounds); + assert_eq!(fill.map(|f| f.width()), Some(120.0), "{paint:?}"); + assert_eq!(stroke.map(|s| s.x0), Some(80.0), "{paint:?}"); + // A piece that an effect around it splits into several paths (a compound path), or puts in a + // group with its copies, still paints. + let NodeKind::Group { children, .. } = &canvas.kind else { panic!("not the pieces: {canvas:?}") }; + let mut split = canvas.as_ref().clone(); + let mut compound = children[0].as_ref().clone(); + compound.kind = NodeKind::Compound { children: vec![children[0].clone(), children[0].clone()], rule: vectorcraft_geom::FillRule::NonZero }; + let copies = Node::group(NodeId(9), vec![children[1].clone(), children[1].clone()]); + if let Some(ch) = split.children_mut() { + ch[0] = Arc::new(compound); + ch[1] = Arc::new(copies); + } + let paint = split.clip_paint(); + assert!(paint.fill.is_some() && paint.stroke.is_some(), "{split:?}"); + let stroke = paint.stroke.unwrap(); + assert_eq!(stroke.children().map(|ch| ch.len()), Some(1), "only the stroke's group: {stroke:?}"); +} + +#[test] +fn a_painted_clipping_paths_stroke_keeps_the_width_its_transform_scales_it_to() { + // A compound clipping path with a 2 pt stroke whose Transform scales strokes to 200 % without + // transforming the object: the export paints the stroke at 4 pt. + let square = Node::path(NodeId(4), shapes::rectangle(Rect::new(50.0, 50.0, 150.0, 150.0)), Appearance::default()); + let mut clip = Node::new(NodeId(3), NodeKind::Compound { children: vec![Arc::new(square)], rule: vectorcraft_geom::FillRule::NonZero }); + clip.appearance = Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 2.0).into(); + let scale = json!({"scaleH": 200, "scaleV": 200, "objects": false, "strokes": true}); + for item in &mut clip.appearance.items { + if let vectorcraft_doc::AppearanceItem::Stroke(s) = item { + s.effects.push(fx("distort.transform", scale.clone())); + } + } + fn widths(n: &Node, out: &mut Vec) { + for item in &n.appearance.items { + if let vectorcraft_doc::AppearanceItem::Stroke(s) = item { + out.push(s.width); + } + } + n.children().into_iter().flatten().for_each(|c| widths(c, out)); + } + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, clip_group(2, clip)).unwrap(); + let baked = baked_clip(&d); + let stroke = baked.clip_paint().stroke.unwrap(); + let mut found = vec![]; + widths(&stroke, &mut found); + assert!(!found.is_empty() && found.iter().all(|w| (w - 4.0).abs() < 1e-6), "{found:?} {stroke:?}"); + // The stroke is still drawn where the path lies, as the Transform does not move the object. + let bounds = stroke.geometric_bounds().unwrap(); + assert!((bounds.x0 - 50.0).abs() < 0.5 && (bounds.width() - 100.0).abs() < 0.5, "{bounds:?}"); +} + +#[test] +fn a_baked_clipping_path_gives_its_pieces_ids_of_their_own() { + // An unpainted clipping path whose fill and stroke have Transform effects, in a clip group + // without effects: the export bakes it into a piece for each, every object with its own id. + let mut d = Document::new(400.0, 400.0); + let (group, path) = (d.alloc_id(), d.alloc_id()); + let mut clip = clipping_path(path.0, vec![]); + clip.appearance = Appearance::basic(Paint::None, Paint::None, 1.0).into(); + for item in &mut clip.appearance.items { + match item { + vectorcraft_doc::AppearanceItem::Fill(f) => f.effects.push(fx("distort.transform", json!({"moveH": 60}))), + vectorcraft_doc::AppearanceItem::Stroke(s) => s.effects.push(fx("distort.transform", json!({"moveV": 60}))), + } + } + let layer = d.layers[0].id; + d.insert(Some(layer), 0, clip_group(group.0, clip)).unwrap(); + let baked = bake_document(&d).unwrap(); + let clip = baked_clip(&d); + assert_eq!(clip.children().map(|c| c.len()), Some(2), "{clip:?}"); + fn ids(n: &Node, out: &mut Vec) { + out.push(n.id); + for c in n.children().into_iter().flatten() { + ids(c, out); + } + } + let mut all = vec![]; + for l in &baked.layers { + ids(l, &mut all); + } + let unique: std::collections::HashSet<_> = all.iter().collect(); + assert_eq!(unique.len(), all.len(), "{all:?}"); +} + +#[test] +fn a_hidden_member_with_an_effect_adds_nothing() { + let shown = Node::path(NodeId(3), shapes::rectangle(Rect::new(50.0, 50.0, 100.0, 100.0)), Appearance::default()); + let mut hidden = clipping_path(4, vec![fx("distort.transform", json!({"moveH": 200}))]); + hidden.visible = false; + let group = Node::group(NodeId(2), vec![Arc::new(shown), Arc::new(hidden)]); + assert_eq!(bounds(&group), Rect::new(50.0, 50.0, 100.0, 100.0)); +} + +#[test] +fn raster_and_hidden_effects_leave_the_clip_as_it_is() { + let mut hidden = fx("distort.transform", json!({"moveH": 60})); + hidden.visible = false; + for effects in [vec![], vec![fx("blur.gaussian", json!({"radius": 10}))], vec![hidden]] { + assert_eq!(bounds(&clipping_path(1, effects)), Rect::new(50.0, 50.0, 150.0, 150.0)); + } +} 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 a610ae7c71..db34010c22 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 } @@ -117,13 +118,125 @@ fn a_hidden_shadow_follows_the_transform_it_loses() { assert!(close(drawn_shadow(&[shown]), (20.0, 20.0, 8.0))); } -/// Rasterize keeps its room around the art: its image keeps its own pixel grid. +/// Rasterize keeps its room around the art: its image keeps its own pixel grid, and the Transform +/// effect moves the image instead ([`crate::rasterize_stage`]). #[test] fn rasterize_before_a_transform_keeps_its_options() { let rasterize = fx(crate::RASTERIZE, json!({"addAround": 6})); let effects = [rasterize.clone(), transform(json!({"scaleH": 200, "scaleV": 200}))]; assert_eq!(crate::raster::followed(&effects)[0], rasterize); assert_eq!(crate::raster::without_geometry(&effects), vec![rasterize]); + assert_eq!(crate::rasterize_stage(&effects), Some(vec![1])); +} + +/// The Transform effects after the last Rasterize effect move or copy its image when, from the +/// first of them on, every visible effect is a Transform effect that does not move at random and at +/// most one of them makes copies. Hidden ones, and ones with Transform Objects off, leave the image +/// where it is. +#[test] +fn rasterize_following_ignores_hidden_and_objects_off() { + let rasterize = || fx(crate::RASTERIZE, json!({})); + let scale = || transform(json!({"scaleH": 200, "scaleV": 200})); + let mut hidden = scale(); + hidden.visible = false; + let off = transform(json!({"scaleH": 200, "objects": false})); + let roughen = fx("distort.roughen", json!({})); + let shadow = shadow(5.0, 5.0, 2.0); + let cases: Vec<(Vec, Option>)> = vec![ + (vec![rasterize(), hidden.clone()], None), + (vec![rasterize(), off.clone()], None), + (vec![rasterize(), hidden, off, scale()], Some(vec![3])), + (vec![rasterize(), transform(json!({"moveH": 10})), scale()], Some(vec![1, 2])), + // Effects before the first Transform effect go into the image; anything after it holds + // the image back. + (vec![rasterize(), roughen.clone(), shadow.clone(), scale()], Some(vec![3])), + (vec![rasterize(), scale(), roughen], None), + (vec![rasterize(), scale(), shadow.clone()], None), + // Each copy carries the image, even of a Transform effect that only copies in place. + (vec![rasterize(), transform(json!({"scaleH": 200, "copies": 2}))], Some(vec![1])), + (vec![rasterize(), transform(json!({"copies": 2}))], Some(vec![1])), + (vec![rasterize(), transform(json!({"moveH": 10, "copies": 2})), scale()], Some(vec![1, 2])), + (vec![rasterize(), transform(json!({"moveH": 10, "copies": 2, "objects": false}))], None), + (vec![rasterize(), transform(json!({"moveH": 10, "copies": 2})), transform(json!({"moveV": 10, "copies": 3}))], None), + (vec![rasterize(), transform(json!({"moveH": 10, "copies": 2})), shadow], None), + (vec![rasterize(), transform(json!({"scaleH": 200, "random": true}))], None), + (vec![rasterize(), transform(json!({"scaleH": 200, "copies": 2, "random": true}))], None), + // The Transform effect before the Rasterize effect moves the art. + (vec![scale(), rasterize()], None), + (vec![scale(), rasterize(), rasterize(), scale()], Some(vec![3])), + ]; + for (effects, want) in cases { + let ids: Vec<&str> = effects.iter().map(|e| e.id.as_str()).collect(); + assert_eq!(crate::rasterize_stage(&effects), want, "{ids:?}"); + } + // What the image is made from hides those Transform effects; the rest stay as they are. + let effects = [rasterize(), scale()]; + let staged = crate::staged_effects(&effects, &[1]); + assert_eq!((staged[0].visible, staged[1].visible), (true, false)); +} + +/// The map that moves the image is each Transform effect's map about its reference point on the +/// bounds of the geometry it takes, in order. +#[test] +fn the_image_moves_by_each_transform_about_the_art_it_takes() { + let staged = shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)); + let effects = [fx(crate::RASTERIZE, json!({})), transform(json!({"scaleH": 200, "scaleV": 200})), transform(json!({"moveH": 5}))]; + let maps = crate::stage_maps(&effects, &[1, 2], &staged).unwrap(); + assert_eq!(maps.len(), 1); + // Twice the size about the center (20, 20), then 5 pt to the right. + let want = Affine::translate((5.0, 0.0)) * Affine::translate((20.0, 20.0)) * Affine::scale(2.0) * Affine::translate((-20.0, -20.0)); + assert!(same_map(maps[0], want), "{maps:?}"); + // The second Transform effect turns about the center of what the first one made. + let effects = [fx(crate::RASTERIZE, json!({})), transform(json!({"moveH": 100})), transform(json!({"rotate": 90}))]; + let maps = crate::stage_maps(&effects, &[1, 2], &staged).unwrap(); + let c = maps[0] * Point::new(20.0, 20.0); + assert!((c.x - 120.0).abs() < 1e-9 && (c.y - 20.0).abs() < 1e-9, "{c:?}"); + assert_eq!(crate::stage_maps(&effects, &[1, 2], &PathData::default()), None); +} + +/// Is `a` `b`, each coefficient within 1e-9? +fn same_map(a: Affine, b: Affine) -> bool { + a.as_coeffs().iter().zip(b.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-9) +} + +/// Are `maps` `want`, in order? +fn same_maps(maps: &[Affine], want: &[Affine]) -> bool { + maps.len() == want.len() && maps.iter().zip(want).all(|(m, w)| same_map(*m, *w)) +} + +/// A Transform effect with copies places the image once for the original and once for each copy, +/// copy `k` through its map `k` times about the art before it, the last copy lowest and the +/// original on top. A Transform effect after it moves every placement, about the bounds of all the +/// copies. +#[test] +fn each_copy_carries_the_image() { + let staged = shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)); + let rasterize = fx(crate::RASTERIZE, json!({})); + let effects = [rasterize.clone(), transform(json!({"moveH": 100, "copies": 2}))]; + let maps = crate::stage_maps(&effects, &[1], &staged).unwrap(); + let want = [Affine::translate((200.0, 0.0)), Affine::translate((100.0, 0.0)), Affine::IDENTITY]; + assert!(same_maps(&maps, &want), "{maps:?}"); + // Turned 90° about the center (20, 20) each time: copy 2 turns 180°. + let effects = [rasterize.clone(), transform(json!({"rotate": 90, "copies": 2}))]; + let maps = crate::stage_maps(&effects, &[1], &staged).unwrap(); + let turn = |deg: f64| Affine::translate((20.0, 20.0)) * Affine::rotate(-deg.to_radians()) * Affine::translate((-20.0, -20.0)); + let want = [turn(180.0), turn(90.0), Affine::IDENTITY]; + assert!(same_maps(&maps, &want), "{maps:?}"); + // A scale after the copies doubles every placement about the center of all three, (120, 20). + let effects = [rasterize.clone(), transform(json!({"moveH": 100, "copies": 2})), transform(json!({"scaleH": 200, "scaleV": 200}))]; + let maps = crate::stage_maps(&effects, &[1, 2], &staged).unwrap(); + let scale = Affine::translate((120.0, 20.0)) * Affine::scale(2.0) * Affine::translate((-120.0, -20.0)); + let want = [scale * Affine::translate((200.0, 0.0)), scale * Affine::translate((100.0, 0.0)), scale]; + assert!(same_maps(&maps, &want), "{maps:?}"); + // A move before the copies moves the art they copy. + let effects = [rasterize.clone(), transform(json!({"moveV": 5})), transform(json!({"moveH": 100, "copies": 1}))]; + let maps = crate::stage_maps(&effects, &[1, 2], &staged).unwrap(); + let want = [Affine::translate((100.0, 5.0)), Affine::translate((0.0, 5.0))]; + assert!(same_maps(&maps, &want), "{maps:?}"); + // Copies stop where the geometry pass stops them: none past its reach of 1e9 pt. + let effects = [rasterize, transform(json!({"moveH": 1.0e7, "copies": 1000}))]; + let maps = crate::stage_maps(&effects, &[1], &staged).unwrap(); + assert_eq!(maps.len(), 100, "{}", maps.len()); } /// An SVG filter keeps its options: it paints in its own user space. @@ -378,6 +491,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] @@ -498,7 +835,7 @@ fn a_groups_transform_moves_its_members_shadows() { } /// A group's Transform effect that makes copies or moves at random leaves its members' shadows as -/// they are, as it leaves the shadows listed before it in its own effects. +/// they are. #[test] fn a_groups_copying_transform_leaves_its_members_shadows() { for params in [json!({"scaleH": 200, "scaleV": 200, "copies": 1}), json!({"scaleH": 200, "scaleV": 200, "random": true})] { @@ -509,6 +846,204 @@ fn a_groups_copying_transform_leaves_its_members_shadows() { } } +/// A layer of `members` with `effects` of its own. +fn layer(id: u64, members: Vec, effects: Vec) -> Node { + let mut l = Node::layer(NodeId(id), "Layer", vectorcraft_doc::LayerColor::Preset(0)); + if let Some(ch) = l.children_mut() { + *ch = members.into_iter().map(std::sync::Arc::new).collect(); + } + l.appearance.effects = effects; + l +} + +/// The offset and blur of the Drop Shadow that each member of `art` draws of its own, in order. +fn copy_shadows(art: &Node) -> Vec<(f64, f64, f64)> { + art.children().into_iter().flatten().map(|c| drawn_shadow(&c.appearance.effects)).collect() +} + +fn close_all(a: &[(f64, f64, f64)], b: &[(f64, f64, f64)]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| close(*x, *y)) +} + +/// A group's or layer's Transform effect that makes copies gives each copy the shadow listed +/// before it, moved, turned, reflected and scaled with that copy, the last copy lowest: drawn and +/// baked. Each copy is a group holding all the members, which carry no shadow of their own, and +/// the art paints none around all the copies. With Scale Strokes & Effects on, the shadow is not +/// scaled a second time. A layer's art stays a layer. +#[test] +fn each_copy_of_a_groups_or_layers_transform_effect_carries_the_shadow_listed_before_it() { + let cases = [ + (json!({"moveH": 100, "copies": 2}), vec![(10.0, 0.0, 4.0); 3]), + // A turn of 90° counterclockwise on screen takes an offset to the right to one upward. + (json!({"rotate": 90, "copies": 2}), vec![(-10.0, 0.0, 4.0), (0.0, -10.0, 4.0), (10.0, 0.0, 4.0)]), + (json!({"reflectX": true, "moveH": 100, "copies": 1}), vec![(-10.0, 0.0, 4.0), (10.0, 0.0, 4.0)]), + (json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1}), vec![(20.0, 0.0, 8.0), (10.0, 0.0, 4.0)]), + (json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1, "strokes": true}), vec![(20.0, 0.0, 8.0), (10.0, 0.0, 4.0)]), + ]; + for (params, want) in cases { + let offsets: Vec<(f64, f64)> = want.iter().map(|w| (w.0, w.1)).collect(); + for container in ["group", "layer"] { + let members = vec![square(101, vec![]), square(102, vec![])]; + let effects = vec![shadow(10.0, 0.0, 4.0), transform(params.clone())]; + let n = if container == "group" { group(100, members, effects) } else { layer(100, members, effects) }; + assert!(crate::outer_effects(&n).iter().all(|e| e.id != "stylize.dropShadow"), "{params}: {container}"); + let art = crate::evaluate_container(None, &n).unwrap(); + assert_eq!(matches!(art.kind, vectorcraft_doc::NodeKind::Layer { .. }), container == "layer", "{params}: {container}"); + assert!(raster_effects(&art.appearance.effects).is_empty(), "{params}: {container} {:?}", art.appearance.effects); + let drawn = copy_shadows(&art); + assert!(close_all(&drawn, &want), "{params}: {container} {drawn:?}"); + assert_eq!(shadows_in(&art).len(), want.len(), "{params}: {container}: the members draw none"); + for c in art.children().into_iter().flatten() { + assert!(matches!(c.kind, vectorcraft_doc::NodeKind::Group { .. }) && paths_in(c) == 2, "{params}: {container} {c:?}"); + } + let b = baked(n); + assert!(near(&shadows_in(&b), &offsets), "{params}: {container} baked {:?}", shadows_in(&b)); + } + } +} + +/// A group's copying Transform effect leaves its members' own shadows on each copy as they are, +/// and a shadow listed after it paints once around all the copies. A clip group's copies each clip +/// and carry the shadow, and the art clips nothing. A Transform effect that makes no copies, or has +/// Transform Objects off, leaves the group's shadows on the group. +#[test] +fn a_groups_copying_transform_leaves_member_and_later_shadows_where_they_paint() { + let g = group( + 110, + vec![square(111, vec![shadow(5.0, 5.0, 0.0)]), square(112, vec![])], + vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1})), shadow(0.0, 5.0, 0.0)], + ); + assert_eq!(crate::outer_effects(&g).len(), 2); + let art = crate::evaluate_container(None, &g).unwrap(); + assert!(near(&shadows_in(&art), &[(0.0, 5.0), (0.0, -10.0), (5.0, 5.0), (10.0, 0.0), (5.0, 5.0)]), "{:?}", shadows_in(&art)); + + let mut clip = square(121, vec![]); + if let vectorcraft_doc::NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + let mut g = group(120, vec![clip, square(122, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))]); + if let vectorcraft_doc::NodeKind::Group { clip, .. } = &mut g.kind { + *clip = true; + } + let art = crate::evaluate_container(None, &g).unwrap(); + assert!(!art.clips()); + assert!(art.children().into_iter().flatten().all(|c| c.clips()), "{art:?}"); + assert!(close_all(©_shadows(&art), &[(10.0, 0.0, 0.0), (10.0, 0.0, 0.0)]), "{:?}", copy_shadows(&art)); + + for params in [json!({"rotate": 90}), json!({"rotate": 90, "copies": 1, "objects": false})] { + let g = group(130, vec![square(131, vec![]), square(132, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(params.clone())]); + assert_eq!(crate::outer_effects(&g).len(), 2, "{params}"); + let art = crate::evaluate_container(None, &g).unwrap(); + assert_eq!(raster_effects(&art.appearance.effects).len(), 1, "{params}: the group keeps its shadow"); + } +} + +/// Copies of a group that stop at the effect budget each keep their shadow: no copy goes without +/// one, and no shadow is left without its copy. +#[test] +fn a_groups_copies_past_the_budget_each_keep_their_shadow() { + let g = group(140, vec![path_node(141, wavy(30_000), vec![])], vec![shadow(1.0, 0.5, 0.0), transform(json!({"moveV": 50, "copies": 1000}))]); + let art = crate::evaluate_container(None, &g).unwrap(); + let paths = paths_in(&art); + assert!(paths > 1 && paths < 1001, "{paths}"); + assert_eq!(shadows_in(&art).len(), paths); +} + +/// A layer's ruler guides stay once above the copies of its Transform effect, and carry no shadow. +#[test] +fn a_layers_guides_stay_once_above_copies_that_carry_its_shadow() { + let guide = Node::new(NodeId(152), vectorcraft_doc::NodeKind::RulerGuide { vertical: true, pos: 3.0, artboard: None }); + let l = layer(150, vec![square(151, vec![]), guide], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 2}))]); + let art = crate::evaluate_container(None, &l).unwrap(); + let ch = art.children().unwrap(); + assert_eq!(ch.len(), 4, "three copies, then the guide"); + assert!(ch[3].is_ruler_guide() && ch.iter().filter(|c| c.is_ruler_guide()).count() == 1); + assert_eq!(shadows_in(&art).len(), 3); +} + +/// The bounds of every node with `id` under `art`, in order. +fn bounds_of(art: &Node, id: u64) -> Vec { + let mut out = vec![]; + art.walk(&mut |m| { + if m.id == NodeId(id) + && let Some(b) = m.geometric_bounds() + { + out.push(b); + } + }); + out +} + +fn rects_near(a: &[Rect], b: &[Rect]) -> bool { + let near = |p: f64, q: f64| (p - q).abs() < 1e-6; + a.len() == b.len() && a.iter().zip(b).all(|(p, q)| near(p.x0, q.x0) && near(p.y0, q.y0) && near(p.x1, q.x1) && near(p.y1, q.y1)) +} + +/// A group with a fill of its own and only a shadow before its copying Transform effect applies +/// its members' own effects before it copies them, as a group without a fill does: a member's own +/// move is turned with each copy. +#[test] +fn a_painted_groups_copies_take_their_members_own_effects_first() { + let members = || vec![square(171, vec![transform(json!({"moveH": 40}))]), square(172, vec![])]; + let effects = || vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1}))]; + let plain = crate::evaluate_container(None, &group(170, members(), effects())).unwrap(); + let mut painted = group(170, members(), effects()); + *painted.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0); + painted.appearance.effects = effects(); + let art = crate::evaluate_container(None, &painted).unwrap(); + let (want, got) = (bounds_of(&plain, 171), bounds_of(&art, 171)); + assert!(!want.is_empty()); + assert!(rects_near(&got, &want), "{got:?} {want:?}"); +} + +/// A layer's copies are made about the bounds of its visible members, as the layer measures them: +/// a hidden member does not move the center that a reflected copy turns about. +#[test] +fn a_layers_copies_leave_its_hidden_members_out_of_their_reference() { + let mut hidden = path_node(182, shapes::rectangle(Rect::new(1000.0, 0.0, 1050.0, 50.0)), vec![]); + hidden.visible = false; + let l = layer(180, vec![square(181, vec![]), hidden], vec![shadow(10.0, 0.0, 0.0), transform(json!({"reflectX": true, "copies": 1}))]); + let art = crate::evaluate_container(None, &l).unwrap(); + let got = bounds_of(&art, 181); + assert!(rects_near(&got, &[Rect::new(0.0, 0.0, 50.0, 50.0); 2]), "{got:?}"); +} + +/// A shadow carried by the copies of an earlier copying Transform effect of a group turns with each +/// copy of a later one, drawn and baked. +#[test] +fn a_groups_later_copying_transform_turns_the_shadows_of_earlier_copies() { + let g = || { + group( + 190, + vec![square(191, vec![])], + vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1})), transform(json!({"rotate": 90, "copies": 1}))], + ) + }; + let want = [(0.0, -10.0), (0.0, -10.0), (10.0, 0.0), (10.0, 0.0)]; + let art = crate::evaluate_container(None, &g()).unwrap(); + assert!(near(&shadows_in(&art), &want), "{:?}", shadows_in(&art)); + let b = baked(g()); + assert!(near(&shadows_in(&b), &want), "baked {:?}", shadows_in(&b)); +} + +/// A group holding type whose Transform effect only moves its copies, baked for export, gives each +/// copy the shadow listed before that effect, as the canvas draws it, rather than keeping the type +/// as type under one shadow around all the copies. Built without fonts, type lays out no glyphs +/// and the test is skipped. +#[test] +fn a_baked_group_with_type_keeps_a_shadow_on_each_copy() { + use vectorcraft_doc::text::{CharStyle, TextObject}; + let style = CharStyle { size: 40.0, fill: Paint::solid(Color::BLACK), ..Default::default() }; + let words = Node::new(NodeId(161), vectorcraft_doc::NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style)))); + if !crate::outline_text(&words).is_some_and(|o| paths_in(&o) > 0) { + eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); + return; + } + let g = group(160, vec![words, square(162, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 150, "copies": 1}))]); + let b = baked(g); + assert!(near(&shadows_in(&b), &[(10.0, 0.0), (10.0, 0.0)]), "{:?}", shadows_in(&b)); +} + /// The Transform effects inside a group apply before the group's: a member's own turn of 90° /// applies to its shadow before the group's uneven scale does, for the member's own shadow, its /// fill's shadow, and the shadow of a member of a nested group that has the turn. @@ -533,8 +1068,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 = [ @@ -542,7 +1077,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)]); @@ -584,8 +1118,9 @@ fn image(id: u64, effects: Vec) -> Node { /// A group's Transform effect transforms, with Scale Strokes & Effects off or on, the raster /// effects that a member's own Transform effect with copies holds back: they keep their value /// through the member's effect and transform with the group's. That holds for a shadow listed -/// before the member's copying effect, one listed after it, a fill's shadow under it, the shadow -/// of a member of a nested group with such an effect, and an image's shadow. +/// before the member's copying effect (which each copy carries), one listed after it, a fill's +/// shadow under it, the shadow of a member of a nested group with such an effect, and an image's +/// shadow. #[test] fn a_groups_transform_moves_the_shadows_its_members_copies_hold_back() { let copies = || transform(json!({"moveH": 60, "copies": 1})); @@ -605,7 +1140,8 @@ fn a_groups_transform_moves_the_shadows_its_members_copies_hold_back() { let art = crate::evaluate_container(None, &g).unwrap(); for id in [71, 72, 73, 75, 76] { let drawn = shadows_in(&node_in(&art, id)); - assert!(near(&drawn, &[want]), "Scale Strokes & Effects {strokes}: {id} {drawn:?}"); + let wanted = if id == 71 { vec![want, want] } else { vec![want] }; + assert!(near(&drawn, &wanted), "Scale Strokes & Effects {strokes}: {id} {drawn:?}"); } } } @@ -841,3 +1377,390 @@ fn copying_and_object_disabled_transforms_keep_their_existing_shadow_rules() { assert!(close(drawn_shadow(&effects), (10.0, 5.0, 4.0)), "{t:?}: {:?}", drawn_shadow(&effects)); } } + +/// The blur of every Drop Shadow drawn on `n` and the nodes under it, in the order of +/// [`shadows_in`]. +fn shadow_blurs_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 { + for r in raster_effects(list) { + if let RasterFx::DropShadow { blur, .. } = r { + out.push(blur); + } + } + } + }); + out +} + +/// How many paths `n` holds. +fn paths_in(n: &Node) -> usize { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, vectorcraft_doc::NodeKind::Path { .. }))); + count +} + +/// A Transform effect that makes copies gives each copy the shadow listed before it, moved, turned, +/// reflected and scaled with that copy, the last copy lowest: drawn, expanded and baked. The object +/// itself keeps the shadow as it is, and paints none around all of them. With Scale Strokes & +/// Effects on, the shadow is not scaled a second time. +#[test] +fn each_copy_of_a_transform_effect_carries_the_shadow_listed_before_it() { + let cases = [ + (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]), + (json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1, "strokes": true}), vec![(20.0, 0.0), (10.0, 0.0)], vec![8.0, 4.0]), + (json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1, "random": true}), vec![(10.0, 0.0), (10.0, 0.0)], vec![4.0, 4.0]), + ]; + for (params, want, blurs) in cases { + let n = square(91, vec![shadow(10.0, 0.0, 4.0), transform(params.clone())]); + assert!(crate::has_transform_art(&n), "{params}"); + assert!(crate::outer_effects(&n).iter().all(|e| e.id != "stylize.dropShadow"), "{params}"); + let random = params["random"].as_bool().unwrap_or(false); + 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_eq!(paths_in(&art), want.len(), "{params}: {how} {art:?}"); + if random { + // Random scales the copy by a share of the 200 %, and its shadow with it; the object + // keeps its own. + assert_eq!(drawn.len(), want.len(), "{params}: {how} {drawn:?}"); + assert!(near(&drawn[1..], &want[1..]), "{params}: {how} {drawn:?}"); + continue; + } + assert!(near(&drawn, &want), "{params}: {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), "{params}: {how} blurs {b:?}"); + } + } +} + +/// A shadow listed after a 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, leaves the object's shadows on the object. +#[test] +fn a_shadow_after_a_copying_transform_paints_once_around_the_copies() { + let n = square(92, vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1})), shadow(0.0, 5.0, 0.0)]); + let art = crate::reshape(None, &n, None).unwrap(); + assert!(near(&shadows_in(&art), &[(0.0, 5.0), (0.0, -10.0), (10.0, 0.0)]), "{:?}", shadows_in(&art)); + assert_eq!(crate::outer_effects(&n).len(), 2); + for params in [json!({"rotate": 90}), json!({"rotate": 90, "copies": 1, "objects": false})] { + let n = square(93, vec![shadow(10.0, 0.0, 0.0), transform(params.clone())]); + assert!(!crate::has_transform_art(&n), "{params}"); + assert_eq!(crate::outer_effects(&n).len(), 2, "{params}"); + } +} + +/// Copies that stop at the effect budget each keep their shadow: no copy goes without one, and no +/// shadow is left without its copy. +#[test] +fn copies_past_the_budget_each_keep_their_shadow() { + let n = path_node(94, wavy(30_000), vec![shadow(1.0, 0.5, 0.0), transform(json!({"moveV": 50, "copies": 1000}))]); + 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); +} + +/// `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/examples/cut_path_select_bench.rs b/crates/engine/examples/cut_path_select_bench.rs new file mode 100644 index 0000000000..1deed62e6f --- /dev/null +++ b/crates/engine/examples/cut_path_select_bench.rs @@ -0,0 +1,167 @@ +//! `cargo run --release -p vectorcraft-engine --example cut_path_select_bench` prints the time +//! Cut Path at Selected Anchor Points takes to select the cut ends, on synthetic documents of 500, +//! 2,000 and 5,000 open paths of 10 anchors each with the 8 anchors between the ends of each +//! direct-selected, and on one path of 2,000 open subpaths selected the same way. For each it times two ways of building the same +//! selection from the cut ends: clearing the selection and adding each path in turn (each add looks +//! through the paths already added), and one `Selection::set` call followed by the anchors. It +//! checks that both give the same selection, every field, before it times them, and then times the +//! whole command once per run on the 2,000-path document. +//! `ITERS` sets the runs per row (default 7); the two ways run in alternating order, each run +//! builds the selection 20 times, and each row is the median time of one build. On Linux the times are the CPU time of the main thread, which runs everything, in +//! ms; elsewhere they are wall times. +// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::hint::black_box; +use std::time::Instant; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, Selection}; +use vectorcraft_engine::Session; +use vectorcraft_geom::{Anchor, PathData, Point, SubPath}; + +/// The anchors of each path, or of each subpath of the one compound path. +const ANCHORS: usize = 10; + +/// The builds of the selection in each timed run; a row gives the time of one build. +const REPS: usize = 20; + +/// What the command selects for one cut end: the path and its anchor (subpath, anchor). +type Pick = (NodeId, (usize, usize)); + +/// A way of building the selection from the cut ends. +type Rebuild = fn(&mut Selection, &[Pick]); + +fn iters() -> usize { + std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1) +} + +fn median(mut ms: Vec) -> f64 { + ms.sort_by(f64::total_cmp); + ms[ms.len() / 2] +} + +/// The CPU time of the calling thread in ns, from `/proc/thread-self/schedstat` (Linux only). +fn thread_cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// The time `f` takes, in ms: CPU time where the system reports it, wall time otherwise. +fn measure(f: impl FnOnce()) -> f64 { + match thread_cpu_ns() { + Some(start) => { + f(); + thread_cpu_ns().map_or(f64::NAN, |end| end.saturating_sub(start) as f64 / 1e6) + } + None => { + let t = Instant::now(); + f(); + t.elapsed().as_secs_f64() * 1000.0 + } + } +} + +/// The selection built by clearing it and adding each path in turn. +fn one_by_one(sel: &mut Selection, picked: &[Pick]) { + sel.clear(); + for (id, a) in picked { + sel.add(*id); + sel.anchors.entry(*id).or_default().insert(*a); + } +} + +/// The selection built with one `Selection::set` call, as the command builds it. +fn one_call(sel: &mut Selection, picked: &[Pick]) { + sel.set(picked.iter().map(|(id, _)| *id)); + for (id, a) in picked { + sel.anchors.entry(*id).or_default().insert(*a); + } +} + +fn exec(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +/// An open subpath of [`ANCHORS`] corner anchors 10 pt apart along row `row`. +fn row(row: usize) -> SubPath { + let y = row as f64 * 20.0; + SubPath::new((0..ANCHORS).map(|i| Anchor::corner(Point::new(i as f64 * 10.0, y))).collect(), false) +} + +/// A session with the paths in `paths` and every anchor of theirs but the two ends of each +/// subpath direct-selected (a path with all its anchors selected counts as selected whole). +fn fixture(paths: Vec) -> Session { + let mut doc = Document::new(1600.0, 1200.0); + let l = doc.layers.first().map(|l| l.id); + let mut items = vec![]; + for pd in paths { + let id = doc.alloc_id(); + let refs: Vec<[usize; 2]> = + pd.subpaths.iter().enumerate().flat_map(|(si, sp)| (1..sp.anchors.len().saturating_sub(1)).map(move |ai| [si, ai])).collect(); + doc.insert(l, usize::MAX, Node::path(id, pd, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))).unwrap(); + items.push(json!({"id": id.0, "anchors": refs})); + } + let mut s = Session::new(); + s.add_document(doc, None); + exec(&mut s, "select.anchorsMany", json!({"items": items})); + s +} + +/// The cut ends the command selects, in the order it selects them: read back from the selection it +/// leaves, which holds each cut path once in that order. +fn picked_after_cut(s: &Session) -> Vec { + let sel = &s.doc().unwrap().selection; + sel.objects.iter().flat_map(|id| sel.anchors[id].iter().map(move |a| (*id, *a))).collect() +} + +fn bench(name: &str, paths: impl Fn() -> Vec) { + let mut s = fixture(paths()); + exec(&mut s, "path.cutAtAnchors", json!({})); + let picked = picked_after_cut(&s); + let mut start = Selection::default(); + one_by_one(&mut start, &[(NodeId(u64::MAX), (0, 3))]); + let (mut a, mut b) = (start.clone(), start.clone()); + one_by_one(&mut a, &picked); + one_call(&mut b, &picked); + assert_eq!(a, b, "both ways give the same selection"); + assert_eq!(b, s.doc().unwrap().selection, "the command gives that selection"); + let (mut old, mut new) = (vec![], vec![]); + for i in 0..iters() { + let run = |f: Rebuild, out: &mut Vec| { + let ms = measure(|| { + for _ in 0..REPS { + let mut sel = start.clone(); + f(&mut sel, black_box(&picked)); + black_box(&sel); + } + }); + out.push(ms / REPS as f64); + }; + if i % 2 == 0 { + run(one_by_one, &mut old); + run(one_call, &mut new); + } else { + run(one_call, &mut new); + run(one_by_one, &mut old); + } + } + let (old, new) = (median(old), median(new)); + println!(" {name:<44} {:>7} {:>6} {old:>12.3} {new:>12.3} {:>8.1}x", picked.len(), b.objects.len(), old / new); +} + +fn main() { + let unit = if thread_cpu_ns().is_some() { "CPU ms" } else { "wall ms" }; + println!(" {:<44} {:>7} {:>6} {:>12} {:>12} {:>9}", "document", "picked", "ids", format!("add, {unit}"), format!("set, {unit}"), "speedup"); + for n in [500, 2_000, 5_000] { + bench(&format!("{n} open paths, {ANCHORS} anchors each"), || (0..n).map(|i| PathData::single(row(i))).collect()); + } + bench("one path of 2,000 open subpaths", || vec![PathData::new((0..2_000).map(row).collect())]); + let whole: Vec = (0..iters()) + .map(|_| { + let mut s = fixture((0..2_000).map(|i| PathData::single(row(i))).collect()); + measure(|| drop(black_box(exec(&mut s, "path.cutAtAnchors", json!({}))))) + }) + .collect(); + println!(" path.cutAtAnchors, 2,000 open paths, whole command: {:.3} {unit}", median(whole)); +} diff --git a/crates/engine/examples/direction_handles_bench.rs b/crates/engine/examples/direction_handles_bench.rs new file mode 100644 index 0000000000..88b5b721bd --- /dev/null +++ b/crates/engine/examples/direction_handles_bench.rs @@ -0,0 +1,145 @@ +//! `cargo run --release -p vectorcraft-engine --example direction_handles_bench` prints the time +//! Select › Object › Direction Handles takes to select every path of documents of 2,000, 10,000 and +//! 20,000 rectangles, spread over two layers with one group. For each size it times, on the same +//! paths and anchors, the selection built one path at a time (a clear, then an add per path) and +//! the selection built with one `Selection::set` call, checks that the two are equal, and then +//! times the whole `select.object.directionHandles` command. +//! On Linux each row is the thread's CPU time, read from `/proc/thread-self/schedstat`; elsewhere +//! it is wall time, and the first line says which. `ITERS` sets the runs per row (default 7); each +//! row is the median in ms. A run of the two selection rows repeats the selection 1,000,000 / paths +//! times and gives the time of one. +// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::BTreeSet; +use std::hint::black_box; +use std::time::Instant; + +use serde_json::json; +use vectorcraft_color::Color; +use vectorcraft_doc::{Document, NodeId, Selection}; +use vectorcraft_engine::Session; +use vectorcraft_geom::Rect; +use vectorcraft_testkit::fixtures::DocBuilder; + +type Items = Vec<(NodeId, BTreeSet<(usize, usize)>)>; + +fn iters() -> usize { + std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7) +} + +/// The thread's CPU time in ns, or `None` where `/proc/thread-self/schedstat` cannot be read. +fn cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// The time `f` takes in ms: CPU time when [`cpu_ns`] reads, wall time otherwise. +fn ms(f: impl FnOnce()) -> f64 { + let (cpu, wall) = (cpu_ns(), Instant::now()); + f(); + match (cpu, cpu_ns()) { + (Some(a), Some(b)) => (b - a) as f64 / 1e6, + _ => wall.elapsed().as_secs_f64() * 1000.0, + } +} + +fn median(mut v: Vec) -> f64 { + v.sort_by(f64::total_cmp); + v[v.len() / 2] +} + +/// `n` 10 pt squares: a tenth of them in one group and the rest loose, half on each of two layers. +fn document(n: usize) -> Document { + let mut b = DocBuilder::new(4000.0, 4000.0); + let square = |b: &mut DocBuilder, i: usize| { + let (x, y) = ((i % 200) as f64 * 12.0, (i / 200) as f64 * 12.0); + b.rect_node(Rect::new(x, y, x + 10.0, y + 10.0), Color::rgb(0.2, 0.4, 0.6)) + }; + let grouped = n / 10; + let kids = (0..grouped).map(|i| square(&mut b, i)).collect(); + b.group(kids, false); + for i in grouped..n { + if i == n / 2 { + b.layer("Layer 2"); + } + let node = square(&mut b, i); + b.add(node); + } + b.build() +} + +/// Selects `items` one path at a time: a clear, then an add and an anchor insert per path. +fn one_by_one(sel: &mut Selection, items: Items) { + sel.clear(); + for (id, refs) in items { + sel.add(id); + sel.anchors.insert(id, refs); + } +} + +/// Selects `items` with one `Selection::set` call and one extend of the anchors. +fn with_set(sel: &mut Selection, items: Items) { + sel.set(items.iter().map(|(id, _)| *id)); + sel.anchors.extend(items); +} + +fn row(name: &str, ms: f64) { + println!(" {name:<44} {ms:>10.3} ms"); +} + +fn bench(n: usize) { + println!("{n} paths"); + let mut s = Session::new(); + s.add_document(document(n), None); + s.execute("select.all", &json!({})).unwrap(); + let start = s.doc().unwrap().selection.clone(); + s.execute("select.object.directionHandles", &json!({})).unwrap(); + let command = s.doc().unwrap().selection.clone(); + // The paths and anchors the command selects, in its order. + let items: Items = command.objects.iter().map(|id| (*id, command.anchors[id].clone())).collect(); + assert_eq!(items.len(), n); + + // Each run selects `reps` times, on copies made before the clock starts, and gives the time of one. + let reps = (1_000_000 / n).max(1); + let time = |f: fn(&mut Selection, Items)| -> (f64, Selection) { + let mut last = Selection::default(); + let runs = (0..iters()) + .map(|_| { + let mut work: Vec<(Selection, Items)> = (0..reps).map(|_| (start.clone(), items.clone())).collect(); + let t = ms(|| { + for (sel, it) in &mut work { + f(sel, black_box(std::mem::take(it))); + } + }); + last = work.pop().unwrap().0; + t / reps as f64 + }) + .collect(); + (median(runs), last) + }; + let (old, a) = time(one_by_one); + let (new, b) = time(with_set); + assert_eq!(a, b, "both ways give the same selection"); + let mut want = start.clone(); + with_set(&mut want, items.clone()); + assert_eq!(want.objects, command.objects); + assert_eq!(want.anchors, command.anchors); + row("selection, one add per path", old); + row("selection, one set call", new); + println!(" {:<44} {:>10.1}x", "ratio", old / new); + + let runs = (0..iters()) + .map(|_| { + s.execute("select.all", &json!({})).unwrap(); + ms(|| drop(black_box(s.execute("select.object.directionHandles", &json!({})).unwrap()))) + }) + .collect(); + row("select.object.directionHandles, whole command", median(runs)); +} + +fn main() { + println!("{}", if cpu_ns().is_some() { "thread CPU time, median of runs" } else { "wall time, median of runs" }); + for n in [2_000, 10_000, 20_000] { + bench(n); + } +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 19695fd4ff..c4a86dd3a5 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -43,6 +43,7 @@ pub(crate) mod graph; mod halftone; pub mod help; pub mod importmatches; +mod info; pub(crate) mod inline; mod interactivity; mod intertwine; @@ -97,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; @@ -232,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. @@ -344,6 +343,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(docmenu::specs()); v.extend(variablecmds::specs()); v.extend(docinfo::specs()); + v.extend(info::specs()); v.extend(panelcmds::specs()); v.extend(artboardalign::specs()); v.extend(buildcmds::specs()); @@ -827,7 +827,8 @@ pub use docmenu::guide_indexes; pub(crate) use edit::{settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned}; -pub use plugin_call::{Location, key_location, location_in, location_keys}; +pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys}; +pub use select::SIMILAR; pub(crate) use vectorcraft_doc::range::parse_range; /// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see @@ -892,6 +893,17 @@ 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; + +/// The Variables panel's sort (`variable.sort`) and its rows in that order. +pub use variablecmds::{VariableSort, VariableSortKey, variable_order}; + /// Command ids kept only so older scripts keep working: `(alias, the command it duplicates)`. /// They run as before but the command palette leaves them out (it lists the command once). pub const ALIASES: &[(&str, &str)] = &[("object.convertDocumentColorMode", "file.documentColorMode")]; diff --git a/crates/engine/src/cmd/actionset.rs b/crates/engine/src/cmd/actionset.rs index b6a9118380..ad23db1c64 100644 --- a/crates/engine/src/cmd/actionset.rs +++ b/crates/engine/src/cmd/actionset.rs @@ -9,8 +9,9 @@ //! text. Each action is an `/action-N` block with a hexadecimal `/name`; each step is an `/event-N` //! block inside one, with its `/internalName` in parentheses, the `/localizedName` it is shown with //! as hexadecimal text, and `/isOn` 0 when it is left out of playback; each value a step was -//! recorded with is a `/parameter-N` block inside it, which is counted, and whose hexadecimal -//! `/value` is checked against its byte count. The set's `/actionCount`, an action's `/eventCount` +//! recorded with is a `/parameter-N` block inside it, which is counted, whose `/key` (a number), +//! `/type` (text in parentheses) and `/value` (a number, text in parentheses or hexadecimal text) are +//! kept, and whose hexadecimal `/value` is checked against its byte count. The set's `/actionCount`, an action's `/eventCount` //! and a step's `/parameterCount` give how many actions, steps and recorded values follow. //! The layout follows the README of Inventsable's Redesigning-Illustrator-Actions-in-Scripting //! (https://github.com/Inventsable/Redesigning-Illustrator-Actions-in-Scripting), the forum post @@ -40,6 +41,8 @@ const MAX_STEPS: usize = 10_000; /// The most steps read in the set: a small text can hold hundreds of thousands of empty steps, and /// the answer holds an object for each. const MAX_SET_STEPS: usize = 100_000; +/// The most recorded values kept in the set; the others are counted but not kept. +const MAX_VALUES: usize = 100_000; /// The longest name kept (bytes). const MAX_NAME: usize = 1024; /// The most tokens listed as unread. @@ -56,7 +59,7 @@ pub fn specs() -> Vec { "Read Action Set File", [], None, - "{path? | data?: the file's text | dataBase64?, name?: the file's name (default: the path's)} read an action set another app saved as text (.aia, starting \"/version\") without changing anything → {set: the set's /name (else the file's name without its extension, else empty), version, actions: [{name, steps: [{name: the step's /internalName, label: its /localizedName, or null when it has none or it is blank, on: false when /isOn is 0, params: how many /parameter blocks it has, line}]}], unread: [{line, text}] (tokens that aren't read, at most 1000), truncated: true when a cap stopped the reading (8 MiB, 16 open blocks, 1,000 actions, 10,000 steps in an action, 100,000 steps in the set; names past 1,024 bytes are cut), when the text ends inside a block or a value or after a field's name, when /actionCount, /eventCount or a step's /parameterCount differs from the actions, steps or recorded values read (a negative count, one too large for a number and one that isn't a number always differ), or when a hexadecimal name, label or recorded /value isn't as many bytes as its count says}. Give exactly one of path, data and dataBase64. Text that doesn't start with /version and a number is an error", + "{path? | data?: the file's text | dataBase64?, name?: the file's name (default: the path's)} read an action set another app saved as text (.aia, starting \"/version\") without changing anything → {set: the set's /name (else the file's name without its extension, else empty), version, actions: [{name, steps: [{name: the step's /internalName, label: its /localizedName, or null when it has none or it is blank, on: false when /isOn is 0, params: how many /parameter blocks it has, values: [{key: the block's /key, or null, type: its /type, or null, value: its /value when it is a number, or text that is UTF-8 (else null), bytes?: the text's length in bytes}] (the first 100,000 recorded values in the set), line}]}], unread: [{line, text}] (tokens that aren't read, at most 1000), truncated: true when a cap stopped the reading (8 MiB, 16 open blocks, 1,000 actions, 10,000 steps in an action, 100,000 steps in the set; names past 1,024 bytes are cut), when the text ends inside a block or a value or after a field's name, when /actionCount, /eventCount or a step's /parameterCount differs from the actions, steps or recorded values read (a negative count, one too large for a number and one that isn't a number always differ), or when a hexadecimal name, label or recorded /value isn't as many bytes as its count says}. Give exactly one of path, data and dataBase64. Text that doesn't start with /version and a number is an error", always, read )] @@ -73,12 +76,33 @@ pub struct AiaStep { pub on: Option, /// How many `/parameter-N` blocks it has. pub params: usize, + /// Its `/parameter-N` blocks, in order, while the set keeps at most [`MAX_VALUES`]. + pub values: Vec, /// Its `/parameterCount`, if it has one. pub declared: Option, /// The line its block opens on (from 1). pub line: usize, } +/// A value a step was recorded with: a `/parameter-N` block. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct AiaValue { + /// Its `/key`, if it has one that fits an `i64`. + pub key: Option, + /// Its `/type`, read as UTF-8 with replacement characters, if it has one. + pub kind: Option, + /// Its `/value`, if it is a number that fits an `i64` or text. + pub value: Option, +} + +/// A recorded `/value` that is kept. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum AiaData { + Int(i64), + /// The bytes of text in parentheses or of hexadecimal text. + Text(Vec), +} + /// An action: an `/action-N` block. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct AiaAction { @@ -106,6 +130,8 @@ pub struct AiaSet { pub truncated: bool, /// How many steps were read in all the actions. steps: usize, + /// How many recorded values were kept in all the steps. + values: usize, } /// A token of the text. @@ -252,7 +278,8 @@ fn hex_bytes(digits: &[u8]) -> Option> { enum Kind { Action, Step, - Param, + /// A recorded value, and whether it is kept. + Param(bool), /// A block that isn't read, or one past a cap. Other, } @@ -315,12 +342,18 @@ fn open_block(set: &mut AiaSet, stack: &[Kind], name: &[u8], line: usize) -> Kin } }, Some(Kind::Step) if numbered(name, b"parameter-") => { + let mut kept = false; if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) { s.params += 1; + if set.values < MAX_VALUES { + s.values.push(AiaValue::default()); + set.values += 1; + kept = true; + } } - Kind::Param + Kind::Param(kept) } - Some(Kind::Param | Kind::Other) => Kind::Other, + Some(Kind::Param(_) | Kind::Other) => Kind::Other, _ => { unread(set, line, format!("/{} {{", String::from_utf8_lossy(name))); Kind::Other @@ -355,12 +388,23 @@ fn set_hex(set: &mut AiaSet, kind: Option<&Kind>, name: Option<&[u8]>, bytes: Op } } -/// Mark `set` truncated when the hexadecimal `/value` on `line` isn't as many bytes as its count -/// says. -fn check_value(set: &mut AiaSet, bytes: Option>, line: usize) { - if bytes.is_none() { +/// Set the field `name` of the recorded value open on `line` to `token`: its `/key`, `/type` or +/// `/value`, when the value is `kept`. A hexadecimal `/value` that isn't as many bytes as its count +/// says marks `set` truncated, kept or not. +fn set_param(set: &mut AiaSet, kept: bool, name: Option<&[u8]>, token: Token, line: usize) { + if name == Some(b"value".as_slice()) && matches!(token, Token::Hex(None)) { set.truncated = true; unread(set, line, BAD_HEX); + return; + } + let value = set.actions.last_mut().and_then(|a| a.steps.last_mut()).and_then(|s| s.values.last_mut()); + let Some(v) = value.filter(|_| kept) else { return }; + match (name, token) { + (Some(b"key"), Token::Int(key)) => v.key = key, + (Some(b"type"), Token::Text(t)) => v.kind = Some(String::from_utf8_lossy(&t).into_owned()), + (Some(b"value"), Token::Int(Some(n))) => v.value = Some(AiaData::Int(n)), + (Some(b"value"), Token::Text(t) | Token::Hex(Some(t))) => v.value = Some(AiaData::Text(t)), + _ => {} } } @@ -448,13 +492,13 @@ pub fn read_aia(bytes: &[u8]) -> std::result::Result { unread(&mut set, line, "}"); } } - Token::Hex(bytes) if matches!(stack.last(), Some(Kind::Param)) => { - if field(&mut pending).as_deref() == Some(b"value".as_slice()) { - check_value(&mut set, bytes, line); - } + _ if matches!(stack.last(), Some(Kind::Param(_))) => { + let kept = matches!(stack.last(), Some(Kind::Param(true))); + let name = field(&mut pending); + set_param(&mut set, kept, name.as_deref(), token, line); } - // The other values inside a recorded value, or a block that isn't read. - _ if matches!(stack.last(), Some(Kind::Param | Kind::Other)) => { + // The values inside a block that isn't read. + _ if matches!(stack.last(), Some(Kind::Other)) => { pending = None; } Token::Hex(bytes) => { @@ -521,6 +565,21 @@ pub fn read_aia(bytes: &[u8]) -> std::result::Result { Ok(set) } +/// A recorded value in `actionSet.read`'s answer: `{key, type, value, bytes?}`, the value a number, +/// text that is UTF-8 (else null) with its length in bytes, or null. +fn value_json(v: &AiaValue) -> Value { + let mut out = json!({ "key": v.key, "type": v.kind, "value": null }); + match &v.value { + Some(AiaData::Int(n)) => out["value"] = json!(n), + Some(AiaData::Text(t)) => { + out["value"] = json!(std::str::from_utf8(t).ok()); + out["bytes"] = json!(t.len()); + } + None => {} + } + out +} + fn read(_: &mut Session, p: &Value) -> Result { const C: &str = "actionSet.read"; let (path, data, b64) = (text_param(p, "path", C)?, text_param(p, "data", C)?, text_param(p, "dataBase64", C)?); @@ -544,7 +603,8 @@ fn read(_: &mut Session, p: &Value) -> Result { .iter() .map(|s| { let label = s.label.clone().filter(|l| !l.trim().is_empty()); - json!({ "name": s.name, "label": label, "on": s.on != Some(0), "params": s.params, "line": s.line }) + let values: Vec = s.values.iter().map(value_json).collect(); + json!({ "name": s.name, "label": label, "on": s.on != Some(0), "params": s.params, "values": values, "line": s.line }) }) .collect(); json!({ "name": a.name, "steps": steps }) 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/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index d7cae868ed..f81d7a599a 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -21,8 +21,9 @@ use vectorcraft_geom::{Affine, Point, Rect}; use vectorcraft_render::effects; use super::super::appearance::series_children_in_paint_order; +use super::super::colorcmds::edit_if_changed; use super::super::edit::selected_roots; -use super::super::graph::capture_series_object_opacity; +use super::super::graph::{capture_series_object_opacity, series_groups_among}; use super::super::menucmds::whole_or; use super::super::object::{choice, object_bounds_transform, scaling, transform_node, transform_patterns}; use super::super::typecmd::refresh_bounds_of; @@ -92,7 +93,7 @@ pub fn specs() -> Vec { "Randomize Opacity", ["Object", "Plug-ins", "Arrange Tools"], None, - "{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step; it is the object's opacity, as the Transparency panel sets it. On paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw (docs/mcp.md) → {count}", + "{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step (none when no opacity changes); it is the object's opacity, as the Transparency panel sets it. On paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw, and on a series group, the group's own (docs/mcp.md) → {count}", has_selection, randomize_opacity ), @@ -101,7 +102,7 @@ pub fn specs() -> Vec { "Sort Objects", ["Object", "Plug-ins", "Arrange Tools"], None, - "{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw (docs/mcp.md). A run that changes nothing makes no step → {count}", + "{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw, and on a series group, the group's own (docs/mcp.md). A run that changes nothing makes no step → {count}", has_multi, sort ), @@ -397,7 +398,8 @@ fn randomize_opacity(s: &mut Session, p: &Value) -> Result { return Ok(json!({ "count": 0 })); } let (lo, hi) = ((min / 100.0) as f32, (max / 100.0) as f32); - s.edit("Randomize Opacity", |d, _| { + // A run that gives every object the opacity it has records no undo step. + edit_if_changed(s, "Randomize Opacity", |_, d| { let mut changed = vec![]; for id in &ids { let o = rng.range(lo, hi); @@ -409,16 +411,18 @@ fn randomize_opacity(s: &mut Session, p: &Value) -> Result { } } keep_series_opacity(d, &changed); - Ok(()) + Ok(((), !changed.is_empty())) })?; Ok(json!({ "count": ids.len() })) } /// Store on their graphs the opacity just given to the paths among `changed` (objects whose opacity changed) that are /// directly in a graph series, with their blend mode, so that every path of the series has them when the graph is drawn -/// again; the frontmost of them in a series sets them. +/// again; the frontmost of them in a series sets them. A series group among `changed` has its own opacity stored for the +/// group. fn keep_series_opacity(d: &mut vectorcraft_doc::Document, changed: &[NodeId]) { - let marks = series_children_in_paint_order(d, changed); + let mut marks = series_children_in_paint_order(d, changed); + marks.extend(series_groups_among(d, changed)); capture_series_object_opacity(d, &marks); } @@ -516,16 +520,18 @@ fn sort(s: &mut Session, p: &Value) -> Result { } let wanted: Vec<(&Sorted, f64)> = rank.iter().filter_map(|i| items.get(*i)).zip(values).collect(); if apply == "opacity" { - if wanted.iter().all(|(o, v)| (o.opacity - v).abs() < 1e-6) { + // The opacity each object is given, as stored; an object whose stored opacity it already is has not changed. + let given: Vec<(NodeId, f32)> = wanted.iter().map(|(o, v)| (o.id, (v / 100.0) as f32)).collect(); + let changed: Vec = given.iter().filter(|(id, a)| d.node(*id).is_some_and(|n| n.opacity != *a)).map(|(id, _)| *id).collect(); + if changed.is_empty() { return Ok(count); } s.edit("Sort Objects", |d, _| { - for (o, v) in &wanted { - if let Some(n) = d.node_mut(o.id) { - n.opacity = (v / 100.0) as f32; + for (id, a) in &given { + if let Some(n) = d.node_mut(*id) { + n.opacity = *a; } } - let changed: Vec = wanted.iter().filter(|(o, v)| (o.opacity - v).abs() >= 1e-6).map(|(o, _)| o.id).collect(); keep_series_opacity(d, &changed); Ok(()) })?; diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index 85191935b2..759f6f321e 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -393,6 +393,25 @@ fn randomize_opacity_takes_ids_and_leaves_the_rest() { assert_eq!((opacity(&s, g), opacity(&s, a), opacity(&s, b)), (0.2, 1.0, 1.0)); } +#[test] +fn randomize_opacity_records_no_undo_step_when_no_opacity_changes() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 5.0, 5.0); + let b = rect(&mut s, 10.0, 0.0, 5.0, 5.0); + select(&mut s, &[a, b]); + let n = steps(&s); + // Every object already has the one opacity the range allows. + let r = s.execute("addon.arrange.randomizeOpacity", &json!({"min": 100, "max": 100})).unwrap(); + assert_eq!(r["count"], json!(2)); + assert_eq!(steps(&s), n); + assert_eq!((opacity(&s, a), opacity(&s, b)), (1.0, 1.0)); + s.execute("addon.arrange.randomizeOpacity", &json!({"min": 40, "max": 40})).unwrap(); + assert_eq!(steps(&s), n + 1); + s.execute("addon.arrange.randomizeOpacity", &json!({"min": 40, "max": 40})).unwrap(); + assert_eq!(steps(&s), n + 1, "the same opacities again"); + assert_eq!((opacity(&s, a), opacity(&s, b)), (0.4, 0.4)); +} + #[test] fn randomize_opacity_refuses_bad_params() { let mut s = session(); diff --git a/crates/engine/src/cmd/addons/cleanup.rs b/crates/engine/src/cmd/addons/cleanup.rs index cba512cd18..d5f241b4ee 100644 --- a/crates/engine/src/cmd/addons/cleanup.rs +++ b/crates/engine/src/cmd/addons/cleanup.rs @@ -9,7 +9,7 @@ mod tests; mod text; use serde_json::{Map, Value, json}; -use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_doc::{Document, LockedArtboards, Node, NodeId, NodeKind}; use vectorcraft_geom::{PathData, SubPath}; use vectorcraft_pathops::addons as po; @@ -37,7 +37,7 @@ pub fn specs() -> Vec { "Simplify Anchors (Keep Shape)…", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{tolerance?: 1..100 (20; higher removes more anchors and lets the outline move further from where it was, up to tolerance × 0.02 pt), protectCorners?: bool (false; anchors where the path turns by more than 30° stay), ids?: [id…] (default: the selection)} remove the anchors each path under the objects can do without, refitting the handles beside each so the outline keeps its shape, as one undo step; open ends stay, and locked and hidden paths are left out → {ids, before, after} anchor counts", + "{tolerance?: 1..100 (20; higher removes more anchors and lets the outline move further from where it was, up to tolerance × 0.02 pt), protectCorners?: bool (false; anchors where the path turns by more than 30° stay), ids?: [id…] (default: the selection)} remove the anchors each path under the objects can do without, refitting the handles beside each so the outline keeps its shape, as one undo step when a path changes; open ends stay; from the selection, locked and hidden paths are left out, and named by `ids`, the paths of the objects, groups and layers it names are taken even when locked or hidden, but not those on a locked artboard; a changed path loses its selected anchors and segments → {ids, before, after} anchor counts", has_selection, simplify ), @@ -73,7 +73,7 @@ pub fn specs() -> Vec { "Deep Ungroup…", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{includeClipGroups?: bool (false: clipping groups, and the art inside them, stay as they are; true: they are ungrouped too and their clipping paths become plain paths), ids?: [id…] (default: the selection)} ungroup every level of the groups among the objects, as one undo step; each object keeps the opacity of the groups it was in; locked and hidden groups stay whole, and locked and hidden objects stay locked or hidden and are not selected → {ids (the objects selected: those left, or with no group to take apart the selection as it was), ungrouped (groups)}", + "{includeClipGroups?: bool (false: clipping groups, and the art inside them, stay as they are; true: they are ungrouped too and their clipping paths become plain paths), ids?: [id…] (default: the selection)} ungroup every level of the groups among the objects, as one undo step when a group goes; each object keeps the opacity of the groups it was in; from the selection, locked and hidden groups stay whole; named by `ids`, the groups it names and the groups in the groups and layers it names are ungrouped even when locked or hidden (a named layer stays), but not those on a locked artboard, and their objects become hidden or locked when a group was; locked and hidden objects stay locked or hidden and are not selected → {ids (the objects selected: those left, or with no group to take apart the selection as it was), ungrouped (groups)}", has_selection, deep_ungroup ), @@ -82,7 +82,7 @@ pub fn specs() -> Vec { "Rejoin Path Pieces…", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{gap?: pt 0..6 (0.1), ids?: [id…] (default: the selection)} weld the open paths under the objects whose ends lie within the gap of each other back into paths: an end joins one other end, the one the path turns least to go on into, pieces may run either way, and a chain whose ends meet closes; each path takes the place and paint of its topmost piece, as one undo step → {ids, joined (paths made), removed (pieces merged into them)}", + "{gap?: pt 0..6 (0.1), ids?: [id…] (default: the selection)} weld the open paths under the objects whose ends lie within the gap of each other back into paths: an end joins one other end, the one the path turns least to go on into, pieces may run either way, and a chain whose ends meet closes; each path takes the place and paint of its topmost piece, as one undo step when a path is made; from the selection, locked and hidden paths are left out, and named by `ids`, they are taken, but not those on a locked artboard; only pieces alike in being hidden (by themselves or a group or layer above them) and in being locked join; locked and hidden paths made are not selected → {ids, joined (paths made), removed (pieces merged into them)}", has_selection, rejoin ), @@ -91,9 +91,28 @@ pub fn specs() -> Vec { v } -/// The paths (not guides) under `roots`, compound path members included; locked and hidden -/// paths, and those in locked or hidden groups, stay out. -fn paths_under(d: &Document, roots: &[NodeId]) -> Vec { +/// Whether a request names its objects with `ids` (present and not null) rather than taking the +/// selection. +fn named(p: &Value) -> bool { + p.get("ids").is_some_and(|v| !v.is_null()) +} + +/// Keep the items of `items` whose object (`id`) a command acts on: when `named`, every one not on +/// a locked artboard, locked and hidden ones (and ones in a locked or hidden group or layer) +/// included; else only those that can be edited. +fn retain_targets(d: &Document, items: &mut Vec, named: bool, id: impl Fn(&T) -> NodeId) { + if named { + let locks = d.locked_artboards(); + items.retain(|t| !locks.holds_id(id(t))); + } else { + let editable = d.editable(); + items.retain(|t| editable(id(t))); + } +} + +/// The paths (not guides) under `roots`, compound path members included, that a command acts on +/// ([`retain_targets`]). +fn paths_under(d: &Document, roots: &[NodeId], named: bool) -> Vec { let mut out = vec![]; for n in roots.iter().filter_map(|id| d.node(*id)) { n.walk(&mut |c| { @@ -102,8 +121,7 @@ fn paths_under(d: &Document, roots: &[NodeId]) -> Vec { } }); } - let editable = d.editable(); - out.retain(|id| editable(*id)); + retain_targets(d, &mut out, named, |id| *id); out } @@ -116,7 +134,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result { let protect = switch_or(p, "protectCorners", false, C)?; let roots = checked_ids_or_selection(s, p, C)?; let d = &s.doc()?.doc; - let ids = paths_under(d, &roots); + let ids = paths_under(d, &roots, named(p)); let paths: Vec<(NodeId, &PathData)> = ids.iter().filter_map(|id| Some((*id, d.node(*id)?.path_data()?))).collect(); let before: usize = paths.iter().map(|(_, p)| p.anchor_count()).sum(); if before > MAX_ANCHORS { @@ -258,10 +276,11 @@ fn ungroupable(n: &Node, clips: bool) -> bool { } /// `n` with every level of grouping Deep Ungroup takes apart removed, into `out`; `count` counts -/// the groups. Members take on the opacity of the groups they were in, and a clipping path -/// becomes a plain path. A locked or hidden group stays whole. -fn flatten(n: Node, clips: bool, out: &mut Vec, count: &mut usize) { - if !ungroupable(&n, clips) || n.locked || !n.visible { +/// the groups. Members take on the opacity of the groups they were in, are hidden when one of them +/// was hidden and locked when one of them was locked, and a clipping path becomes a plain path. A +/// locked or hidden group stays whole unless `named`. +fn flatten(n: Node, clips: bool, named: bool, out: &mut Vec, count: &mut usize) { + if !ungroupable(&n, clips) || (!named && (n.locked || !n.visible)) { out.push(n); return; } @@ -276,26 +295,57 @@ fn flatten(n: Node, clips: bool, out: &mut Vec, count: &mut usize) { *clipping = false; } c.opacity *= n.opacity; - flatten(c, clips, out, count); + c.visible &= n.visible; + c.locked |= n.locked; + flatten(c, clips, named, out, count); } } +/// The outermost groups Deep Ungroup takes apart in layer `n`, its sublayers included, in paint +/// order, leaving out those on a locked artboard. +fn groups_in_layer(d: &Document, n: &Node, clips: bool, out: &mut Vec) { + let locks = d.locked_artboards(); + fn visit(n: &Node, clips: bool, locks: &LockedArtboards, out: &mut Vec) { + for c in n.children().into_iter().flatten() { + if c.is_layer() { + visit(c, clips, locks, out); + } else if ungroupable(c, clips) && !locks.holds_id(c.id) { + out.push(c.id); + } + } + } + visit(n, clips, &locks, out); +} + fn deep_ungroup(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.cleanup.deepUngroup"; let clips = switch_or(p, "includeClipGroups", false, C)?; - let roots = checked_ids_or_selection(s, p, C)?; + let named = named(p); + let mut roots = checked_ids_or_selection(s, p, C)?; let d = &s.doc()?.doc; - // Locked and hidden objects, and those in locked or hidden groups, stay as they are. - let roots: Vec = { - let editable = d.editable(); - roots.into_iter().filter(|id| editable(*id)).collect() - }; + // From the selection, locked and hidden objects, and those in locked or hidden groups, stay as + // they are; named, only those on a locked artboard do. + retain_targets(d, &mut roots, named, |id| *id); + // A named layer stays: the groups in it, and in its sublayers, are taken apart. + let mut groups = vec![]; + for id in roots { + match d.node(id) { + Some(n) if named && n.is_layer() => { + let at = groups.len(); + groups_in_layer(d, n, clips, &mut groups); + if groups.len() == at { + groups.push(id); + } + } + _ => groups.push(id), + } + } let (mut items, mut selected, mut count) = (vec![], vec![], 0); - for id in &roots { + for id in &groups { match d.node(*id).filter(|n| ungroupable(n, clips)) { Some(n) => { let mut out = vec![]; - flatten(n.clone(), clips, &mut out, &mut count); + flatten(n.clone(), clips, named, &mut out, &mut count); selected.extend(out.iter().map(|n| n.id)); items.push((*id, out)); } @@ -304,7 +354,7 @@ fn deep_ungroup(s: &mut Session, p: &Value) -> Result { } // With no group to take apart, the document, the selection and the undo history stay as they // are, and the reply lists the selection. - if items.is_empty() { + if count == 0 { selected = s.doc()?.selection.objects.to_vec(); } else { selected = s.edit("Deep Ungroup", move |d, sel| { @@ -319,26 +369,39 @@ fn deep_ungroup(s: &mut Session, p: &Value) -> Result { Ok(json!({ "ids": selected.iter().map(|i| i.0).collect::>(), "ungrouped": count })) } +/// One path Rejoin Path Pieces takes: its id, its subpath, and whether it and every group and layer +/// above it are visible, and whether they are all unlocked. +type Piece = (NodeId, SubPath, (bool, bool)); + /// The open single-subpath paths under `roots` that Rejoin Path Pieces takes, in paint order -/// (compound path members, clipping paths and guides stay out). -fn pieces(d: &Document, roots: &[NodeId]) -> Vec<(NodeId, SubPath)> { - fn visit(n: &Node, out: &mut Vec<(NodeId, SubPath)>) { +/// (compound path members, clipping paths and guides stay out; [`retain_targets`]). +fn pieces(d: &Document, roots: &[NodeId], named: bool) -> Vec { + fn visit(n: &Node, above: (bool, bool), out: &mut Vec) { + let state = (above.0 && n.visible, above.1 && !n.locked); match &n.kind { NodeKind::Path { path, guide: false, clipping: false, .. } => { if let [sp] = path.subpaths.as_slice() && !sp.closed { - out.push((n.id, sp.clone())); + out.push((n.id, sp.clone(), state)); } } - NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().for_each(|c| visit(c, out)), + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().for_each(|c| visit(c, state, out)), _ => {} } } let mut out = vec![]; - roots.iter().filter_map(|id| d.node(*id)).for_each(|n| visit(n, &mut out)); - let editable = d.editable(); - out.retain(|(id, _)| editable(*id)); + for (id, n) in roots.iter().filter_map(|id| Some((*id, d.node(*id)?))) { + // The groups and layers above the root, and their state. + let above = d.ancestry(id).unwrap_or_default(); + let above = above.split_last().map_or(&[][..], |(_, up)| up); + if above.last().and_then(|i| d.node(*i)).is_some_and(|parent| matches!(parent.kind, NodeKind::Compound { .. })) { + continue; + } + let state = above.iter().filter_map(|i| d.node(*i)).fold((true, true), |(v, u), a| (v && a.visible, u && !a.locked)); + visit(n, state, &mut out); + } + retain_targets(d, &mut out, named, |piece| piece.0); out } @@ -349,18 +412,26 @@ fn rejoin(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "`gap` must be from 0 to 6 pt")); } let roots = checked_ids_or_selection(s, p, C)?; - let found = pieces(&s.doc()?.doc, &roots); + let found = pieces(&s.doc()?.doc, &roots, named(p)); if found.len() > MAX_OBJECTS { return Err(EngineError::Other("Rejoin Path Pieces: too many paths to rejoin at once".into())); } - let subpaths: Vec = found.iter().map(|(_, sp)| sp.clone()).collect(); - // Each chain becomes its topmost piece (the last in paint order); the others go. + // Only pieces alike in being shown and in being unlocked join, so that a joined path neither + // shows hidden art nor hides shown art, nor locks or unlocks a piece. let (mut kept, mut gone) = (vec![], vec![]); - for j in po::rejoin(&subpaths, gap) { - let ids: Vec = j.members.iter().filter_map(|&m| found.get(m).map(|f| f.0)).collect(); - let Some(&top) = j.members.iter().max().and_then(|&m| found.get(m).map(|f| &f.0)) else { continue }; - gone.extend(ids.into_iter().filter(|id| *id != top)); - kept.push((top, j.path)); + for state in [(true, true), (true, false), (false, true), (false, false)] { + let part: Vec<&Piece> = found.iter().filter(|f| f.2 == state).collect(); + if part.is_empty() { + continue; + } + let subpaths: Vec = part.iter().map(|f| f.1.clone()).collect(); + // Each chain becomes its topmost piece (the last in paint order); the others go. + for j in po::rejoin(&subpaths, gap) { + let ids: Vec = j.members.iter().filter_map(|&m| part.get(m).map(|f| f.0)).collect(); + let Some(top) = j.members.iter().max().and_then(|&m| part.get(m).map(|f| f.0)) else { continue }; + gone.extend(ids.into_iter().filter(|id| *id != top)); + kept.push((top, j.path)); + } } if !kept.is_empty() { let ids: Vec = kept.iter().map(|k| k.0).collect(); @@ -369,7 +440,9 @@ fn rejoin(s: &mut Session, p: &Value) -> Result { set_path(d, *id, PathData::single(sp.clone())); } d.remove_many(&gone)?; - sel.set(ids); + // Locked and hidden paths, and those in locked or hidden groups, are not selected. + let editable = d.editable(); + sel.set(ids.into_iter().filter(|id| editable(*id))); Ok(()) })?; } diff --git a/crates/engine/src/cmd/addons/cleanup/tests.rs b/crates/engine/src/cmd/addons/cleanup/tests.rs index 4d4ed6461b..e1a50b928b 100644 --- a/crates/engine/src/cmd/addons/cleanup/tests.rs +++ b/crates/engine/src/cmd/addons/cleanup/tests.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind}; +use vectorcraft_doc::{Appearance, LayerColor, Node, NodeId, NodeKind}; use vectorcraft_geom::{FillRule, Rect}; use crate::Session; @@ -123,18 +123,100 @@ fn simplify_leaves_locked_and_hidden_paths_alone() { assert_eq!(r["before"], 16); assert!(anchors(&s, ids[0]) < 16); assert_eq!((anchors(&s, ids[1]), anchors(&s, ids[2])), (16, 16)); - // Named by `ids`, or in a locked group, a path stays too, with no undo step. - let steps = undo_steps(&s); - s.execute("addon.cleanup.simplify", &json!({"ids": [ids[1].0, ids[2].0]})).unwrap(); - assert_eq!((anchors(&s, ids[1]), anchors(&s, ids[2])), (16, 16)); - assert_eq!(undo_steps(&s), steps); + // In a selected locked group, a path stays too, with no undo step. change(&mut s, ids[1], |n| n.locked = false); change(&mut s, g, |n| n.locked = true); let steps = undo_steps(&s); - let r = s.execute("addon.cleanup.simplify", &json!({"ids": [g.0]})).unwrap(); + let r = s.execute("addon.cleanup.simplify", &json!({})).unwrap(); assert_eq!((r["before"].as_u64(), r["after"].as_u64()), (Some(0), Some(0))); assert_eq!(anchors(&s, ids[1]), 16); assert_eq!(undo_steps(&s), steps); + // Named by `ids`, the locked group's paths, its hidden one included, are simplified. + let r = s.execute("addon.cleanup.simplify", &json!({"ids": [g.0]})).unwrap(); + assert_eq!(r["ids"], json!([ids[0].0, ids[1].0, ids[2].0])); + assert!(anchors(&s, ids[1]) < 16 && anchors(&s, ids[2]) < 16); + assert_eq!(undo_steps(&s), steps + 1); +} + +/// A path of 16 anchors at (`x`, `y`): an ellipse with anchors added twice. +fn ellipse16(s: &mut Session, x: f64, y: f64) -> NodeId { + let e = id_of(&s.execute("shape.ellipse", &json!({"x": x, "y": y, "width": 50, "height": 50})).unwrap()); + select(s, &[e]); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + e +} + +/// Simplify Anchors takes the locked and hidden paths `ids` names, those in the locked or hidden +/// groups and layers it names (their locked and hidden members too) and a hidden compound path's +/// member, as one undo step, without selecting them; from the selection it leaves them alone, and a +/// path on a locked artboard stays even when named. +#[test] +fn simplify_named_locked_and_hidden_paths() { + let mut s = session(); + let locked = ellipse16(&mut s, 10.0, 10.0); + let hidden = ellipse16(&mut s, 70.0, 10.0); + change(&mut s, locked, |n| n.locked = true); + change(&mut s, hidden, |n| n.visible = false); + // A locked group with a hidden member, and a hidden group with a locked member. + let in_locked = ellipse16(&mut s, 130.0, 10.0); + let locked_group = wrap(&mut s, in_locked, |c| NodeKind::Group { children: c, clip: false }); + change(&mut s, locked_group, |n| n.locked = true); + change(&mut s, in_locked, |n| n.visible = false); + let in_hidden = ellipse16(&mut s, 190.0, 10.0); + let hidden_group = wrap(&mut s, in_hidden, |c| NodeKind::Group { children: c, clip: false }); + change(&mut s, hidden_group, |n| n.visible = false); + change(&mut s, in_hidden, |n| n.locked = true); + // A member of a hidden compound path. + let member = ellipse16(&mut s, 250.0, 10.0); + let compound = wrap(&mut s, member, |c| NodeKind::Compound { children: c, rule: FillRule::NonZero }); + change(&mut s, compound, |n| n.visible = false); + // A path in a locked layer, named itself. + let layer = id_of(&s.execute("layer.new", &json!({})).unwrap()); + let in_layer = ellipse16(&mut s, 10.0, 100.0); + let on_board = ellipse16(&mut s, 10.0, 200.0); + change(&mut s, layer, |n| n.locked = true); + let all = [locked, hidden, in_locked, in_hidden, member, in_layer]; + select(&mut s, &[locked, hidden, locked_group, hidden_group, compound]); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.simplify", &json!({})).unwrap(); + assert_eq!(r["ids"], json!([]), "from the selection, none is taken"); + assert_eq!(undo_steps(&s), steps); + assert!(all.iter().all(|id| anchors(&s, *id) == 16)); + select(&mut s, &[]); + s.edit("Select Anchors", |_, sel| { + sel.anchors.insert(locked, [(0, 1)].into()); + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.simplify", &json!({"ids": [locked.0, hidden.0, locked_group.0, hidden_group.0, member.0, in_layer.0]})).unwrap(); + assert_eq!(r["ids"], json!(all.iter().map(|i| i.0).collect::>())); + assert_eq!(r["before"], 16 * 6); + assert_eq!(r["after"].as_u64(), Some(all.iter().map(|id| anchors(&s, *id) as u64).sum::())); + assert!(all.iter().all(|id| anchors(&s, *id) < 16), "{r}"); + assert_eq!(undo_steps(&s), steps + 1); + let sel = &s.doc().unwrap().selection; + assert!(sel.objects.is_empty() && sel.anchors.is_empty(), "nothing is selected, and the changed path's anchors are not"); + let n = node(&s, in_hidden).unwrap(); + assert!(n.locked && n.visible && !node(&s, hidden_group).unwrap().visible); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(all.iter().all(|id| anchors(&s, *id) == 16)); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(all.iter().all(|id| anchors(&s, *id) < 16)); + // Nothing left to remove: no undo step. + let steps = undo_steps(&s); + s.execute("addon.cleanup.simplify", &json!({"ids": [locked.0]})).unwrap(); + assert_eq!(undo_steps(&s), steps); + // On a locked artboard, a named path stays as it is. + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.simplify", &json!({"ids": [on_board.0]})).unwrap(); + assert_eq!((r["ids"].clone(), anchors(&s, on_board), undo_steps(&s)), (json!([]), 16, steps)); } /// Each kind: what makes the issue in a fresh document (beside a clean rectangle). @@ -610,14 +692,15 @@ fn deep_ungroup_keeps_hidden_art_hidden_and_locked_art_locked() { assert!(!d.node(hidden).unwrap().visible && d.node(b).unwrap().visible); assert!(d.node(locked).unwrap().locked && d.node(e).unwrap().locked); assert_eq!(s.doc().unwrap().selection.objects, [a]); - // Named by `ids`, a locked group stays as it is, with no undo step. + // Named by `ids`, a locked group is taken apart as one undo step; its member becomes locked + // and is not selected. let steps = undo_steps(&s); let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [locked.0]})).unwrap(); - assert_eq!(r["ungrouped"], 0); - assert!(node(&s, locked).is_some()); - assert_eq!(undo_steps(&s), steps); + assert_eq!(r["ungrouped"], 1); + assert!(node(&s, locked).is_none() && node(&s, c).unwrap().locked); + assert_eq!(undo_steps(&s), steps + 1); + assert_eq!(r["ids"], json!([])); // With nothing ungrouped, the selection stays and the reply lists it. - assert_eq!(r["ids"], json!([a.0])); let f = rect(&mut s, 130.0, 10.0, 20.0, 20.0); select(&mut s, &[a]); let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [f.0]})).unwrap(); @@ -625,6 +708,108 @@ fn deep_ungroup_keeps_hidden_art_hidden_and_locked_art_locked() { assert_eq!(s.doc().unwrap().selection.objects, [a]); } +/// Put `ids` inside a new container that `kind` makes of its members. +fn wrap_all(s: &mut Session, ids: &[NodeId], kind: fn(Vec>) -> NodeKind) -> NodeId { + s.edit("t", |d, _| { + let w = d.alloc_id(); + Ok(d.wrap(ids, |c| Node::new(w, kind(c)))?) + }) + .unwrap() +} + +fn plain_group(c: Vec>) -> NodeKind { + NodeKind::Group { children: c, clip: false } +} + +fn sublayer(c: Vec>) -> NodeKind { + NodeKind::Layer { color: LayerColor::Preset(0), template: false, printable: true, children: c, clip: false, preview: true, dim_images: None } +} + +/// Named by `ids`, Deep Ungroup takes apart locked and hidden groups, those nested in a group it +/// names and those in a layer it names (its sublayers included, the layer staying), as one undo +/// step; their members become locked or hidden as the groups were, keep the groups' opacity and are +/// not selected. From the selection those groups stay whole, as do a clipping group and a group on a +/// locked artboard even when named. +#[test] +fn deep_ungroup_named_locked_and_hidden_groups() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + let b = rect(&mut s, 40.0, 10.0, 20.0, 20.0); + let locked = wrap_all(&mut s, &[a], plain_group); + let hidden = wrap_all(&mut s, &[b], plain_group); + change(&mut s, locked, |n| n.locked = true); + change(&mut s, hidden, |n| { + n.visible = false; + n.opacity = 0.5; + }); + select(&mut s, &[locked, hidden]); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.deepUngroup", &json!({})).unwrap(); + assert_eq!((r["ungrouped"].clone(), undo_steps(&s)), (json!(0), steps), "from the selection, they stay whole"); + assert!(node(&s, locked).is_some() && node(&s, hidden).is_some()); + let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [locked.0, hidden.0]})).unwrap(); + assert_eq!((r["ungrouped"].clone(), r["ids"].clone()), (json!(2), json!([]))); + assert_eq!(undo_steps(&s), steps + 1); + assert!(node(&s, locked).is_none() && node(&s, hidden).is_none()); + let (na, nb) = (node(&s, a).unwrap(), node(&s, b).unwrap()); + assert!(na.locked && na.visible && !nb.visible && !nb.locked); + assert_eq!(nb.opacity, 0.5); + assert!(s.doc().unwrap().selection.objects.is_empty()); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(node(&s, locked).is_some() && !node(&s, a).unwrap().locked && node(&s, b).unwrap().visible); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(node(&s, locked).is_none() && node(&s, a).unwrap().locked); + // Locked and hidden groups nested in a named group that can be edited. + let c = rect(&mut s, 70.0, 10.0, 20.0, 20.0); + let e = rect(&mut s, 100.0, 10.0, 20.0, 20.0); + let f = rect(&mut s, 130.0, 10.0, 20.0, 20.0); + let inner_locked = wrap_all(&mut s, &[e], plain_group); + let inner_hidden = wrap_all(&mut s, &[f], plain_group); + change(&mut s, inner_locked, |n| n.locked = true); + change(&mut s, inner_hidden, |n| n.visible = false); + let outer = wrap_all(&mut s, &[c, inner_locked, inner_hidden], plain_group); + let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [outer.0]})).unwrap(); + assert_eq!((r["ungrouped"].clone(), r["ids"].clone()), (json!(3), json!([c.0]))); + assert!(node(&s, e).unwrap().locked && !node(&s, f).unwrap().visible); + assert_eq!(s.doc().unwrap().selection.objects, [c]); + // In a named layer and its sublayer; the layers and a clipping group stay. + let layer = id_of(&s.execute("layer.new", &json!({})).unwrap()); + let g = rect(&mut s, 10.0, 100.0, 20.0, 20.0); + let h = rect(&mut s, 40.0, 100.0, 20.0, 20.0); + let layer_locked = wrap_all(&mut s, &[g], plain_group); + change(&mut s, layer_locked, |n| n.locked = true); + let layer_hidden = wrap_all(&mut s, &[h], plain_group); + change(&mut s, layer_hidden, |n| n.visible = false); + let sub = wrap_all(&mut s, &[layer_hidden], sublayer); + let clipped = rect(&mut s, 100.0, 100.0, 10.0, 10.0); + let clip = rect(&mut s, 95.0, 95.0, 30.0, 30.0); + select(&mut s, &[clipped, clip]); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let clip_group = s.doc().unwrap().selection.objects[0]; + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [layer.0]})).unwrap(); + assert_eq!((r["ungrouped"].clone(), undo_steps(&s)), (json!(2), steps + 1)); + assert!(node(&s, layer_locked).is_none() && node(&s, layer_hidden).is_none()); + assert!(node(&s, layer).is_some() && node(&s, clip_group).is_some()); + assert!(node(&s, g).unwrap().locked && !node(&s, h).unwrap().visible); + assert_eq!(s.doc().unwrap().doc.parent_of(h), Some(sub)); + // On a locked artboard, a named group stays whole, with the selection as it was. + let k = rect(&mut s, 10.0, 200.0, 20.0, 20.0); + let on_board = wrap_all(&mut s, &[k], plain_group); + let off_board = rect(&mut s, 500.0, 10.0, 20.0, 20.0); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + select(&mut s, &[off_board]); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [on_board.0]})).unwrap(); + assert_eq!((r["ungrouped"].clone(), r["ids"].clone(), undo_steps(&s)), (json!(0), json!([off_board.0]), steps)); + assert!(node(&s, on_board).is_some()); + assert_eq!(s.doc().unwrap().selection.objects, [off_board]); +} + #[test] fn rejoin_joins_pieces_within_the_gap_only() { let mut s = session(); @@ -646,3 +831,74 @@ fn rejoin_joins_pieces_within_the_gap_only() { assert!(s.execute("addon.cleanup.rejoin", &bad).is_err(), "{bad}"); } } + +/// Named by `ids`, Rejoin Path Pieces takes locked and hidden pieces (in a locked group or layer +/// too) and joins only pieces alike in being hidden and in being locked, whichever is topmost, as one +/// undo step; a locked or hidden path it makes is not selected. From the selection it takes only +/// pieces that can be edited, and compound path members and pieces on a locked artboard stay out. +#[test] +fn rejoin_named_locked_and_hidden_pieces() { + let mut s = session(); + let a = line(&mut s, &[(10.0, 10.0), (50.0, 10.0)]); + let b = line(&mut s, &[(50.05, 10.0), (90.0, 10.0)]); + let g = wrap_all(&mut s, &[a, b], plain_group); + change(&mut s, g, |n| n.locked = true); + select(&mut s, &[g]); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.rejoin", &json!({})).unwrap(); + assert_eq!((r["joined"].clone(), undo_steps(&s)), (json!(0), steps), "from the selection, none is taken"); + let r = s.execute("addon.cleanup.rejoin", &json!({"ids": [g.0]})).unwrap(); + assert_eq!((r["joined"].clone(), r["removed"].clone(), r["ids"].clone()), (json!(1), json!(1), json!([b.0]))); + assert_eq!(undo_steps(&s), steps + 1); + assert!(node(&s, a).is_none() && anchors(&s, b) == 3); + assert!(s.doc().unwrap().selection.objects.is_empty(), "the locked path is not selected"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(node(&s, a).is_some() && anchors(&s, b) == 2); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(node(&s, a).is_none() && anchors(&s, b) == 3); + // A shown piece and two hidden ones, the hidden on top: only the hidden pair joins. + let c = line(&mut s, &[(10.0, 40.0), (50.0, 40.0)]); + let e = line(&mut s, &[(50.05, 40.0), (90.0, 40.0)]); + let h = line(&mut s, &[(90.05, 40.0), (130.0, 40.0)]); + change(&mut s, e, |n| n.visible = false); + change(&mut s, h, |n| n.visible = false); + let r = s.execute("addon.cleanup.rejoin", &json!({"ids": [c.0, e.0, h.0]})).unwrap(); + assert_eq!((r["joined"].clone(), r["removed"].clone(), r["ids"].clone()), (json!(1), json!(1), json!([h.0]))); + assert!(node(&s, e).is_none() && anchors(&s, c) == 2 && anchors(&s, h) == 3); + assert!(!node(&s, h).unwrap().visible && node(&s, c).unwrap().visible); + assert!(s.doc().unwrap().selection.objects.is_empty(), "the hidden path is not selected"); + // An unlocked piece under a locked one, and a hidden piece under a shown one: none joins. + let k = line(&mut s, &[(10.0, 70.0), (50.0, 70.0)]); + let m = line(&mut s, &[(50.05, 70.0), (90.0, 70.0)]); + let n = line(&mut s, &[(10.0, 100.0), (50.0, 100.0)]); + let o = line(&mut s, &[(50.05, 100.0), (90.0, 100.0)]); + change(&mut s, m, |x| x.locked = true); + change(&mut s, n, |x| x.visible = false); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.rejoin", &json!({"ids": [k.0, m.0, n.0, o.0]})).unwrap(); + assert_eq!((r["joined"].clone(), r["removed"].clone(), undo_steps(&s)), (json!(0), json!(0), steps)); + assert!([k, m, n, o].iter().all(|id| anchors(&s, *id) == 2)); + // Named pieces in a locked layer join; members of a compound path stay out. + let layer = id_of(&s.execute("layer.new", &json!({})).unwrap()); + let p = line(&mut s, &[(10.0, 130.0), (50.0, 130.0)]); + let q = line(&mut s, &[(50.05, 130.0), (90.0, 130.0)]); + let u = line(&mut s, &[(10.0, 160.0), (50.0, 160.0)]); + let v = line(&mut s, &[(50.05, 160.0), (90.0, 160.0)]); + wrap_all(&mut s, &[u, v], |c| NodeKind::Compound { children: c, rule: FillRule::NonZero }); + let w = line(&mut s, &[(10.0, 200.0), (50.0, 200.0)]); + let x = line(&mut s, &[(50.05, 200.0), (90.0, 200.0)]); + change(&mut s, layer, |l| l.locked = true); + let r = s.execute("addon.cleanup.rejoin", &json!({"ids": [p.0, q.0, u.0, v.0]})).unwrap(); + assert_eq!((r["joined"].clone(), r["ids"].clone()), (json!(1), json!([q.0]))); + assert!(node(&s, p).is_none() && anchors(&s, u) == 2 && anchors(&s, v) == 2); + // On a locked artboard, named pieces stay as they are. + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.rejoin", &json!({"ids": [w.0, x.0]})).unwrap(); + assert_eq!((r["joined"].clone(), undo_steps(&s)), (json!(0), steps)); + assert!(node(&s, w).is_some() && node(&s, x).is_some()); +} diff --git a/crates/engine/src/cmd/addons/cleanup/text.rs b/crates/engine/src/cmd/addons/cleanup/text.rs index 052ba901ed..ea7e3314bb 100644 --- a/crates/engine/src/cmd/addons/cleanup/text.rs +++ b/crates/engine/src/cmd/addons/cleanup/text.rs @@ -45,7 +45,7 @@ pub fn specs() -> Vec { "Break Text", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{by?: \"lines\"|\"paragraphs\"|\"words\"|\"glyphs\" (lines), ids?: [id…] (default: the selection)} each horizontal point or area type object becomes point type objects, one per line, paragraph, word or glyph, each where its characters were and with their character styles, as one undo step; spaces between pieces go, a paragraph's lines stay lines (a wrapped line ends in a line break), justified lines close up, and a paragraph broken out whole keeps its bullet (not its number; other pieces have no list markers). Type on a path, vertical type, threaded type and area type whose text doesn't fit stay as they are → {ids (the pieces, selected), skipped}", + "{by?: \"lines\"|\"paragraphs\"|\"words\"|\"glyphs\" (lines), ids?: [id…] (default: the selection; the type they name is taken locked or hidden too)} each horizontal point or area type object becomes point type objects, one per line, paragraph, word or glyph, each where its characters were and with their character styles, as one undo step; spaces between pieces go, a paragraph's lines stay lines (a wrapped line ends in a line break), justified lines close up, and a paragraph broken out whole keeps its bullet (not its number; other pieces have no list markers). Type on a path, vertical type, threaded type and area type whose text doesn't fit stay as they are → {ids (the pieces, selected), skipped}", has_selection, break_text ), @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Combine Point Text", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{ids?: [id…] (default: the selection)} merge one-line horizontal point type into as few objects as it can, every glyph staying where it was: pieces turned and sheared alike whose baselines line up (within 0.4 em; the difference becomes baseline shift) join left to right, a space goes between pieces at least half a space apart, and tracking on the character before each piece keeps the spacing; each object keeps its character styles, and the leftmost piece of each run its place and paint, as one undo step → {ids (the objects made, selected), combined (pieces merged into them)}", + "{ids?: [id…] (default: the selection; the type they name is taken locked or hidden too)} merge one-line horizontal point type into as few objects as it can, every glyph staying where it was: pieces turned and sheared alike, as visible and as locked (their groups and layers included), whose baselines line up (within 0.4 em; the difference becomes baseline shift) join left to right, a space goes between pieces at least half a space apart, and tracking on the character before each piece keeps the spacing; each object keeps its character styles, and the leftmost piece of each run its place and paint, as one undo step → {ids (the objects made, selected), combined (pieces merged into them)}", has_selection, combine_text ), @@ -63,7 +63,7 @@ pub fn specs() -> Vec { "Join Point Text", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{ids?: [id…] (default: the selection)} join one-line horizontal point type into one point type object, as one undo step: pieces turned and sheared like the top-left one are read as lines (baselines within 0.4 em of each other), top to bottom, each line's pieces left to right with a space between them; each line becomes a paragraph, left aligned, and keeps the distance between baselines as its leading. The text keeps its character styles; the object takes the top-left piece's place and paint, and the other pieces go → {id (selected), joined (pieces merged into it), lines}", + "{ids?: [id…] (default: the selection; the type they name is taken locked or hidden too)} join one-line horizontal point type into one point type object, as one undo step: pieces turned and sheared like the top-left one, and as visible and as locked (their groups and layers included), are read as lines (baselines within 0.4 em of each other), top to bottom, each line's pieces left to right with a space between them; each line becomes a paragraph, left aligned, and keeps the distance between baselines as its leading. The text keeps its character styles; the object takes the top-left piece's place and paint, and the other pieces go → {id (selected), joined (pieces merged into it), lines}", has_selection, join_text ), @@ -72,7 +72,7 @@ pub fn specs() -> Vec { "Remove Breaks", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{kind: \"line\"|\"paragraph\", ids?: [id…]} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool (after Select All in a frame of threaded text, in the text of every frame of the story), else in all the text of the selected type, as one undo step; a break between two words becomes a space, the frames of a threaded story selected all together being read as one text → {ids, removed}", + "{kind: \"line\"|\"paragraph\", ids?: [id…] (the type they name is taken locked or hidden too)} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool (after Select All in a frame of threaded text, in the text of every frame of the story, locked and hidden frames included), else in all the text of the selected type, as one undo step; a break between two words becomes a space, the frames of a threaded story selected all together being read as one text → {ids, removed}", has_selection, remove_breaks ), @@ -90,7 +90,7 @@ pub fn specs() -> Vec { "Set Alignment, Keep Position", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{align: \"left\"|\"center\"|\"right\", ids?: [id…] (default: the selection)} align every paragraph of each horizontal point type object so, moving the object so its longest line stays where it is (one line: the text doesn't move), as one undo step → {ids (the objects changed)}", + "{align: \"left\"|\"center\"|\"right\", ids?: [id…] (default: the selection; the type they name is taken locked or hidden too)} align every paragraph of each horizontal point type object so, moving the object so its longest line stays where it is (one line: the text doesn't move), as one undo step → {ids (the objects changed)}", has_selection, align_in_place ), @@ -99,7 +99,7 @@ pub fn specs() -> Vec { "Reset Text Transform", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{scale?: bool (false: the horizontal scale stays; true: it goes too, the object's and every character's), ids?: [id…] (default: the selection)} take the rotation, shear and reflection off each point type object, its size and the centre of its text staying, as one undo step → {ids (the objects changed)}", + "{scale?: bool (false: the horizontal scale stays; true: it goes too, the object's and every character's), ids?: [id…] (default: the selection; the type they name is taken locked or hidden too)} take the rotation, shear and reflection off each point type object, its size and the centre of its text staying, as one undo step → {ids (the objects changed)}", has_selection, reset_transform ), @@ -123,8 +123,17 @@ fn editing_text(s: &Session) -> std::result::Result<(), String> { } } -/// The type objects under `roots` (inside groups and layers, not live art) that can be edited. -fn texts_under(d: &Document, roots: &[NodeId]) -> Result> { +/// The type objects a command acts on: those under the objects `ids` names, locked and hidden ones +/// included, else those under the selection that can be edited ([`texts_under`]). +fn target_texts(s: &Session, p: &Value, command: &str) -> Result> { + let named = p.get("ids").is_some_and(|v| !v.is_null()); + texts_under(&s.doc()?.doc, &checked_ids_or_selection(s, p, command)?, named) +} + +/// The type objects under `roots` (inside groups and layers, not live art). When `named`, every one +/// not on a locked artboard, locked and hidden ones (and ones in a locked or hidden group or layer) +/// included; else only those that can be edited. +fn texts_under(d: &Document, roots: &[NodeId], named: bool) -> Result> { fn visit(n: &Node, out: &mut Vec) { match &n.kind { NodeKind::Text(_) => out.push(n.id), @@ -134,8 +143,13 @@ fn texts_under(d: &Document, roots: &[NodeId]) -> Result> { } let mut out = vec![]; roots.iter().filter_map(|id| d.node(*id)).for_each(|n| visit(n, &mut out)); - let editable = d.editable(); - out.retain(|id| editable(*id)); + if named { + let locks = d.locked_artboards(); + out.retain(|id| !locks.holds_id(*id)); + } else { + let editable = d.editable(); + out.retain(|id| editable(*id)); + } out.dedup(); if out.len() > MAX_TEXTS { return Err(EngineError::Other("Too many type objects to change at once".into())); @@ -376,7 +390,9 @@ fn replace_with_pieces(s: &mut Session, label: &str, items: Vec<(NodeId, Node, V places.push((id, nodes)); } d.insert_beside(places, true)?; - sel.set(made.iter().copied()); + // Pieces of locked or hidden type stay unselected. + let editable = d.editable(); + sel.set(made.iter().copied().filter(|id| editable(*id))); Ok(made.iter().map(|i| i.0).collect()) }) } @@ -396,7 +412,7 @@ fn break_text(s: &mut Session, p: &Value) -> Result { }; let d = &s.doc()?.doc; let (mut items, mut skipped, mut count) = (vec![], vec![], 0); - let ids = texts_under(d, &checked_ids_or_selection(s, p, C)?)?; + let ids = target_texts(s, p, C)?; let threads = thread_index(d); for id in ids { let (Some(src), Some(node)) = (Source::of(d, id, threads.contains_key(&id)), d.node(id)) else { @@ -450,6 +466,9 @@ fn split_text(s: &mut Session, _: &Value) -> Result { struct Piece { id: NodeId, t: TextObject, + /// Whether the object and every group and layer above it are visible, and whether they are all + /// unlocked. + state: (bool, bool), /// The object's turn and shear (`xf` without its move). turn: [f64; 4], /// Where its first character's glyph starts on its baseline, in that frame. @@ -487,13 +506,19 @@ impl Piece { if !(at.x.is_finite() && at.y.is_finite() && size > 0.0) { return None; } - Some((Self { id, t, turn: [a, b, c, dd], at, end: at.x + end, size, pens }, node)) + let state = d.ancestry(id)?.iter().filter_map(|i| d.node(*i)).fold((true, true), |(v, u), n| (v && n.visible, u && !n.locked)); + Some((Self { id, t, state, turn: [a, b, c, dd], at, end: at.x + end, size, pens }, node)) } /// Whether `o` is turned and sheared alike. fn turned_like(&self, o: &Piece) -> bool { self.turn.iter().zip(&o.turn).all(|(x, y)| (x - y).abs() <= 1e-6 * x.abs().max(y.abs()).max(1.0)) } + + /// Whether `o` is turned and sheared alike and has the same `state`. + fn joins(&self, o: &Piece) -> bool { + self.turned_like(o) && self.state == o.state + } } /// Whether two objects look alike apart from their text (paint, opacity, blending, effects). @@ -595,15 +620,14 @@ fn merge(chain: &[&Piece]) -> std::result::Result { fn combine_text(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.cleanup.combineText"; let d = &s.doc()?.doc; - let mut pieces: Vec<(Piece, &Node)> = - texts_under(d, &checked_ids_or_selection(s, p, C)?)?.into_iter().filter_map(|id| Piece::of(d, id)).collect(); - // Lines: pieces turned alike and looking alike, by baseline, then left to right. + let mut pieces: Vec<(Piece, &Node)> = target_texts(s, p, C)?.into_iter().filter_map(|id| Piece::of(d, id)).collect(); + // Lines: pieces turned alike, as visible and as locked and looking alike, by baseline, then left + // to right. pieces.sort_by(|x, y| x.0.at.y.total_cmp(&y.0.at.y).then(x.0.at.x.total_cmp(&y.0.at.x))); let mut lines: Vec> = vec![]; for (piece, node) in &pieces { let fits = |l: &Vec<(&Piece, &Node)>| { - l.first() - .is_some_and(|(f, n)| f.turned_like(piece) && same_look(n, node) && (f.at.y - piece.at.y).abs() <= SAME_LINE * f.size.min(piece.size)) + l.first().is_some_and(|(f, n)| f.joins(piece) && same_look(n, node) && (f.at.y - piece.at.y).abs() <= SAME_LINE * f.size.min(piece.size)) }; match lines.iter_mut().find(|l| fits(l)) { Some(l) => l.push((piece, node)), @@ -672,7 +696,8 @@ fn combine_text(s: &mut Session, p: &Value) -> Result { gone.extend(others); } d.remove_many(&gone)?; - sel.set(ids.iter().map(|i| NodeId(*i))); + let editable = d.editable(); + sel.set(ids.iter().map(|i| NodeId(*i)).filter(|id| editable(*id))); Ok(()) })?; Ok(json!({ "ids": ids, "combined": combined })) @@ -681,15 +706,15 @@ fn combine_text(s: &mut Session, p: &Value) -> Result { fn join_text(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.cleanup.joinText"; let d = &s.doc()?.doc; - let pieces: Vec = - texts_under(d, &checked_ids_or_selection(s, p, C)?)?.into_iter().filter_map(|id| Piece::of(d, id).map(|p| p.0)).collect(); - // The piece top-left on the page sets the turn; the others turned like it are read in that frame. + let pieces: Vec = target_texts(s, p, C)?.into_iter().filter_map(|id| Piece::of(d, id).map(|p| p.0)).collect(); + // The piece top-left on the page sets the turn; the others turned like it, and as visible and as + // locked, are read in that frame. let on_page = |p: &Piece| Affine::new([p.turn[0], p.turn[1], p.turn[2], p.turn[3], 0.0, 0.0]) * p.at; let first = pieces.iter().min_by(|x, y| { let (a, b) = (on_page(x), on_page(y)); a.y.total_cmp(&b.y).then(a.x.total_cmp(&b.x)) }); - let mut kept: Vec<&Piece> = first.map(|f| pieces.iter().filter(|p| p.turned_like(f)).collect()).unwrap_or_default(); + let mut kept: Vec<&Piece> = first.map(|f| pieces.iter().filter(|p| f.joins(p)).collect()).unwrap_or_default(); kept.sort_by(|x, y| x.at.y.total_cmp(&y.at.y).then(x.at.x.total_cmp(&y.at.x))); // Lines, top to bottom, by baseline; each line's pieces left to right. let mut lines: Vec> = vec![]; @@ -751,7 +776,7 @@ fn join_text(s: &mut Session, p: &Value) -> Result { n.kind = NodeKind::Text(Box::new(m)); } d.remove_many(&gone)?; - sel.set([id]); + sel.set([id].into_iter().filter(|id| d.is_editable(*id))); Ok(()) })?; Ok(json!({ "id": id.0, "joined": joined, "lines": count })) @@ -796,8 +821,8 @@ fn apply_cuts(t: &mut TextObject, cuts: &[(usize, bool)], brk: char) -> usize { } /// The breaks `brk` in the text of the frames of `story`, read as one text: a break at the end or -/// start of a frame between words of the frames on either side becomes a space. Each editable frame -/// comes with its own breaks, at its own bytes. +/// start of a frame between words of the frames on either side becomes a space. Each frame comes +/// with its own breaks, at its own bytes, its locked and hidden frames included. fn story_cuts(d: &Document, story: &[NodeId], brk: char) -> Vec<(NodeId, Vec<(usize, bool)>)> { let texts: Vec<(NodeId, String)> = story.iter().filter_map(|id| Some((*id, text_of(d, *id)?.plain_text()))).collect(); let joined: String = texts.iter().map(|(_, t)| t.as_str()).collect(); @@ -811,9 +836,7 @@ fn story_cuts(d: &Document, story: &[NodeId], brk: char) -> Vec<(NodeId, Vec<(us while let Some((at, space)) = cuts.next_if(|(at, _)| *at < end) { own.push((at - start, space)); } - if d.is_editable(id) { - out.push((id, own)); - } + out.push((id, own)); start = end; } out @@ -841,24 +864,30 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result { .filter_map(|(id, a, b)| Some((id, break_cuts(&text_of(d, id)?.plain_text(), a, b, brk)))) .collect(), None => { - let ids = texts_under(d, &checked_ids_or_selection(s, p, C)?)?; + let ids = target_texts(s, p, C)?; // A threaded story whose frames are all among them is read as one text, once. let named: std::collections::HashSet = ids.iter().copied().collect(); let threads = thread_index(d); let mut done = std::collections::HashSet::new(); + // The threads already found not to be a story whose frames are all among them: their + // other frames are read one at a time without going through the thread again. + let mut partial = std::collections::HashSet::new(); let mut out: Vec<(NodeId, Vec<(usize, bool)>)> = vec![]; for &id in &ids { if !done.insert(id) { continue; } - let story = match threads.get(&id).and_then(|&i| d.text_threads.get(i)) { - Some(thread) => crate::cmd::threads::story_in(d, thread, id), + let thread = threads.get(&id).copied(); + let story = match thread.filter(|i| !partial.contains(i)).and_then(|i| d.text_threads.get(i)) { + Some(frames) => crate::cmd::threads::story_in(d, frames, id), None => vec![], }; if !story.is_empty() && story.iter().all(|f| named.contains(f)) { done.extend(story.iter().copied()); out.extend(story_cuts(d, &story, brk)); } else if let Some(t) = text_of(d, id) { + // `id` is type, so the story of its thread is the same for each of its frames. + partial.extend(thread); out.push((id, break_cuts(&t.plain_text(), 0, usize::MAX, brk))); } } @@ -891,10 +920,8 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result { /// Horizontal point type among the objects `p` names. fn point_texts(s: &Session, p: &Value, cmd: &str) -> Result> { let d = &s.doc()?.doc; - let ids: Vec = texts_under(d, &checked_ids_or_selection(s, p, cmd)?)? - .into_iter() - .filter(|id| text_of(d, *id).is_some_and(|t| matches!(t.kind, TextKind::Point))) - .collect(); + let ids: Vec = + target_texts(s, p, cmd)?.into_iter().filter(|id| text_of(d, *id).is_some_and(|t| matches!(t.kind, TextKind::Point))).collect(); if ids.is_empty() { return Err(EngineError::Other("Select point type".into())); } diff --git a/crates/engine/src/cmd/addons/cleanup/text/tests.rs b/crates/engine/src/cmd/addons/cleanup/text/tests.rs index cfa78a5ce5..9671bb3306 100644 --- a/crates/engine/src/cmd/addons/cleanup/text/tests.rs +++ b/crates/engine/src/cmd/addons/cleanup/text/tests.rs @@ -379,6 +379,228 @@ fn remove_breaks_reads_the_threads_once() { } } +/// Remove Breaks reads each named frame of a story that is not all named on its own, in the order +/// named and each once, as one undo step, and goes through that story's frames once for all of them. +#[test] +fn remove_breaks_goes_through_a_partly_named_story_once() { + for (kind, brk) in [("line", '\u{2028}'), ("paragraph", '\n')] { + let mut s = session(); + let a = text(&mut s, json!({"x": 10, "y": 20, "text": "a\u{2028}b\n".repeat(40), "size": 12, "area": {"width": 150, "height": 60}})); + let mut roots = vec![a]; + for i in 0..4 { + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 100 + 70 * i, "width": 150, "height": 60})).unwrap(); + roots.push(NodeId(r["id"].as_u64().unwrap())); + } + select(&mut s, &roots); + s.execute("text.thread.create", &json!({})).unwrap(); + let f = s.doc().unwrap().doc.text_threads[0].clone(); + assert_eq!(f.len(), 5); + let named = [f[4], f[1], f[3]]; + let breaks: Vec = named.iter().map(|id| obj(&s, *id).plain_text().matches(brk).count()).collect(); + assert!(breaks.iter().all(|n| *n > 0), "{kind}: each named frame holds breaks: {breaks:?}"); + let before = doc_json(&s); + let steps = undo_steps(&s); + let builds = crate::cmd::threads::story_builds(); + let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": kind, "ids": [f[4].0, f[1].0, f[4].0, f[3].0]})).unwrap(); + assert_eq!(crate::cmd::threads::story_builds() - builds, 1, "{kind}: the story's frames are gone through once"); + assert_eq!(r["removed"].as_u64(), Some(breaks.iter().sum::() as u64), "{kind}"); + assert_eq!(ids(&r), named, "{kind}"); + assert_eq!(undo_steps(&s), steps + 1, "{kind}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(doc_json(&s), before, "{kind}"); + } +} + +/// Lock `id` (`locked`), else hide it, as an undo step of its own. +fn lock_or_hide(s: &mut Session, id: NodeId, locked: bool) { + s.edit("Lock or Hide", |d, _| { + let n = d.node_mut(id).unwrap(); + if locked { + n.locked = true; + } else { + n.visible = false; + } + Ok(()) + }) + .unwrap(); +} + +/// Remove Breaks takes the locked and hidden type that `ids` names, and the locked member of a +/// group it names, as one undo step; from the selection it takes only type that can be edited, and +/// nothing changed makes no undo step. +#[test] +fn remove_breaks_named_locked_and_hidden_type() { + let mut s = session(); + let locked = text(&mut s, json!({"x": 40, "y": 60, "text": "a\nb", "size": 12})); + let hidden = text(&mut s, json!({"x": 40, "y": 120, "text": "c\nd", "size": 12})); + let grouped = text(&mut s, json!({"x": 40, "y": 180, "text": "e\nf", "size": 12})); + let free = text(&mut s, json!({"x": 40, "y": 240, "text": "g\nh", "size": 12})); + select(&mut s, &[grouped, free]); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + lock_or_hide(&mut s, locked, true); + lock_or_hide(&mut s, hidden, false); + lock_or_hide(&mut s, grouped, true); + select(&mut s, &[locked, hidden]); + let steps = undo_steps(&s); + assert_eq!(other(s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"}))), "No paragraph breaks to remove"); + assert_eq!(undo_steps(&s), steps, "the selected locked and hidden type stays as it is"); + let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph", "ids": [locked.0, hidden.0, group.0]})).unwrap(); + assert_eq!(undo_steps(&s), steps + 1); + assert_eq!(r["removed"], 4); + for (id, now) in [(locked, "a b"), (hidden, "c d"), (grouped, "e f"), (free, "g h")] { + assert_eq!(obj(&s, id).plain_text(), now); + } + assert_eq!(other(s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph", "ids": [locked.0]}))), "No paragraph breaks to remove"); + assert_eq!(undo_steps(&s), steps + 1, "nothing changed, no undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(obj(&s, locked).plain_text(), "a\nb"); +} + +/// A threaded story whose frames `ids` all names is read as one text even when a frame is locked. +#[test] +fn remove_breaks_named_story_with_a_locked_frame() { + let mut s = session(); + let (a, b) = threaded(&mut s, "one\ntwo"); + lock_or_hide(&mut s, a, true); + let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph", "ids": [a.0, b.0]})).unwrap(); + assert_eq!(r["removed"], 1); + assert_eq!(obj(&s, a).plain_text(), "one two"); +} + +/// Type on a locked artboard stays as it is even when `ids` names it, with no undo step. +#[test] +fn remove_breaks_named_type_on_a_locked_artboard() { + let mut s = session(); + let on_board = text(&mut s, json!({"x": 40, "y": 60, "text": "a\nb", "size": 12})); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph", "ids": [on_board.0]})); + assert_eq!(other(r), "No paragraph breaks to remove"); + assert_eq!(undo_steps(&s), steps); + assert_eq!(obj(&s, on_board).plain_text(), "a\nb"); +} + +/// Break Text, Combine and Join Point Text, Set Alignment, Keep Position and Reset Text Transform +/// act on the locked and hidden type that `ids` names (type in a locked layer included), each as +/// one undo step, and leave it as it is when it is only selected. +#[test] +fn named_locked_and_hidden_type() { + let mut s = session(); + let words = text(&mut s, json!({"x": 40, "y": 100, "text": "Two words", "size": 14})); + lock_or_hide(&mut s, words, true); + select(&mut s, &[words]); + assert!(s.execute("addon.cleanup.breakText", &json!({"by": "words"})).is_err()); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.breakText", &json!({"by": "words", "ids": [words.0]})).unwrap(); + assert_eq!((ids(&r).len(), undo_steps(&s)), (2, steps + 1)); + assert!(s.doc().unwrap().selection.objects.is_empty(), "the locked pieces stay unselected"); + + let mut s = session(); + let a = text(&mut s, json!({"x": 50, "y": 100, "text": "Left", "size": 20})); + let b = text(&mut s, json!({"x": 110, "y": 100, "text": "Right", "size": 20})); + lock_or_hide(&mut s, a, false); + lock_or_hide(&mut s, b, false); + select(&mut s, &[a, b]); + assert!(s.execute("addon.cleanup.combineText", &json!({})).is_err()); + let r = s.execute("addon.cleanup.combineText", &json!({"ids": [a.0, b.0]})).unwrap(); + assert_eq!(ids(&r), [a]); + assert_eq!(obj(&s, a).plain_text(), "Left Right"); + assert!(s.doc().unwrap().selection.objects.is_empty(), "the hidden object stays unselected"); + + let mut s = session(); + let first = text(&mut s, json!({"x": 50, "y": 100, "text": "First", "size": 20})); + let second = text(&mut s, json!({"x": 50, "y": 130, "text": "Second", "size": 20})); + let layer = s.doc().unwrap().doc.layers[0].id; + lock_or_hide(&mut s, layer, true); + select(&mut s, &[first, second]); + assert!(s.execute("addon.cleanup.joinText", &json!({})).is_err()); + let r = s.execute("addon.cleanup.joinText", &json!({"ids": [first.0, second.0]})).unwrap(); + assert_eq!(r["id"].as_u64(), Some(first.0)); + assert_eq!(obj(&s, first).plain_text(), "First\nSecond"); + assert!(s.doc().unwrap().selection.objects.is_empty(), "the object in the locked layer stays unselected"); + + let mut s = session(); + let lines = text(&mut s, json!({"x": 50, "y": 100, "text": "a\nlonger line", "size": 20})); + lock_or_hide(&mut s, lines, false); + select(&mut s, &[lines]); + assert!(s.execute("addon.cleanup.alignInPlace", &json!({"align": "center"})).is_err()); + s.execute("addon.cleanup.alignInPlace", &json!({"align": "center", "ids": [lines.0]})).unwrap(); + assert!(obj(&s, lines).para_styles().all(|p| p.justify == Justify::Center)); + + let mut s = session(); + let turned = text(&mut s, json!({"x": 300, "y": 200, "text": "Turned", "size": 18, "rotation": 30})); + lock_or_hide(&mut s, turned, true); + select(&mut s, &[turned]); + assert!(s.execute("addon.cleanup.resetTextTransform", &json!({})).is_err()); + let steps = undo_steps(&s); + s.execute("addon.cleanup.resetTextTransform", &json!({"ids": [turned.0]})).unwrap(); + assert_eq!(undo_steps(&s), steps + 1); + let [_, b, c, _, _, _] = obj(&s, turned).xf.as_coeffs(); + assert!(b.abs() < 1e-9 && c.abs() < 1e-9, "the rotation is gone"); +} + +/// Combine Point Text joins named pieces only with pieces as visible and as locked, a group's lock +/// included: a visible piece and a hidden one beside it, or a free piece and one in a locked group, +/// stay as they are, with no undo step. +#[test] +fn combine_keeps_hidden_and_locked_pieces_apart() { + let mut s = session(); + let a = text(&mut s, json!({"x": 50, "y": 100, "text": "Left", "size": 20})); + let b = text(&mut s, json!({"x": 110, "y": 100, "text": "Right", "size": 20})); + lock_or_hide(&mut s, b, false); + let steps = undo_steps(&s); + assert!(s.execute("addon.cleanup.combineText", &json!({"ids": [a.0, b.0]})).is_err()); + assert_eq!(undo_steps(&s), steps); + assert_eq!((obj(&s, a).plain_text(), obj(&s, b).plain_text()), ("Left".into(), "Right".into())); + let d = &s.doc().unwrap().doc; + assert!(d.is_visible(a) && !d.is_visible(b), "the visible text stays shown and the hidden text stays hidden"); + + let mut s = session(); + let a = text(&mut s, json!({"x": 50, "y": 100, "text": "Left", "size": 20})); + let b = text(&mut s, json!({"x": 110, "y": 100, "text": "Right", "size": 20})); + select(&mut s, &[b]); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + lock_or_hide(&mut s, group, true); + let steps = undo_steps(&s); + assert!(s.execute("addon.cleanup.combineText", &json!({"ids": [a.0, group.0]})).is_err()); + assert_eq!(undo_steps(&s), steps); + assert_eq!((obj(&s, a).plain_text(), obj(&s, b).plain_text()), ("Left".into(), "Right".into())); +} + +/// Join Point Text joins only the named pieces as visible and as locked as the top-left one: a +/// hidden piece between two visible lines stays as it is, hidden, and a hidden top-left piece +/// with only a visible one below it joins nothing, with no undo step. +#[test] +fn join_keeps_a_hidden_piece_apart() { + let mut s = session(); + let first = text(&mut s, json!({"x": 50, "y": 100, "text": "First", "size": 20})); + let hidden = text(&mut s, json!({"x": 50, "y": 130, "text": "Hidden", "size": 20})); + let third = text(&mut s, json!({"x": 50, "y": 160, "text": "Third", "size": 20})); + lock_or_hide(&mut s, hidden, false); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.joinText", &json!({"ids": [first.0, hidden.0, third.0]})).unwrap(); + assert_eq!((r["id"].as_u64(), r["joined"].as_u64(), undo_steps(&s)), (Some(first.0), Some(2), steps + 1)); + assert_eq!(obj(&s, first).plain_text(), "First\nThird"); + assert_eq!(obj(&s, hidden).plain_text(), "Hidden"); + let d = &s.doc().unwrap().doc; + assert!(d.is_visible(first) && !d.is_visible(hidden), "the visible text stays shown and the hidden text stays hidden"); + assert!(d.node(third).is_none()); + + let mut s = session(); + let top = text(&mut s, json!({"x": 50, "y": 100, "text": "Top", "size": 20})); + let below = text(&mut s, json!({"x": 50, "y": 130, "text": "Below", "size": 20})); + lock_or_hide(&mut s, top, false); + let steps = undo_steps(&s); + assert!(s.execute("addon.cleanup.joinText", &json!({"ids": [top.0, below.0]})).is_err()); + assert_eq!(undo_steps(&s), steps); + assert_eq!((obj(&s, top).plain_text(), obj(&s, below).plain_text()), ("Top".into(), "Below".into())); + assert!(s.doc().unwrap().doc.is_visible(below)); +} + #[test] fn split_at_the_cursor_and_around_a_selection() { for (anchor, caret, want) in [(6, 6, &["Split", "here please"][..]), (6, 10, &["Split", "here", "please"][..])] { diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index 2fe9c77a36..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 (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 (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 (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/cutting.rs b/crates/engine/src/cmd/addons/cutting.rs index 37e9f2fa79..6ad2af043b 100644 --- a/crates/engine/src/cmd/addons/cutting.rs +++ b/crates/engine/src/cmd/addons/cutting.rs @@ -2,9 +2,11 @@ //! Bridges cuts bridges out of the selected art so that a stencil cut from it holds together //! ([`stencil`]), and Weed Box and Lines adds a weed box and weeding lines around the selected art //! for vinyl cutting ([`weed`]). Banner Hems and Grommets marks the hems and grommets of a banner -//! ([`banner`]). Its submenu (Object › Plug-ins › Cutting Tools) and dialogs are the UI's. +//! ([`banner`]). Nest Shapes packs the selected art onto a sheet or a roll of material ([`nest`]). +//! Its submenu (Object › Plug-ins › Cutting Tools) and dialogs are the UI's. mod banner; +mod nest; mod stencil; mod weed; @@ -14,5 +16,6 @@ pub fn specs() -> Vec { let mut v = stencil::specs(); v.extend(weed::specs()); v.extend(banner::specs()); + v.extend(nest::specs()); v } diff --git a/crates/engine/src/cmd/addons/cutting/nest.rs b/crates/engine/src/cmd/addons/cutting/nest.rs new file mode 100644 index 0000000000..18d4dd70f2 --- /dev/null +++ b/crates/engine/src/cmd/addons/cutting/nest.rs @@ -0,0 +1,403 @@ +//! Nest Shapes (`addon.cutting.nest`), a command of the built-in Cutting Tools add-on that packs +//! the selected objects onto a sheet or a roll of material by their bounding boxes +//! (). The sheet is an +//! artboard, or a set size from the artboard's top-left corner; a roll is as wide as the sheet +//! and has no end. The objects are moved, and with `rotate` turned a quarter turn when that places +//! them better; they are never scaled or changed otherwise. + +#[cfg(test)] +mod tests; + +use std::collections::VecDeque; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Scaling}; +use vectorcraft_geom::{Affine, Point, Rect, Vec2}; +use vectorcraft_render::effects; + +use super::super::super::edit::selected_roots_to_transform; +use super::super::super::object::{keep_compound_aligned, transform_node, transform_patterns}; +use super::super::super::pathops::length_given; +use super::super::super::{CommandSpec, bad, check_switches, cmd, has_selection, switch_or}; +use crate::{Result, Session}; + +/// Nest Shapes' command. +pub const NEST: &str = "addon.cutting.nest"; +/// The largest sheet width or height, in points. +const MAX_SIZE: f64 = 1_000_000.0; +/// The largest margin or spacing, in points. +const MAX_GAP: f64 = 100_000.0; +/// The most objects one run nests. +const MAX_SHAPES: usize = 10_000; +/// How far a box may reach past the sheet's edge and still fit (rounding). +const EPS: f64 = 1e-9; + +pub fn specs() -> Vec { + vec![cmd!( + "addon.cutting.nest", + "Nest Shapes…", + ["Object", "Plug-ins", "Cutting Tools"], + None, + "{roll?: bool (false: a sheet `width` × `height`; true: a roll `width` wide with no end), width?: pt 0..1000000 (0: the artboard's width), height?: pt 0..1000000 (0: the artboard's height; not used with roll), margin?: pt 0..100000 (18: kept clear inside each edge of the sheet; on a roll, the sides and the start), spacing?: pt 0..100000 (9: kept between two objects), rotate?: bool (false: objects keep their orientation; true: an object may turn 90° clockwise where that puts its bottom edge higher, or where only the turned object fits), usePreviewBounds?: bool (true: objects are measured with their strokes and effects, the reach of shadows, glows and blurs included; false: by their geometry), artboard?: index (0-based; the sheet's artboard; default: the artboard under the center of the selection, else the first), patterns?: bool (Transform Patterns: pattern fills and strokes move with the art; default: prefs transformPatternTiles)} move the selected objects onto the sheet or roll, which starts at the artboard's top-left corner, packed by their bounding boxes: the tallest first (with rotate, the longest side first), each where its bottom edge is highest and then furthest left, without resizing them. An object on the pixel grid moves by whole points and takes 1 pt more room across and down; a path of a pixel-aligned compound path is not turned. Objects that do not fit on the sheet go in a column to the right of it, `spacing` from its edge and from each other, from its top, in stacking order (back to front). Objects without bounds (an empty group) are not moved. One undo step; nothing changes when no object moves → {placed: count, unplaced: [ids of the objects put beside the sheet], rotated: [ids], skipped: [ids of the objects without bounds], length: pt (from the sheet's top edge to the bottom margin below the lowest object placed)}", + has_selection, + nest + )] +} + +/// The length `p` gives for `key`, from 0 to `max`, or `default`. +fn length(p: &Value, key: &str, default: f64, max: f64) -> Result { + match length_given(p, key, NEST)? { + None => Ok(default), + Some(v) if (0.0..=max).contains(&v) => Ok(v), + Some(_) => Err(bad(NEST, format!("`{key}` must be from 0 to {max} pt"))), + } +} + +/// One stretch of a skyline: from `x`, `w` wide, filled down to `y`. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Span { + x: f64, + w: f64, + y: f64, +} + +/// Bottom-left packing of boxes on a skyline: a strip `width` wide and `height` deep +/// (`f64::INFINITY` for a roll), whose filled part is the spans' outline along its top. +struct Skyline { + spans: Vec, + width: f64, + height: f64, +} + +impl Skyline { + fn new(width: f64, height: f64) -> Self { + Skyline { spans: vec![Span { x: 0.0, w: width, y: 0.0 }], width, height } + } + + /// Where a box `w` × `h` goes: at the left edge of a span, as high as the spans under it + /// allow, choosing the place where its bottom edge is highest and then furthest left. `None` + /// when it fits nowhere. The spans under the box at each span are a window whose two ends only + /// move right, and `window` holds the indices in it whose depth no later span in it reaches, so + /// its front is the deepest: one call takes time in proportion to the number of spans. + fn find(&self, w: f64, h: f64) -> Option<(f64, f64)> { + let mut best: Option<(f64, f64)> = None; + let mut window: VecDeque = VecDeque::new(); + let mut end = 0; + for (i, s) in self.spans.iter().enumerate() { + if s.x + w > self.width + EPS { + break; + } + while window.front().is_some_and(|&j| j < i) { + window.pop_front(); + } + end = end.max(i); + while let Some(t) = self.spans.get(end) + && (end == i || t.x < s.x + w - EPS) + { + while window.back().and_then(|&j| self.spans.get(j)).is_some_and(|b| b.y <= t.y) { + window.pop_back(); + } + window.push_back(end); + end += 1; + } + let y = window.front().and_then(|&j| self.spans.get(j)).map_or(0.0, |t| t.y.max(0.0)); + if y + h > self.height + EPS { + continue; + } + // The box is `h` tall at every place, so the place with the highest bottom edge is the + // place with the highest top edge. + if best.is_none_or(|(bx, by)| y < by - EPS || ((y - by).abs() <= EPS && s.x < bx)) { + best = Some((s.x, y)); + } + } + best + } + + /// Fills the skyline down to `y + h` from `x` across `w`. + fn place(&mut self, x: f64, y: f64, w: f64, h: f64) { + if w <= 0.0 { + return; + } + let end = x + w; + let mut out = Vec::with_capacity(self.spans.len() + 2); + let mut added = false; + for s in &self.spans { + let s_end = s.x + s.w; + if s_end <= x || s.x >= end { + out.push(*s); + continue; + } + if s.x < x { + out.push(Span { x: s.x, w: x - s.x, y: s.y }); + } + if !added { + out.push(Span { x, w, y: y + h }); + added = true; + } + if s_end > end { + out.push(Span { x: end, w: s_end - end, y: s.y }); + } + } + // Neighbors filled to the same depth are one span. + let mut merged: Vec = Vec::with_capacity(out.len()); + for s in out { + match merged.last_mut() { + Some(l) if l.y == s.y => l.w = s.x + s.w - l.x, + _ => merged.push(s), + } + } + self.spans = merged; + } +} + +/// One box to pack: its width and height as it stands, and when it may turn, as it is turned. +type Sizes = ((f64, f64), Option<(f64, f64)>); + +/// The side a box is ordered by: its height, or its longest side when it may turn. +fn lead(b: &Sizes) -> (f64, f64) { + let ((w, h), turned) = *b; + if turned.is_some() { (w.max(h), w.min(h)) } else { (h, w) } +} + +/// Packs `boxes` onto a strip `width` wide and `height` deep, the tallest first (a box that may +/// turn by its longest side; then the widest, then in their order), each where [`Skyline::find`] +/// puts it, turned when that puts its bottom edge higher (then further left), or when only the +/// turned box fits. Gives each box's top-left corner and whether it is turned, or `None` for a box +/// that does not fit. +fn pack(boxes: &[Sizes], width: f64, height: f64) -> Vec> { + let mut order: Vec = (0..boxes.len()).collect(); + order.sort_by(|&a, &b| { + let (la, lb) = (lead(&boxes[a]), lead(&boxes[b])); + lb.0.total_cmp(&la.0).then(lb.1.total_cmp(&la.1)) + }); + let mut sky = Skyline::new(width, height); + let mut at = vec![None; boxes.len()]; + for i in order { + let Some(&((w, h), turned)) = boxes.get(i) else { continue }; + let mut best = sky.find(w, h).map(|(x, y)| (x, y, false, w, h)); + if let Some((tw, th)) = turned + && let Some((x, y)) = sky.find(tw, th) + { + let better = best.is_none_or(|(bx, by, _, _, bh)| { + let (was, now) = (by + bh, y + th); + now < was - EPS || ((now - was).abs() <= EPS && x < bx - EPS) + }); + if better { + best = Some((x, y, true, tw, th)); + } + } + if let Some((x, y, t, bw, bh)) = best { + sky.place(x, y, bw, bh); + if let Some(slot) = at.get_mut(i) { + *slot = Some((x, y, t)); + } + } + } + at +} + +/// A quarter turn clockwise on the page about `c`. +fn quarter_turn(c: Point) -> Affine { + Affine::translate(c.to_vec2()) * vectorcraft_geom::rotate_deg(90.0) * Affine::translate(-c.to_vec2()) +} + +fn finite(r: &Rect) -> bool { + [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) +} + +/// The box `id` is packed by: with `preview`, its visual bounds with geometry effects +/// ([`effects::preview::bounds_of`]) and the reach of its raster effects, such as shadows, glows +/// and blurs ([`vectorcraft_render::drawn_bounds`]); else its geometric bounds. +fn measure(d: &vectorcraft_doc::Document, id: NodeId, preview: bool) -> Option { + let b = effects::preview::bounds_of(d, &[id], preview).filter(finite)?; + if !preview { + return Some(b); + } + match d.node(id).and_then(|n| vectorcraft_render::drawn_bounds(d, n)).filter(finite) { + Some(r) => Some(b.union(r)), + None => Some(b), + } +} + +/// Whether `id` is a path of a pixel-aligned compound path. +fn in_aligned_compound(d: &Document, id: NodeId) -> bool { + d.parent_of(id).and_then(|p| d.node(p)).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && n.extras().pixel_aligned) +} + +/// Whether moving `id` snaps it, or an object in it, to the pixel grid: it, an object it holds or +/// the art of a linked opacity mask in it is pixel-aligned, or it is a path of a pixel-aligned +/// compound path. +fn snaps(d: &Document, id: NodeId) -> bool { + if in_aligned_compound(d, id) { + return true; + } + let mut stack: Vec<&Node> = d.node(id).into_iter().collect(); + while let Some(n) = stack.pop() { + if n.extras().pixel_aligned { + return true; + } + stack.extend(n.children().map_or(&[][..], Vec::as_slice).iter().map(|c| &**c)); + if let Some(m) = n.extras().mask.as_ref() + && m.linked + { + stack.push(&*m.art); + } + } + false +} + +fn nest(s: &mut Session, p: &Value) -> Result { + check_switches(p, &["patterns"], NEST)?; + let roll = switch_or(p, "roll", false, NEST)?; + let width = length(p, "width", 0.0, MAX_SIZE)?; + let height = length(p, "height", 0.0, MAX_SIZE)?; + let margin = length(p, "margin", 18.0, MAX_GAP)?; + let spacing = length(p, "spacing", 9.0, MAX_GAP)?; + let turn = switch_or(p, "rotate", false, NEST)?; + let preview = switch_or(p, "usePreviewBounds", true, NEST)?; + let named = match p.get("artboard") { + None | Some(Value::Null) => None, + Some(v) => Some(v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(NEST, "`artboard` must be an artboard's index"))?), + }; + // A path of a compound path selected on its own moves without the rest of the compound path. + let ids = selected_roots_to_transform(s)?; + if ids.len() > MAX_SHAPES { + return Err(bad(NEST, format!("select at most {MAX_SHAPES} objects to nest"))); + } + // Objects without a finite box (an empty group, empty type) are left where they are and + // listed as `skipped`. + let mut skipped = vec![]; + let (items, board): (Vec<(NodeId, Rect)>, Rect) = { + let d = &s.doc()?.doc; + let mut items: Vec<(NodeId, Rect)> = Vec::with_capacity(ids.len()); + for id in &ids { + match measure(d, *id, preview) { + Some(r) => items.push((*id, r)), + None => skipped.push(id.0), + } + } + let board = match named { + Some(i) => d.artboards.get(i).ok_or_else(|| bad(NEST, format!("there is no artboard {i}")))?.rect, + None => { + let all = items.iter().map(|(_, r)| *r).reduce(|a, b| a.union(b)); + let i = all.and_then(|r| d.artboard_at(r.center())).unwrap_or(0); + d.artboards.get(i).ok_or_else(|| bad(NEST, "there is no artboard for the sheet"))?.rect + } + }; + (items, board) + }; + if items.is_empty() { + return Err(bad(NEST, "the selection has nothing to nest")); + } + let sheet_w = if width > 0.0 { width } else { board.width() }; + let sheet_h = if roll { + f64::INFINITY + } else if height > 0.0 { + height + } else { + board.height() + }; + // Every box is `spacing` wider and taller, and the strip is `spacing` wider and deeper than + // the room inside the margins, so the spacing falls between boxes and not at the far edges. + let room_w = sheet_w - 2.0 * margin; + let room_h = if roll { f64::INFINITY } else { sheet_h - 2.0 * margin }; + if room_w <= 0.0 || room_h <= 0.0 { + return Err(bad(NEST, "the margin leaves no room on the sheet")); + } + let all: Vec = items.iter().map(|(id, _)| *id).collect(); + let grid: Vec = { + let d = &s.doc()?.doc; + all.iter().map(|id| snaps(d, *id)).collect() + }; + let sc = Scaling { patterns: transform_patterns(s, p, &all)?, ..Scaling::default() }; + // With `rotate`, each object is turned in a copy of the document and measured there, so the + // box packed for a turned object is the box its turned strokes and effects take. A path of a + // pixel-aligned compound path keeps its orientation: turning it snaps the whole compound path + // again, which would move the compound's other paths away from where they were measured. + let turned: Vec> = if turn { + let mut t = vectorcraft_doc::Document::clone(&s.doc()?.doc); + let xfs: Vec> = items.iter().map(|(id, r)| (!in_aligned_compound(&t, *id)).then(|| quarter_turn(r.center()))).collect(); + for ((id, _), xf) in items.iter().zip(&xfs) { + if let (Some(xf), Some(n)) = (xf, t.node_mut(*id)) { + transform_node(n, *xf, sc, true); + } + } + items.iter().zip(xfs).map(|((id, _), xf)| xf.and_then(|xf| measure(&t, *id, preview).map(|r| (xf, r)))).collect() + } else { + vec![None; items.len()] + }; + // An object that snaps to the pixel grid moves by whole points, so it stays on the grid and the + // snap after the move does not shift it; its box is 1 pt wider and taller to hold the rounding. + let slack = |g: bool| if g { 1.0 } else { 0.0 }; + let boxes: Vec = items + .iter() + .zip(&turned) + .zip(&grid) + .map(|(((_, r), t), g)| { + let pad = spacing + slack(*g); + ((r.width() + pad, r.height() + pad), t.map(|(_, q)| (q.width() + pad, q.height() + pad))) + }) + .collect(); + let at = pack(&boxes, room_w + spacing, room_h + spacing); + let origin = Vec2::new(board.x0 + margin, board.y0 + margin); + // The move that puts the top-left corner of box `b` at `to`: rounded up to whole points for an + // object on the pixel grid, so it moves at most 1 pt further right and down, into its slack. + let shift = |b: &Rect, to: Vec2, g: bool| { + let v = Vec2::new(to.x - b.x0, to.y - b.y0); + if g { Vec2::new(v.x.ceil(), v.y.ceil()) } else { v } + }; + // Each move: the quarter turn first, when the object turns, then the shift. + let mut moves: Vec<(NodeId, Option, Vec2)> = vec![]; + let mut aside: Vec<(NodeId, Option, Vec2)> = vec![]; + let mut unplaced = vec![]; + let mut rotated = vec![]; + let mut bottom = 0.0_f64; + // Objects that do not fit go in a column to the right of the sheet, `spacing` from its edge + // and from each other, so that no object placed on the sheet covers them. + let aside_x = board.x0 + sheet_w + spacing; + let mut aside_y = board.y0; + for ((((id, r), spot), t), g) in items.iter().zip(&at).zip(&turned).zip(&grid) { + match (spot, t) { + (Some((x, y, true)), Some((xf, q))) => { + let dv = shift(q, Vec2::new(origin.x + x, origin.y + y), *g); + moves.push((*id, Some(*xf), dv)); + rotated.push(id.0); + bottom = bottom.max(q.y1 + dv.y - origin.y); + } + (Some((x, y, _)), _) => { + let dv = shift(r, Vec2::new(origin.x + x, origin.y + y), *g); + moves.push((*id, None, dv)); + bottom = bottom.max(r.y1 + dv.y - origin.y); + } + (None, _) => { + aside.push((*id, None, shift(r, Vec2::new(aside_x, aside_y), *g))); + aside_y += r.height() + spacing + slack(*g); + unplaced.push(id.0); + } + } + } + if moves.is_empty() { + return Err(bad(NEST, "no selected object fits on the sheet")); + } + moves.extend(aside); + let length = 2.0 * margin + bottom; + let placed = moves.len() - unplaced.len(); + let result = json!({ "placed": placed, "unplaced": unplaced, "rotated": rotated, "skipped": skipped, "length": length }); + if moves.iter().all(|(_, xf, dv)| xf.is_none() && dv.x.abs() <= EPS && dv.y.abs() <= EPS) { + return Ok(result); + } + s.edit("Nest Shapes", |d, _| { + for (id, xf, dv) in &moves { + // The turn is the one the object was measured with in the copy, and the shift after it + // is whole points for an object on the pixel grid. + for step in xf.iter().copied().chain([Affine::translate(*dv)]) { + if let Some(n) = d.node_mut(*id) { + transform_node(n, step, sc, true); + } + keep_compound_aligned(d, *id, sc); + } + } + Ok(()) + })?; + Ok(result) +} diff --git a/crates/engine/src/cmd/addons/cutting/nest/tests.rs b/crates/engine/src/cmd/addons/cutting/nest/tests.rs new file mode 100644 index 0000000000..6ca6548a19 --- /dev/null +++ b/crates/engine/src/cmd/addons/cutting/nest/tests.rs @@ -0,0 +1,433 @@ +//! Tests for `addon.cutting.nest`: packing the selected objects onto a sheet or a roll. + +use serde_json::{Value, json}; +use vectorcraft_geom::Rect; + +use super::{Skyline, pack}; +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) +} + +fn bounds(s: &Session, id: NodeId) -> Rect { + s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().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() +} + +fn overlap(a: Rect, b: Rect) -> bool { + a.x0 < b.x1 - 1e-9 && b.x0 < a.x1 - 1e-9 && a.y0 < b.y1 - 1e-9 && b.y0 < a.y1 - 1e-9 +} + +#[test] +fn boxes_pack_tallest_first_from_the_top_left() { + // 100 wide: the 60 × 50 box goes first at the left and the 40 × 30 one beside it. The 50 × 20 + // one is too wide for the 40 pt beside the first box, so it goes below the first box. + let at = pack(&fixed(&[(40.0, 30.0), (60.0, 50.0), (50.0, 20.0)]), 100.0, f64::INFINITY); + assert_eq!(at, vec![Some((60.0, 0.0, false)), Some((0.0, 0.0, false)), Some((0.0, 50.0, false))]); +} + +#[test] +fn a_box_that_does_not_fit_is_left_out() { + let at = pack(&fixed(&[(80.0, 80.0), (80.0, 80.0), (120.0, 10.0)]), 100.0, 100.0); + assert_eq!(at, vec![Some((0.0, 0.0, false)), None, None]); +} + +/// Boxes that keep their orientation. +fn fixed(b: &[(f64, f64)]) -> Vec { + b.iter().map(|&s| (s, None)).collect() +} + +/// Boxes that may turn a quarter. +fn turning(b: &[(f64, f64)]) -> Vec { + b.iter().map(|&(w, h)| ((w, h), Some((h, w)))).collect() +} + +#[test] +fn a_box_turns_where_its_bottom_edge_ends_higher_or_only_turned_it_fits() { + // A 20 × 90 box lies down as 90 × 20 at the top; a 120 × 10 box only fits the 100 pt strip + // turned, as 10 × 120. + let at = pack(&turning(&[(20.0, 90.0), (120.0, 10.0)]), 100.0, f64::INFINITY); + assert_eq!(at, vec![Some((10.0, 0.0, true)), Some((0.0, 0.0, true))]); + // Without turning, the 120 pt wide box is left out and the other stands up. + let at = pack(&fixed(&[(20.0, 90.0), (120.0, 10.0)]), 100.0, f64::INFINITY); + assert_eq!(at, vec![Some((0.0, 0.0, false)), None]); + // A square box is never turned: turned, it is no better. + let at = pack(&turning(&[(30.0, 30.0)]), 100.0, 100.0); + assert_eq!(at, vec![Some((0.0, 0.0, false))]); +} + +#[test] +fn the_skyline_fills_and_merges_spans() { + let mut sky = Skyline::new(100.0, f64::INFINITY); + sky.place(0.0, 0.0, 30.0, 10.0); + sky.place(30.0, 0.0, 30.0, 10.0); + assert_eq!(sky.spans.len(), 2, "two spans at the same depth are one: {:?}", sky.spans); + assert_eq!(sky.find(50.0, 5.0), Some((0.0, 10.0)), "50 wide does not fit in the 40 left at the top"); + assert_eq!(sky.find(40.0, 5.0), Some((60.0, 0.0))); +} + +#[test] +fn selected_objects_are_nested_on_the_artboard_as_one_undo_step() { + let mut s = session(); + let ids: Vec = (0..6).map(|i| rect(&mut s, 900.0 + 300.0 * i as f64, 700.0, 150.0, 100.0 + 10.0 * i as f64)).collect(); + select(&mut s, &ids); + let n = steps(&s); + let r = s.execute("addon.cutting.nest", &json!({"margin": 10, "spacing": 5, "usePreviewBounds": false})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert_eq!(r["placed"], json!(6)); + assert_eq!(r["unplaced"], json!([])); + let boxes: Vec = ids.iter().map(|id| bounds(&s, *id)).collect(); + for (i, a) in boxes.iter().enumerate() { + assert!(a.x0 >= 10.0 - 1e-9 && a.y0 >= 10.0 - 1e-9 && a.x1 <= 790.0 + 1e-9 && a.y1 <= 590.0 + 1e-9, "{a:?} inside the margins"); + assert!((a.width(), a.height()) == (150.0, 100.0 + 10.0 * i as f64), "moved, not resized"); + for b in &boxes[i + 1..] { + assert!(!overlap(a.inflate(2.5, 2.5), b.inflate(2.5, 2.5)), "{a:?} and {b:?} are 5 pt apart"); + } + } + // The tallest (150 pt) is at the top-left corner inside the margin, and five 150 pt wide + // boxes with 5 pt between them fill the 780 pt inside the margins. The shortest goes 5 pt below + // the 110 pt tall box at the right, where its bottom edge is highest. + assert_eq!((boxes[5].x0, boxes[5].y0), (10.0, 10.0)); + assert_eq!(boxes.iter().filter(|b| b.y0 == 10.0).count(), 5); + assert_eq!((boxes[0].x0, boxes[0].y0), (630.0, 125.0)); + assert_eq!(r["length"], json!(10.0 + 115.0 + 100.0 + 10.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(bounds(&s, ids[0]), Rect::new(900.0, 700.0, 1050.0, 800.0)); +} + +#[test] +fn objects_that_do_not_fit_go_beside_the_sheet() { + let mut s = session(); + let a = rect(&mut s, 900.0, 0.0, 500.0, 400.0); + let b = rect(&mut s, 1500.0, 0.0, 500.0, 400.0); + let big = rect(&mut s, 2100.0, 0.0, 900.0, 100.0); + select(&mut s, &[a, b, big]); + let r = s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 5, "usePreviewBounds": false})).unwrap(); + assert_eq!(r["placed"], json!(1)); + assert_eq!(r["unplaced"], json!([b.0, big.0])); + assert_eq!(bounds(&s, a), Rect::new(0.0, 0.0, 500.0, 400.0)); + // A column 5 pt to the right of the 800 pt sheet, in stacking order, 5 pt apart. + assert_eq!(bounds(&s, b), Rect::new(805.0, 0.0, 1305.0, 400.0)); + assert_eq!(bounds(&s, big), Rect::new(805.0, 405.0, 1705.0, 505.0)); +} + +#[test] +fn the_column_beside_the_sheet_is_in_stacking_order() { + let mut s = session(); + let back = rect(&mut s, 900.0, 0.0, 900.0, 100.0); + let front = rect(&mut s, 900.0, 200.0, 900.0, 50.0); + let small = rect(&mut s, 900.0, 400.0, 50.0, 50.0); + // Selected front first: the column still starts with the object at the back. + select(&mut s, &[front, small, back]); + let r = s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 5, "usePreviewBounds": false})).unwrap(); + assert_eq!(r["unplaced"], json!([back.0, front.0])); + assert_eq!(bounds(&s, back), Rect::new(805.0, 0.0, 1705.0, 100.0)); + assert_eq!(bounds(&s, front), Rect::new(805.0, 105.0, 1705.0, 155.0)); +} + +#[test] +fn objects_without_bounds_are_skipped_and_listed() { + let mut s = session(); + let a = rect(&mut s, 900.0, 0.0, 50.0, 50.0); + let layer = s.doc().unwrap().doc.parent_of(a); + let empty = s + .edit("empty group", |d, _| { + let g = vectorcraft_doc::Node::new(d.alloc_id(), vectorcraft_doc::NodeKind::Group { children: vec![], clip: false }); + Ok(d.insert(layer, usize::MAX, g).unwrap()) + }) + .unwrap(); + select(&mut s, &[a, empty]); + let r = s.execute("addon.cutting.nest", &json!({"margin": 0, "usePreviewBounds": false})).unwrap(); + assert_eq!((r["placed"].clone(), r["unplaced"].clone(), r["skipped"].clone()), (json!(1), json!([]), json!([empty.0]))); + assert_eq!(bounds(&s, a), Rect::new(0.0, 0.0, 50.0, 50.0)); +} + +#[test] +fn the_sheet_is_the_artboard_under_the_center_of_the_selection() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 300, "height": 300})).unwrap(); + let a = rect(&mut s, 1100.0, 100.0, 50.0, 50.0); + let b = rect(&mut s, 1200.0, 200.0, 40.0, 40.0); + select(&mut s, &[a, b]); + s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 0, "usePreviewBounds": false})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(1000.0, 0.0, 1050.0, 50.0), "on the second artboard, not the first"); + assert_eq!(bounds(&s, b), Rect::new(1050.0, 0.0, 1090.0, 40.0)); +} + +#[test] +fn rotate_turns_clockwise() { + let mut s = session(); + // A 400 × 100 group with a 20 pt mark at its top-left corner. Turned clockwise on the page, the + // top-left corner goes to the top-right. + let long = rect(&mut s, 900.0, 0.0, 400.0, 100.0); + let mark = rect(&mut s, 900.0, 0.0, 20.0, 20.0); + select(&mut s, &[long, mark]); + s.execute("object.group", &json!({})).unwrap(); + let r = s + .execute("addon.cutting.nest", &json!({"width": 300, "height": 500, "margin": 0, "spacing": 0, "rotate": true, "usePreviewBounds": false})) + .unwrap(); + assert_eq!(r["rotated"].as_array().map(Vec::len), Some(1)); + assert_eq!(bounds(&s, long), Rect::new(0.0, 0.0, 100.0, 400.0)); + assert_eq!(bounds(&s, mark), Rect::new(80.0, 0.0, 100.0, 20.0), "the mark is at the top-right"); +} + +#[test] +fn a_path_of_a_pixel_aligned_compound_path_is_not_turned() { + let mut s = session(); + let outer = rect(&mut s, 900.0, 100.0, 500.0, 200.0); + let hole = rect(&mut s, 950.0, 150.0, 400.0, 100.0); + select(&mut s, &[outer, hole]); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("object.setPixelAligned", &json!({})).unwrap(); + select(&mut s, &[hole]); + // The 400 pt wide path fits the 300 pt sheet only turned, and it keeps its orientation. + let r = + s.execute("addon.cutting.nest", &json!({"width": 300, "height": 500, "margin": 0, "spacing": 0, "rotate": true, "usePreviewBounds": false})); + let e = r.unwrap_err().to_string(); + assert!(e.contains("no selected object fits"), "{e}"); +} + +/// [`Skyline::find`] as a search of every span and every span under the box. +fn find_by_search(sky: &Skyline, w: f64, h: f64) -> Option<(f64, f64)> { + let mut best: Option<(f64, f64)> = None; + for (i, s) in sky.spans.iter().enumerate() { + if s.x + w > sky.width + 1e-9 { + break; + } + let y = sky.spans[i..].iter().take_while(|t| t.x == s.x || t.x < s.x + w - 1e-9).fold(0.0_f64, |m, t| m.max(t.y)); + if y + h > sky.height + 1e-9 { + continue; + } + if best.is_none_or(|(bx, by)| y < by - 1e-9 || ((y - by).abs() <= 1e-9 && s.x < bx)) { + best = Some((s.x, y)); + } + } + best +} + +#[test] +fn find_matches_a_search_of_every_span() { + // A fixed pseudo-random sequence of boxes, each placed where `find` puts it. + let mut seed: u64 = 0x2545_f491_4f6c_dd1d; + let mut next = |n: u64| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % n) as f64 + 1.0 + }; + let mut sky = Skyline::new(200.0, 400.0); + for _ in 0..400 { + let (w, h) = (next(60), next(30)); + let got = sky.find(w, h); + assert_eq!(got, find_by_search(&sky, w, h), "{w} × {h} on {:?}", sky.spans); + if let Some((x, y)) = got { + sky.place(x, y, w, h); + } + } +} + +#[test] +fn an_object_that_does_not_fit_is_not_covered_by_the_others() { + let mut s = session(); + // The wide object sits on the sheet and does not fit; the small one must not land on it. + let wide = rect(&mut s, 0.0, 0.0, 900.0, 100.0); + let small = rect(&mut s, 300.0, 300.0, 50.0, 50.0); + select(&mut s, &[wide, small]); + s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 0, "usePreviewBounds": false})).unwrap(); + assert!(!overlap(bounds(&s, wide), bounds(&s, small)), "{:?} {:?}", bounds(&s, wide), bounds(&s, small)); +} + +#[test] +fn objects_on_the_pixel_grid_keep_the_margin_and_spacing() { + let mut s = session(); + let a = rect(&mut s, 900.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 1100.0, 0.0, 100.0, 90.0); + select(&mut s, &[a, b]); + s.execute("object.setPixelAligned", &json!({})).unwrap(); + let on_grid = |r: Rect| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| (v * 2.0).fract() == 0.0); + assert!(on_grid(bounds(&s, a)) && on_grid(bounds(&s, b))); + s.execute("addon.cutting.nest", &json!({"margin": 0.6, "spacing": 0.6, "usePreviewBounds": false})).unwrap(); + let (ba, bb) = (bounds(&s, a), bounds(&s, b)); + assert!(on_grid(ba) && on_grid(bb), "still on the grid: {ba:?} {bb:?}"); + assert!(ba.x0 >= 0.6 && ba.y0 >= 0.6 && bb.y0 >= 0.6, "inside the margin: {ba:?} {bb:?}"); + assert!(bb.x0 >= ba.x1 + 0.6, "0.6 pt apart: {ba:?} {bb:?}"); + assert!(ba.x1.max(bb.x1) <= 800.0 - 0.6, "inside the margin: {ba:?} {bb:?}"); +} + +#[test] +fn preview_bounds_take_in_a_drop_shadow() { + let mut s = session(); + let a = rect(&mut s, 900.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 1100.0, 0.0, 100.0, 100.0); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [a.0], "params": {"x": 20, "y": 0, "blur": 0}})).unwrap(); + select(&mut s, &[a, b]); + s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 0})).unwrap(); + let (ba, bb) = (bounds(&s, a), bounds(&s, b)); + let shadow = vectorcraft_render::drawn_bounds(&s.doc().unwrap().doc, s.doc().unwrap().doc.node(a).unwrap()).unwrap(); + assert!(shadow.x1 >= ba.x1 + 20.0 - 1e-9, "the shadow reaches 20 pt right: {shadow:?}"); + let shadow_b = vectorcraft_render::drawn_bounds(&s.doc().unwrap().doc, s.doc().unwrap().doc.node(b).unwrap()).unwrap_or(bb); + assert!(!overlap(shadow, shadow_b.union(bb)), "the shadow {shadow:?} does not reach {bb:?}"); +} + +#[test] +fn a_roll_has_no_end() { + let mut s = session(); + let ids: Vec = (0..5).map(|i| rect(&mut s, 900.0, 300.0 * i as f64, 500.0, 400.0)).collect(); + select(&mut s, &ids); + let r = s.execute("addon.cutting.nest", &json!({"roll": true, "margin": 0, "spacing": 10, "usePreviewBounds": false})).unwrap(); + assert_eq!((r["placed"].clone(), r["unplaced"].clone()), (json!(5), json!([]))); + let mut tops: Vec = ids.iter().map(|id| bounds(&s, *id).y0).collect(); + tops.sort_by(f64::total_cmp); + assert_eq!(tops, vec![0.0, 410.0, 820.0, 1230.0, 1640.0], "one 500 pt wide shape per row on the 800 pt roll"); + assert_eq!(r["length"], json!(2040.0)); +} + +#[test] +fn width_and_height_set_the_sheet_from_the_artboard_corner() { + let mut s = session(); + let ids: Vec = (0..3).map(|i| rect(&mut s, 50.0 * i as f64, 300.0, 40.0, 40.0)).collect(); + select(&mut s, &ids); + let r = s.execute("addon.cutting.nest", &json!({"width": "1 in", "height": 200, "margin": 0, "spacing": 0, "usePreviewBounds": false})).unwrap(); + assert_eq!(r["placed"], json!(3)); + for id in &ids { + let b = bounds(&s, *id); + assert!(b.x0 == 0.0 && b.x1 <= 72.0, "one 40 pt shape per row on a 72 pt sheet: {b:?}"); + } +} + +#[test] +fn preview_bounds_keep_strokes_apart() { + let mut s = session(); + let a = rect(&mut s, 900.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 1100.0, 0.0, 100.0, 100.0); + select(&mut s, &[a, b]); + s.execute("stroke.set", &json!({"weight": 10})).unwrap(); + s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 0})).unwrap(); + let (ba, bb) = (bounds(&s, a), bounds(&s, b)); + assert_eq!((ba.x0, ba.y0), (5.0, 5.0), "the stroke's outer half is inside the sheet"); + assert_eq!((bb.x0 - ba.x1), 10.0, "the strokes touch and do not overlap"); +} + +#[test] +fn a_selection_already_nested_adds_no_undo_step() { + let mut s = session(); + let a = rect(&mut s, 18.0, 18.0, 100.0, 100.0); + select(&mut s, &[a]); + let n = steps(&s); + let r = s.execute("addon.cutting.nest", &json!({"usePreviewBounds": false})).unwrap(); + assert_eq!(r["placed"], json!(1)); + assert_eq!(steps(&s), n, "nothing moved"); +} + +#[test] +fn bad_params_are_refused_and_change_nothing() { + let mut s = session(); + let a = rect(&mut s, 900.0, 0.0, 100.0, 100.0); + select(&mut s, &[a]); + let n = steps(&s); + let bad: [(Value, &str); 10] = [ + (json!({"rotate": 1}), "`rotate` must be true or false"), + (json!({"width": -1}), "`width` must be from 0"), + (json!({"height": 2e6}), "`height` must be from 0"), + (json!({"margin": "x"}), "`margin` must be a number"), + (json!({"spacing": 1e6}), "`spacing` must be from 0"), + (json!({"roll": "yes"}), "`roll` must be true or false"), + (json!({"usePreviewBounds": 1}), "`usePreviewBounds` must be true or false"), + (json!({"artboard": 3}), "there is no artboard 3"), + (json!({"artboard": -1}), "`artboard` must be"), + (json!({"margin": 400}), "the margin leaves no room"), + ]; + for (p, want) in bad { + let e = s.execute("addon.cutting.nest", &p).expect_err(&p.to_string()).to_string(); + assert!(e.contains(want), "{p}: {e}"); + } + let e = s.execute("addon.cutting.nest", &json!({"width": 50, "margin": 0})).unwrap_err().to_string(); + assert!(e.contains("no selected object fits"), "{e}"); + let e = s.execute("addon.cutting.nest", &json!({"patterns": "no"})).unwrap_err().to_string(); + assert!(e.contains("`patterns` must be true or false"), "{e}"); + assert_eq!(steps(&s), n, "a refused run changes nothing"); + assert_eq!(bounds(&s, a), Rect::new(900.0, 0.0, 1000.0, 100.0)); +} + +#[test] +fn the_named_artboard_is_the_sheet() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 300, "height": 300})).unwrap(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + select(&mut s, &[a]); + s.execute("addon.cutting.nest", &json!({"artboard": 1, "margin": 0, "usePreviewBounds": false})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(1000.0, 0.0, 1050.0, 50.0)); +} + +#[test] +fn rotate_turns_objects_a_quarter_to_fit_the_sheet() { + let mut s = session(); + // On a 300 × 500 sheet with no margin, a 400 × 100 object only fits standing up. + let long = rect(&mut s, 900.0, 0.0, 400.0, 100.0); + let small = rect(&mut s, 900.0, 300.0, 50.0, 40.0); + select(&mut s, &[long, small]); + let p = json!({"width": 300, "height": 500, "margin": 0, "spacing": 0, "usePreviewBounds": false}); + let r = s.execute("addon.cutting.nest", &p).unwrap(); + assert_eq!((r["unplaced"].clone(), r["rotated"].clone()), (json!([long.0]), json!([])), "without rotate it does not fit"); + s.execute("edit.undo", &json!({})).unwrap(); + let mut p = p; + p["rotate"] = json!(true); + let n = steps(&s); + let r = s.execute("addon.cutting.nest", &p).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert_eq!((r["placed"].clone(), r["unplaced"].clone(), r["rotated"].clone()), (json!(2), json!([]), json!([long.0]))); + assert_eq!(bounds(&s, long), Rect::new(0.0, 0.0, 100.0, 400.0), "turned and at the corner"); + // The 50 × 40 object stays as it is: turned, its bottom edge would be lower. + assert_eq!(bounds(&s, small), Rect::new(100.0, 0.0, 150.0, 40.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(bounds(&s, long), Rect::new(900.0, 0.0, 1300.0, 100.0), "undo turns it back"); +} + +#[test] +fn rotate_measures_the_turned_preview_bounds() { + let mut s = session(); + let a = rect(&mut s, 900.0, 0.0, 400.0, 100.0); + select(&mut s, &[a]); + s.execute("stroke.set", &json!({"weight": 10})).unwrap(); + let r = s.execute("addon.cutting.nest", &json!({"width": 300, "height": 500, "margin": 0, "spacing": 0, "rotate": true})).unwrap(); + assert_eq!(r["rotated"], json!([a.0])); + assert_eq!(bounds(&s, a), Rect::new(5.0, 5.0, 105.0, 405.0), "the turned stroke's outer half is inside the sheet"); +} + +#[test] +fn a_compound_paths_path_selected_alone_moves_alone() { + let mut s = session(); + let outer = rect(&mut s, 900.0, 100.0, 40.0, 40.0); + let hole = rect(&mut s, 910.0, 110.0, 10.0, 10.0); + select(&mut s, &[outer, hole]); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + select(&mut s, &[hole]); + s.execute("addon.cutting.nest", &json!({"margin": 0, "usePreviewBounds": false})).unwrap(); + assert_eq!(bounds(&s, hole), Rect::new(0.0, 0.0, 10.0, 10.0), "the path moved"); + assert_eq!(bounds(&s, outer), Rect::new(900.0, 100.0, 940.0, 140.0), "the rest of the compound path stayed"); +} + +#[test] +fn a_group_is_nested_as_one_object() { + let mut s = session(); + let a = rect(&mut s, 900.0, 0.0, 50.0, 50.0); + let b = rect(&mut s, 1000.0, 100.0, 50.0, 50.0); + select(&mut s, &[a, b]); + s.execute("object.group", &json!({})).unwrap(); + s.execute("addon.cutting.nest", &json!({"margin": 0, "usePreviewBounds": false})).unwrap(); + assert_eq!((bounds(&s, a), bounds(&s, b)), (Rect::new(0.0, 0.0, 50.0, 50.0), Rect::new(100.0, 100.0, 150.0, 150.0))); +} 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 786effbd2e..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 @@ -320,7 +318,8 @@ fn fresh(doc: &Document, n: &Node, cmd: &str) -> Option, doc: &mut Document) { 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/tests.rs b/crates/engine/src/cmd/addons/pathtools/tests.rs index a72075d233..7d11eedd1a 100644 --- a/crates/engine/src/cmd/addons/pathtools/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tests.rs @@ -531,8 +531,13 @@ fn an_anchor_edit_makes_it_a_plain_path_and_transforms_keep_it_editable() { s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "count": 6})).unwrap(); assert_eq!((path(&s, id).anchor_count(), steps(&s)), (12, n + 1)); assert!((shape_of(&s, id).unwrap().rotation + 30.0).abs() < 1e-6, "the turn stays"); - // Stretched across its own axes (it is turned): skewed, so no longer. + // Stretched along its turned bounding box: still the shape, wider along its own axis. s.execute("object.scale", &json!({"sx": 150, "sy": 100, "origin": [220, 140]})).unwrap(); + let r = shape_of(&s, id).unwrap(); + assert!((r.width - 300.0).abs() < 1e-6 && (r.height - 200.0).abs() < 1e-6 && (r.rotation + 30.0).abs() < 1e-6, "{r:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + // Stretched across the page's axes (it is turned): skewed, so no longer. + s.execute("object.scale", &json!({"sx": 150, "sy": 100, "origin": [220, 140], "basis": "page"})).unwrap(); assert_eq!(shape_of(&s, id), None); s.execute("edit.undo", &json!({})).unwrap(); assert!(shape_of(&s, id).is_some(), "undo brings it back"); @@ -1220,7 +1225,7 @@ fn expand_dashes_keeps_the_fill_below_and_follows_aligned_corners() { let mut centred = 0; for id in ids(&r) { let sp = path(&s, id).subpaths[0].clone(); - if let [a, b, c] = sp.anchors.as_slice() + if let [a, b, c] = &*sp.anchors.to_vec() && corners.iter().any(|k| b.p.distance(*k) < 1e-6) { assert!((a.p.distance(b.p) - 5.0).abs() < 1e-6 && (c.p.distance(b.p) - 5.0).abs() < 1e-6, "{sp:?}"); diff --git a/crates/engine/src/cmd/addons/pathtools/trim.rs b/crates/engine/src/cmd/addons/pathtools/trim.rs index 134edc6607..e1a21393f1 100644 --- a/crates/engine/src/cmd/addons/pathtools/trim.rs +++ b/crates/engine/src/cmd/addons/pathtools/trim.rs @@ -1,15 +1,15 @@ //! 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. +//! be edited, selected or not. What it removes is worked out by +//! [`vectorcraft_tools::addons::trim::plan`], which the tool also uses to show it beforehand. use std::collections::HashSet; use serde_json::{Value, json}; -use vectorcraft_doc::{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 +41,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 +79,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 })); } @@ -291,20 +102,21 @@ fn trim(s: &mut Session, p: &Value) -> Result { compounds.dedup(); let mut beside = Beside::replacing(d, &trimmed); let mut all = vec![]; + // The selection is read through a set and changed once at the end, so a trim of many + // paths does not go through the selected objects once per path and per piece. + let mut selected_ids: HashSet = sel.objects.iter().copied().collect(); + let mut joining: Vec = vec![]; + let mut gone: Vec = vec![]; for (id, pieces) in plan { - let selected = sel.contains(id); + let selected = selected_ids.contains(&id); sel.anchors.remove(&id); sel.segments.remove(&id); let made = replace_with_pieces(d, &mut beside, id, pieces)?; // The pieces of a selected path are selected; what was not selected stays so. if made.is_empty() { - sel.remove(id); + gone.push(id); } else if selected { - for n in &made { - if !sel.contains(*n) { - sel.add(*n); - } - } + joining.extend(made.iter().copied().filter(|n| selected_ids.insert(*n))); } all.extend(made); } @@ -312,9 +124,15 @@ fn trim(s: &mut Session, p: &Value) -> Result { for c in compounds { if d.node(c).is_some_and(|n| n.children().is_some_and(|ch| ch.is_empty())) { d.remove(c)?; - sel.remove(c); + gone.push(c); } } + sel.remove_all(gone); + if let Some((first, rest)) = joining.split_first() { + // `add` clears what any change to the object selection clears; the rest are new ids. + sel.add(*first); + sel.objects.extend_from_slice(rest); + } Ok(all) })?; Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "removed": removed })) diff --git a/crates/engine/src/cmd/addons/pathtools/trim/tests.rs b/crates/engine/src/cmd/addons/pathtools/trim/tests.rs index 42adb70ab9..6e0e2c057a 100644 --- a/crates/engine/src/cmd/addons/pathtools/trim/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/trim/tests.rs @@ -2,8 +2,9 @@ //! one undo step, and what takes no part. use serde_json::{Value, json}; -use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_doc::{NodeId, NodeKind, Selection}; use vectorcraft_geom::{PathData, Point}; +use vectorcraft_tools::addons::trim::plan::{self, Limits, Stretches}; use crate::Session; @@ -420,6 +421,139 @@ fn the_selection_stays_as_it_was_and_the_pieces_of_a_selected_path_are_selected( assert!(s.doc().unwrap().selection.is_empty(), "a removed path leaves the selection"); } +/// Run the command with `p`, and check that it leaves the selection exactly as changing it one +/// id at a time does: for each trimmed path in the plan's order, its anchors and segments let go, +/// a path with no pieces left removed, and each piece of a selected path added; then each emptied +/// compound path removed. Returns the selection. +fn same_selection_as_one_id_at_a_time(s: &mut Session, p: Value) -> Selection { + let st = s.doc().unwrap(); + let pick = super::pick(&p).unwrap(); + let root = crate::cmd::ordinary_isolation(st); + let plan: Vec<(NodeId, usize)> = + plan::plan(&st.doc, root, &pick, Limits::COMMAND, &mut Stretches::default()).unwrap().into_iter().map(|t| (t.id, t.pieces.len())).collect(); + let mut compounds: Vec = plan + .iter() + .filter_map(|(id, _)| st.doc.parent_of(*id)) + .filter(|c| matches!(st.doc.node(*c).map(|n| &n.kind), Some(NodeKind::Compound { .. }))) + .collect(); + compounds.dedup(); + let mut want = st.selection.clone(); + let made = ids(&s.execute(TRIM, &p).unwrap()); + assert_eq!(made.len(), plan.iter().map(|(_, n)| n).sum::()); + let mut made = made.into_iter(); + for (id, n) in plan { + let selected = want.contains(id); + want.anchors.remove(&id); + want.segments.remove(&id); + let pieces: Vec = made.by_ref().take(n).collect(); + if pieces.is_empty() { + want.remove(id); + } else if selected { + for piece in pieces { + if !want.contains(piece) { + want.add(piece); + } + } + } + } + let st = s.doc().unwrap(); + for c in compounds { + if st.doc.node(c).is_none() { + want.remove(c); + } + } + want.prune(&st.doc); + assert_eq!(st.selection, want); + st.selection.clone() +} + +/// Two lines across split by a rectangle, one of them selected; a selected line nothing crosses +/// and a selected compound path of two such lines, which the rectangle removes whole; and a +/// selected line elsewhere with an anchor and a segment direct-selected. Returns (the selected +/// line across, the line removed whole, the compound path, the line elsewhere). +fn trim_scene(s: &mut Session) -> (NodeId, NodeId, NodeId, NodeId) { + let (h, ..) = across_and_uprights(s); + line(s, &[(0.0, 120.0), (300.0, 120.0)], false); + let alone = line(s, &[(145.0, 200.0), (155.0, 200.0)], false); + let c1 = line(s, &[(145.0, 170.0), (155.0, 170.0)], false); + let c2 = line(s, &[(145.0, 180.0), (155.0, 180.0)], false); + s.execute("select.set", &json!({"ids": [c1.0, c2.0]})).unwrap(); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let elsewhere = line(s, &[(0.0, 250.0), (10.0, 250.0), (20.0, 250.0)], false); + s.execute("select.set", &json!({"ids": [elsewhere.0, h.0, alone.0, compound.0]})).unwrap(); + s.edit("direct", |_, sel| { + sel.anchors.insert(elsewhere, [(0, 1)].into()); + sel.anchors.insert(h, [(0, 0)].into()); + sel.segments.insert(elsewhere, [(0, 0)].into()); + Ok(()) + }) + .unwrap(); + (h, alone, compound, elsewhere) +} + +#[test] +fn the_selection_after_a_trim_is_the_one_changing_it_one_id_at_a_time_gives() { + // A removed key object stops being the key. + let mut s = session(); + let (h, alone, compound, elsewhere) = trim_scene(&mut s); + s.edit("key", |_, sel| { + sel.key = Some(alone); + Ok(()) + }) + .unwrap(); + let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 90, 20, 120]})); + assert_eq!(sel.key, None); + assert!(!sel.contains(alone) && !sel.contains(compound)); + assert_eq!(&sel.objects[..2], [elsewhere, h]); + assert_eq!(sel.objects.len(), 3, "{:?}", sel.objects); + assert!(sel.anchors.contains_key(&elsewhere) && sel.segments.contains_key(&elsewhere) && !sel.anchors.contains_key(&h)); + // A key object that keeps its first piece stays the key. + let mut s = session(); + let (h, alone, compound, _) = trim_scene(&mut s); + s.edit("key", |_, sel| { + sel.key = Some(h); + Ok(()) + }) + .unwrap(); + let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 90, 20, 120]})); + assert_eq!(sel.key, Some(h)); + assert!(!sel.contains(alone) && !sel.contains(compound)); + // Trimming only paths that are not selected leaves a targeted object targeted. + let mut s = session(); + let (h, _, _, elsewhere) = trim_scene(&mut s); + s.execute("select.set", &json!({"ids": [elsewhere.0]})).unwrap(); + s.edit("target", |_, sel| { + sel.target = Some(elsewhere); + Ok(()) + }) + .unwrap(); + let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 90, 20, 40]})); + assert_eq!((sel.objects.as_slice(), sel.target), ([elsewhere].as_slice(), Some(elsewhere))); + assert!(exists(&s, h)); + // A selected path that gains a piece changes the object selection, which lets go of the target. + let mut s = session(); + let (h, _, _, elsewhere) = trim_scene(&mut s); + s.execute("select.set", &json!({"ids": [elsewhere.0, h.0]})).unwrap(); + s.edit("target", |_, sel| { + sel.target = Some(elsewhere); + Ok(()) + }) + .unwrap(); + let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 90, 20, 40]})); + assert_eq!((sel.objects.len(), sel.target), (3, None)); + // So does a selected path that is removed whole. + let mut s = session(); + let (_, alone, _, elsewhere) = trim_scene(&mut s); + s.execute("select.set", &json!({"ids": [elsewhere.0, alone.0]})).unwrap(); + s.edit("target", |_, sel| { + sel.target = Some(elsewhere); + Ok(()) + }) + .unwrap(); + let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 190, 20, 20]})); + assert_eq!((sel.objects.as_slice(), sel.target), ([elsewhere].as_slice(), None)); +} + #[test] fn many_paths_far_from_the_trimmed_one_cost_no_crossing_search() { let mut s = session(); @@ -480,6 +614,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/addons/select.rs b/crates/engine/src/cmd/addons/select.rs index b2ab59d851..c9ae29a303 100644 --- a/crates/engine/src/cmd/addons/select.rs +++ b/crates/engine/src/cmd/addons/select.rs @@ -14,8 +14,9 @@ use vectorcraft_doc::{LockedArtboards, Node, NodeId, NodeKind}; use vectorcraft_geom::Point; use super::super::links::{Status, statuses}; +use super::super::panelcmds::listed_artboards; use super::super::select::{is_selectable, on_artboard, selectable}; -use super::super::{CommandSpec, bad, checked_ids_param, cmd, has_doc, point_indices, switch_or, text_param}; +use super::super::{CommandSpec, bad, checked_ids_param, cmd, has_doc, switch_or, text_param}; use crate::{DocState, Result, Session}; /// How Select by Artboards relates an object to the chosen artboards (`relation`). @@ -33,7 +34,7 @@ pub fn specs() -> Vec { "Select by Artboards", ["Object", "Plug-ins", "Selection Tools"], None, - "{artboards: [index…] (0-based, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}", + "{artboards: [index…] (0-based whole numbers, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}", has_doc, by_artboards ), @@ -58,13 +59,12 @@ fn by_artboards(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "`relation` must be overlap, inside or outside")); } let listed = p.get("artboards").ok_or_else(|| bad(C, "missing `artboards`"))?; - let indices = point_indices(listed).ok_or_else(|| bad(C, "`artboards` must be a list of artboard indices"))?; - if indices.is_empty() { + if listed.as_array().is_some_and(Vec::is_empty) { return Err(bad(C, "choose at least one artboard")); } let st = s.doc()?; - let rects = - indices.iter().map(|i| st.doc.artboards.get(*i).map(|a| a.rect)).collect::>>().ok_or_else(|| bad(C, "no such artboard"))?; + let rects: Vec<_> = + listed_artboards(&st.doc, listed, "artboards", C)?.into_iter().filter_map(|i| st.doc.artboards.get(i)).map(|a| a.rect).collect(); let symbols = st.doc.symbol_boxes(); let ids: Vec = selectable(&st.doc, st.isolation) .into_iter() diff --git a/crates/engine/src/cmd/addons/select/tests.rs b/crates/engine/src/cmd/addons/select/tests.rs index c97b278258..09106a3652 100644 --- a/crates/engine/src/cmd/addons/select/tests.rs +++ b/crates/engine/src/cmd/addons/select/tests.rs @@ -108,6 +108,35 @@ fn bad_params_are_errors_and_leave_the_selection() { } } +/// A malformed `artboards` entry is refused as one, naming the parameter, before any entry is +/// looked up; a value that is not a list, an empty list, a left-out list and a whole number past +/// the last artboard each have their own error. +#[test] +fn artboard_errors_say_what_is_wrong() { + let mut s = three_boards(); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + let entries = "invalid parameters for `addon.select.byArtboards`: `artboards` must contain whole numbers"; + let not_a_list = "invalid parameters for `addon.select.byArtboards`: `artboards` must be a list of artboard indices"; + for (p, want) in [ + (json!({"artboards": ["1"]}), entries), + (json!({"artboards": [-1]}), entries), + (json!({"artboards": [1.5]}), entries), + (json!({"artboards": [true]}), entries), + (json!({"artboards": [9, "1"]}), entries), + (json!({"artboards": "0"}), not_a_list), + (json!({"artboards": null}), not_a_list), + (json!({"artboards": []}), "invalid parameters for `addon.select.byArtboards`: choose at least one artboard"), + (json!({}), "invalid parameters for `addon.select.byArtboards`: missing `artboards`"), + (json!({"artboards": [9]}), "no such artboard"), + (json!({"artboards": [0, 9]}), "no such artboard"), + ] { + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + assert_eq!(s.execute(C, &p).unwrap_err().to_string(), want, "{p}"); + assert_eq!(s.doc().unwrap().selection.objects, vec![a], "{p}"); + } + assert_eq!(pick(&mut s, json!({"artboards": [0, 0]})), vec![a]); +} + #[test] fn a_symbol_instance_is_measured_by_its_art() { // The symbol's art, (100, 60) to (140, 80), drawn 50 pt up and left: (50, 10) to (90, 30), on diff --git a/crates/engine/src/cmd/addons/typetools.rs b/crates/engine/src/cmd/addons/typetools.rs index 10a00b1b45..d0c5447c42 100644 --- a/crates/engine/src/cmd/addons/typetools.rs +++ b/crates/engine/src/cmd/addons/typetools.rs @@ -61,7 +61,7 @@ pub fn specs() -> Vec { "Release Type on a Path…", ["Object", "Plug-ins", "Type Tools"], None, - "{mode?: \"both\" (point type and the path) | \"path\" (the path only) | \"text\" (point type only) (\"both\"), keepOriginal?: false (true: the type on a path stays and the released objects go just above it), ids?: [id…], id? (instead of ids; neither: the selection)} split each type on a path among the objects (inside groups too) into point type and the path it was set on. The point type holds the same text with the same character and paragraph attributes, on one straight line whose baseline starts where the first character sat on the path; Type on a Path Options (effect, align to path, spacing, flip, brackets) don't apply to point type and are dropped; type with Dynamic Text on (type.dynamicText) comes out with it off, at the sizes it was drawn at. The path keeps its exact shape (open or closed, anchors and handles, the object's transform) and comes out with no fill and no stroke, in the type's layer and place in the stacking order. Other objects are left alone, and with no type on a path among them nothing changes and no undo step is made. One undo step; the released objects are selected → {ids (released, bottom to top), paths, texts}", + "{mode?: \"both\" (point type and the path) | \"path\" (the path only) | \"text\" (point type only) (\"both\"), keepOriginal?: false (true: the type on a path stays and the released objects go just above it), ids?: [id…], id? (instead of ids; neither: the selection)} split each type on a path among the objects (inside groups too) into point type and the path it was set on. The point type holds the same text with the same character and paragraph attributes, on one straight line whose baseline starts where the first character sat on the path (when the type starts before an open path's start, the first character drawn on the path stays where it was drawn and the characters that were not drawn come before it); Type on a Path Options (effect, align to path, spacing, flip, brackets) don't apply to point type and are dropped; type with Dynamic Text on (type.dynamicText) comes out with it off, at the sizes it was drawn at. The path keeps its exact shape (open or closed, anchors and handles, the object's transform) and comes out with no fill and no stroke, in the type's layer and place in the stacking order. Other objects are left alone, and with no type on a path among them nothing changes and no undo step is made. One undo step; the released objects are selected → {ids (released, bottom to top), paths, texts}", has_selection, release_path ), @@ -229,6 +229,28 @@ fn first_pen(lay: &vectorcraft_text::TextLayout) -> Option { lay.glyphs.iter().filter(|g| g.origin.x.is_finite() && g.origin.y.is_finite()).min_by_key(|g| (g.byte, g.len != 0)).map(|g| g.origin) } +/// A glyph of a character: its byte, whether it stands for characters (a list marker does not), +/// and its place among the glyphs of that byte and kind (an All Caps ß is two glyphs). +type GlyphKey = (usize, bool, usize); + +/// The key and pen position of the first glyph drawn in `lay`, in text order: characters before an +/// open path's start are not drawn ([`vectorcraft_text::PositionedGlyph::off_path`]). None without +/// a drawn glyph. +fn first_drawn_pen(lay: &vectorcraft_text::TextLayout) -> Option<(GlyphKey, Point)> { + let (gi, g) = (lay.glyphs.iter().enumerate()) + .filter(|(_, g)| !g.off_path && g.origin.x.is_finite() && g.origin.y.is_finite()) + .min_by_key(|(gi, g)| (g.byte, g.len != 0, *gi))?; + let kind = g.len != 0; + let nth = lay.glyphs.iter().take(gi).filter(|h| h.byte == g.byte && (h.len != 0) == kind).count(); + Some(((g.byte, kind, nth), g.origin)) +} + +/// The pen position of the glyph `key` names in `lay`. None without one. +fn pen_at(lay: &vectorcraft_text::TextLayout, (byte, kind, nth): GlyphKey) -> Option { + let g = lay.glyphs.iter().filter(|g| g.byte == byte && (g.len != 0) == kind).nth(nth)?; + (g.origin.x.is_finite() && g.origin.y.is_finite()).then_some(g.origin) +} + /// `t`, type on a path, as point type on one straight line: the same runs and character and /// paragraph attributes, its baseline starting where its first character sat on the path (in the /// object's own text space, so its transform stays). Type on a Path Options are dropped, and @@ -237,13 +259,14 @@ fn first_pen(lay: &vectorcraft_text::TextLayout) -> Option { fn released_text(t: &TextObject) -> Option { let TextKind::OnPath { path, .. } = &t.kind else { return None }; let db = vectorcraft_text::FontDb::global(); - // Where the first character sat. Text that didn't fit on the path has no glyph there: it - // starts at the start bracket. - let at = first_pen(&vectorcraft_text::layout(db, t)).or_else(|| { + // Where the first drawn character sat; characters before an open path's start come before it + // on the line. Text that didn't fit on the path has no glyph there: it starts at the start + // bracket. + let (key, at) = first_drawn_pen(&vectorcraft_text::layout(db, t)).map(|(b, p)| (Some(b), p)).or_else(|| { let ap = ArcPath::new(path); let (from, _) = t.kind.path_span()?; let (p, _) = ap.at(from * ap.len()); - (p.x.is_finite() && p.y.is_finite()).then_some(p) + (p.x.is_finite() && p.y.is_finite()).then_some((None, p)) })?; let mut out = t.clone(); // Point type has no brackets to fit: it keeps the sizes the path drew it at. @@ -254,9 +277,10 @@ fn released_text(t: &TextObject) -> Option { out.path_spacing = 0.0; // Point type is in no thread: its first paragraph starts in it. out.first_para_continues = false; - // Where the point type puts its own first character; the origin moves so it lands at `at`, - // whatever the paragraph's alignment and direction. - let own = first_pen(&vectorcraft_text::layout(db, &out)).unwrap_or(Point::ZERO); + // Where the point type puts that glyph; the origin moves so it lands at `at`, whatever the + // paragraph's alignment and direction. + let own_lay = vectorcraft_text::layout(db, &out); + let own = key.and_then(|k| pen_at(&own_lay, k)).or_else(|| first_pen(&own_lay)).unwrap_or(Point::ZERO); let shift = at - own; if !(shift.x.is_finite() && shift.y.is_finite()) { return None; diff --git a/crates/engine/src/cmd/addons/typetools/tests.rs b/crates/engine/src/cmd/addons/typetools/tests.rs index e597525c97..a8518719be 100644 --- a/crates/engine/src/cmd/addons/typetools/tests.rs +++ b/crates/engine/src/cmd/addons/typetools/tests.rs @@ -482,6 +482,44 @@ mod release { } } + /// Type that starts before its open path: the first drawn character stays where it was drawn, + /// and the characters that were not drawn come before it on the line. + #[test] + fn type_starting_before_its_open_path_keeps_its_drawn_characters_in_place() { + let mut s = session(); + let id = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Hidden start"); + s.execute("type.pathOptions", &json!({"start": -0.05})).unwrap(); + let before = text(&s, id); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &before); + let first = lay.glyphs.iter().filter(|g| !g.off_path).min_by_key(|g| g.byte).unwrap(); + let (byte, drawn) = (first.byte, before.xf * first.origin); + assert!(byte > 0, "some characters are before the path"); + s.execute(C, &json!({"mode": "text"})).unwrap(); + let after = text(&s, id); + assert_eq!(after.kind, TextKind::Point); + assert_eq!(after.plain_text(), before.plain_text()); + let back = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &after); + let same = back.glyphs.iter().find(|g| g.byte == byte).unwrap(); + assert!(close(after.xf * same.origin, drawn), "{:?} vs {drawn:?}", after.xf * same.origin); + let lead = back.glyphs.iter().find(|g| g.byte == 0).unwrap(); + assert!((after.xf * lead.origin).x < drawn.x, "the hidden characters come before it"); + // An All Caps ß is two glyphs: with the first before the path's start, the second stays + // where it was drawn. + let id = path_type(&mut s, "M100 400 L500 400", [100.0, 400.0], "ße"); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 4, "allCaps": true})).unwrap(); + let adv = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(&s, id)).glyphs[0].advance; + s.execute("type.pathOptions", &json!({"start": -1.2 * adv / 400.0})).unwrap(); + let before = text(&s, id); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &before); + assert!(lay.glyphs[0].byte == 0 && lay.glyphs[1].byte == 0 && lay.glyphs[0].off_path && !lay.glyphs[1].off_path); + let drawn = before.xf * lay.glyphs[1].origin; + s.execute(C, &json!({"mode": "text"})).unwrap(); + let after = text(&s, id); + let back = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &after); + let second = back.glyphs.iter().filter(|g| g.byte == 0).nth(1).unwrap(); + assert!(close(after.xf * second.origin, drawn), "{:?} vs {drawn:?}", after.xf * second.origin); + } + #[test] fn flipped_type_releases_its_path_as_it_runs() { let mut s = session(); diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index bed4b33b76..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: 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: 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: 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: 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)} 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: 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)} 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: 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 ), @@ -102,7 +102,7 @@ pub fn specs() -> Vec { "Add Effect", [], None, - "{…as effect.apply} same as effect.apply (an alias): {effect: id, params?: {…}, item?: appearance item index|null, ids?, target?} → {ids, index, item}", + "{…as effect.apply} same as effect.apply (an alias): {effect: id, params?: {…}, item?: appearance item index|null, ids?, target?, aligned?} → {ids, index, item}", has_doc, super::effectcmd::apply ), @@ -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)} 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: 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)} 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: 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: 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: 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: 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 ), @@ -183,14 +183,21 @@ pub(crate) struct ActiveItem { impl Session { /// The method returns explicit target parameters and the selected appearance effect list. pub fn appearance_effect_target(&self, params: &Value) -> Option<(Value, &[vectorcraft_doc::Effect])> { - let mut ids = appearance_targets(self, params).ok()?; + let mut ids = drop_design_art(&self.active()?.doc, appearance_targets(self, params).ok()?); let item = item_target(self, params, "effect.apply").ok()?; let anchor = item.anchor(self, &ids); - let node = self.active()?.doc.node(*ids.get(anchor)?)?; + // Aligned effects given with a graph design's art first are effects of the art's stack, which stays first; the + // Appearance panel's active row is a row of the first selected object's. + let of = match item { + ItemTarget::Item { explicit: false, .. } => None, + _ => design_reference(self, params, "effect.apply").ok()?, + }; + let own = *ids.get(anchor)?; + let node = self.active()?.doc.node(of.unwrap_or(own))?; let at = item.effects_item(&node.appearance, "effect.apply").ok()?; let effects = node.appearance.effects_at(at)?; ids.swap(0, anchor); - let ids: Vec = ids.into_iter().map(|id| id.0).collect(); + let ids: Vec = with_reference(of, &ids).into_iter().map(|id| id.0).collect(); let aligned = match item { ItemTarget::Item { aligned, .. } => aligned, ItemTarget::Top => aligned(params, "effect.apply").ok()?, @@ -253,6 +260,10 @@ pub(crate) fn item_target_at(s: &Session, p: &Value, key: &str, cmd: &str) -> Re .ok_or_else(|| bad(cmd, format!("`{key}` must be an appearance item index (paint order) or null"))), // The active item is a row of the first selected object's own stack. None if p.get("ids").is_some() || p.get("id").is_some() || targets_contents(p)? => Ok(ItemTarget::Top), + // A row of a graph design's art in a series stands for nothing: the commands leave that art out. + None if s.active().and_then(|st| st.selection.subjects().first().map(|id| super::graph::is_design_art(&st.doc, *id))) == Some(true) => { + Ok(ItemTarget::Top) + } None => Ok(s.appearance_item().map_or(ItemTarget::Top, |index| ItemTarget::Item { index, explicit: false, aligned: true })), } } @@ -300,6 +311,21 @@ impl ItemTarget { .collect() } + /// [`ItemTarget::per_target`], with an explicit aligned item a row of the stack of `of` (see [`design_reference`]), + /// which is not among `ids`, when there is one: each target edits the item equal to it there, and a target without + /// an equal item is left out (`None`). + pub(crate) fn per_target_of(self, s: &Session, of: Option, ids: &[NodeId]) -> Vec> { + let ItemTarget::Item { index, explicit: true, aligned: true } = self else { return self.per_target(s, ids) }; + let Some(d) = s.active().map(|st| &st.doc) else { return self.per_target(s, ids) }; + let Some(r) = of.and_then(|of| d.node(of)) else { return self.per_target(s, ids) }; + ids.iter() + .map(|id| { + let index = SharedStack::of(&[&*r.appearance, &*d.node(*id)?.appearance]).item_in(index, 1)?; + Some(ItemTarget::Item { index, explicit: true, aligned: true }) + }) + .collect() + } + /// Where among `ids` (the targets, in paint order) the object whose stack this item is a row of /// is: the first selected object (or the compound path holding it) for the active item, which /// need not paint first; the first target otherwise, or when that object is not among them. @@ -384,8 +410,43 @@ pub(crate) fn items_per_target(d: &vectorcraft_doc::Document, ids: &[NodeId], id } } +/// The art of a graph design in a graph series whose stack the aligned rows of `p` (`aligned: true`) are rows of: the +/// first of the [`appearance_targets`] when it is such art, which the edit leaves out ([`without_design_art`]). A +/// command reads it after its own target checks. +pub(crate) fn design_reference(s: &Session, p: &Value, cmd: &str) -> Result> { + if !aligned(p, cmd)? { + return Ok(None); + } + let ids = appearance_targets(s, p)?; + let d = &s.doc()?.doc; + Ok(ids.first().copied().filter(|id| super::graph::is_design_art(d, *id))) +} + +/// The [`design_reference`] of an edit aimed at `item`: none for the Appearance panel's active row, which is a row of the +/// first selected object's stack. +pub(crate) fn reference_of(s: &Session, p: &Value, item: ItemTarget, cmd: &str) -> Result> { + if matches!(item, ItemTarget::Item { explicit: false, .. }) { + return Ok(None); + } + design_reference(s, p, cmd) +} + +/// `ids` after `of` (see [`design_reference`]), when there is one. +pub(crate) fn with_reference(of: Option, ids: &[NodeId]) -> Vec { + of.into_iter().chain(ids.iter().copied()).collect() +} + +/// [`items_per_target`] of `ids`, with the aligned rows `idx` taken from the stack of `of` (see [`design_reference`]) +/// when there is one: a row a target has no equal of is left out of that target. +pub(crate) fn rows_per_target(d: &Document, of: Option, ids: &[NodeId], idx: &[usize], aligned: bool) -> Vec> { + match of { + Some(of) => items_per_target(d, &with_reference(Some(of), ids), idx, true).into_iter().skip(1).collect(), + None => items_per_target(d, ids, idx, aligned), + } +} + /// 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() { @@ -424,24 +485,61 @@ const DESIGN_ART: &str = "the art of a graph design in a graph series is drawn a /// The [`appearance_targets`] whose rows and effects a command edits: the art of graph designs drawn in graph series /// ([`super::graph::is_design_art`]) is left out, as the graph draws it again from the design. A command whose targets -/// are all such art is refused. -pub(crate) fn edit_targets(s: &Session, p: &Value) -> Result> { +/// are all such art is refused as an error of `cmd`. +pub(crate) fn edit_targets(s: &Session, p: &Value, cmd: &str) -> Result> { let ids = appearance_targets(s, p)?; - without_design_art(&s.doc()?.doc, ids, "appearance") + without_design_art(&s.doc()?.doc, ids, cmd) } /// `ids` without the art of graph designs drawn in graph series; `cmd` is refused when `ids` held nothing else. -pub(crate) fn without_design_art(d: &Document, mut ids: Vec, cmd: &str) -> Result> { +pub(crate) fn without_design_art(d: &Document, ids: Vec, cmd: &str) -> Result> { let given = ids.len(); - ids.retain(|id| !super::graph::is_design_art(d, *id)); + let ids = drop_design_art(d, ids); if given > 0 && ids.is_empty() { return Err(bad(cmd, DESIGN_ART)); } Ok(ids) } +/// `ids` without the art of graph designs drawn in graph series, for the paint commands, which leave it out without an +/// error. +pub(crate) fn drop_design_art(d: &Document, mut ids: Vec) -> Vec { + ids.retain(|id| !super::graph::is_design_art(d, *id)); + 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 { + let mut out = vec![]; + for id in roots { + let Some(n) = d.node(*id) else { continue }; + n.walk(&mut |m| { + if m.extras().series_index.is_some() { + out.extend(m.children().into_iter().flatten().map(|c| c.id).filter(|c| super::graph::is_design_art(d, *c))); + } + }); + } + out +} + /// `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()) @@ -462,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) } @@ -476,15 +575,15 @@ pub(crate) fn look_holder<'a>(d: &'a Document, n: &'a Node) -> &'a Node { /// Objects whose fill and stroke rows a command edits: the [`edit_targets`], with a graph series group standing for the /// paths directly inside it ([`rowless_series_marks`]), so the graph can store the edit. -pub(crate) fn row_targets(s: &Session, p: &Value) -> Result> { - let ids = edit_targets(s, p)?; +pub(crate) fn row_targets(s: &Session, p: &Value, cmd: &str) -> Result> { + let ids = edit_targets(s, p, cmd)?; Ok(rowless_series_marks(&s.doc()?.doc, &ids)) } /// Objects whose whole appearance a command edits: the [`row_targets`], then each graph series group they stand for, /// which can hold effects and a graphic style link of its own. -pub(crate) fn whole_targets(s: &Session, p: &Value) -> Result> { - let own = edit_targets(s, p)?; +pub(crate) fn whole_targets(s: &Session, p: &Value, cmd: &str) -> Result> { + let own = edit_targets(s, p, cmd)?; let mut ids = rowless_series_marks(&s.doc()?.doc, &own); let groups = stood_for(&own, &ids); ids.extend(groups); @@ -498,8 +597,9 @@ pub(crate) fn stood_for(own: &[NodeId], ids: &[NodeId]) -> Vec { } /// Clear Appearance on each series group a command gave a whole new appearance through its paths, so the group's own -/// opacity, blend mode, isolation, knockout, effects and style link do not stay on top of it. -pub(crate) fn clear_stood_for(d: &mut Document, groups: &[NodeId]) { +/// opacity, blend mode, isolation, knockout, effects and style link do not stay on top of it. The graph stops keeping the +/// groups' opacity, blend mode, isolation and knockout. Returns whether what a graph keeps changed. +pub(crate) fn clear_stood_for(d: &mut Document, groups: &[NodeId]) -> bool { for id in groups { if let Some(n) = d.node_mut(*id) { clear(n); @@ -507,11 +607,12 @@ pub(crate) fn clear_stood_for(d: &mut Document, groups: &[NodeId]) { n.extras_mut().graphic_style = None; } } + super::graph::capture_series_object_opacity(d, groups) } /// [`whole_targets`] of `cmd`, which needs at least one. fn require_whole_targets(s: &Session, p: &Value, cmd: &str) -> Result> { - let ids = whole_targets(s, p)?; + let ids = whole_targets(s, p, cmd)?; if ids.is_empty() { return Err(bad(cmd, "select objects or give ids")); } @@ -520,28 +621,79 @@ fn require_whole_targets(s: &Session, p: &Value, cmd: &str) -> Result Result> { - let ids = row_targets(s, p)?; + let ids = row_targets(s, p, cmd)?; if ids.is_empty() { return Err(bad(cmd, "select objects or give ids")); } 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 is stored on -/// their graphs in the same step ([`capture_series_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. +/// 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`]), 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. +/// +/// With `of` (see [`reference_of`]), an explicit aligned `item` is a row of the stack of `of`, which +/// is not among `ids`: it must be there and of the edited kind, each target edits the row equal to +/// it, a target without one is left as it is, and no target with one is an error. Returns the +/// targets `f` was aimed at, in the order of `ids`. +#[allow(clippy::too_many_arguments)] pub(crate) fn edit_items( s: &mut Session, ids: &[NodeId], item: ItemTarget, + of: Option, cmd: &str, label: &str, fill: bool, f: impl FnMut(&mut Node, Option) -> Result<()>, -) -> Result<()> { - edit_items_then(s, ids, item, cmd, label, fill, f, |before, d, edited| Ok(capture_series_changes(before, d, edited))) +) -> Result> { + 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, None); + Ok(series || labels) + }) } /// [`edit_items`], then `after` on the document as it was before the edit, the edited document and @@ -553,21 +705,76 @@ pub(crate) fn edit_items_then( s: &mut Session, ids: &[NodeId], item: ItemTarget, + of: Option, 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<()> { - if ids.is_empty() { - return Ok(()); - } +) -> Result> { + let art = of.and_then(|of| s.doc().ok()?.doc.node(of).map(|n| n.appearance.clone())); + let per = match (item, art) { + // Checked even when the art is the only object given, which leaves `ids` empty. + (ItemTarget::Item { index, explicit: true, aligned: true }, Some(art)) => { + item.resolve(&art, fill, cmd)?; + let per = item.per_target_of(s, of, ids); + if per.iter().all(Option::is_none) { + return Err(bad(cmd, format!("no appearance item {index}"))); + } + per + } + _ if ids.is_empty() => return Ok(Vec::new()), + _ => item.per_target(s, ids), + }; + let aimed: Vec = ids.iter().zip(&per).filter(|(_, item)| item.is_some()).map(|(id, _)| *id).collect(); let before = s.doc()?.doc.clone(); - let per = item.per_target(s, ids); super::overprint::edit_counted(s, label, |d| { 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 }; @@ -577,12 +784,41 @@ 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(()) + Ok(aimed) +} + +/// The first of `ids` that [`edit_items`] aimed at `item` with `of` changes, and the item it changes there. Read it +/// before the edit: once edited, a row that was equal to a row of the art of `of` no longer is. +pub(crate) fn first_edited(s: &Session, item: ItemTarget, of: Option, ids: &[NodeId]) -> Option<(NodeId, ItemTarget)> { + 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`. @@ -591,17 +827,26 @@ pub(crate) fn count_changed(d: &vectorcraft_doc::Document, before: &vectorcraft_ } /// Whether an edit aimed at `item` changes a stroke: the `stroke` param, else the kind of the -/// targeted item (on the object whose row it is, see [`ItemTarget::anchor`]), else `default`. A `stroke` other than true, false or -/// null is an error of command `cmd`. +/// targeted item (on the object whose row it is, see [`ItemTarget::anchor`] and [`reference_of`]), else `default`. A `stroke` other than +/// true, false or null is an error of command `cmd`. pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bool, cmd: &str) -> Result { check_switches(p, &["stroke"], cmd)?; if let Some(b) = p.get("stroke").and_then(Value::as_bool) { return Ok(b); } let ItemTarget::Item { index, .. } = item else { return Ok(default) }; - let ids = appearance_targets(s, p)?; let d = &s.doc()?.doc; - Ok(ids.get(item.anchor(s, &ids)).and_then(|id| d.node(*id)?.appearance.items.get(index)).map_or(default, |it| !it.is_fill())) + let holder = match reference_of(s, p, item, cmd)? { + Some(of) => Some(of), + None => { + 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() + } + }; + Ok(holder.and_then(|id| d.node(id)?.appearance.items.get(index)).map_or(default, |it| !it.is_fill())) } /// The whole number of 0 or more that `key` holds, read with [`u64_req`] and [`index`]. @@ -714,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 @@ -906,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); } @@ -936,7 +1184,7 @@ fn transfer(s: &mut Session, p: &Value) -> Result { (src.opacity, src.blend, src.isolate, src.knockout, src.knockout_shape); super::object::snap_if_aligned(to); } - clear_stood_for(d, &group); + let forgot = clear_stood_for(d, &group); for id in &cleared { if let Some(n) = d.node_mut(*id) { clear(n); @@ -951,10 +1199,11 @@ 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)) + Ok(count_changed(d, &before, &all) + usize::from(kept || painted || object || labels || forgot)) })?; s.active_appearance_item = None; Ok(json!({ "source": source.0, "target": target.0 })) @@ -1010,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; @@ -1023,17 +1272,22 @@ fn set_item(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["weight", "opacity"], "appearance.setItem")?; check_switches(p, &["visible"], "appearance.setItem")?; let paint = paint_from(s, p)?; - let ids = row_targets(s, p)?; + let ids = row_targets(s, p, "appearance.setItem")?; 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. let before = s.doc()?.doc.clone(); - let per = items_per_target(&before, &ids, &[idx], aligned(p, "appearance.setItem")?); + let of = design_reference(s, p, "appearance.setItem")?; + 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 }; @@ -1044,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) => { @@ -1086,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); @@ -1115,13 +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 per = items_per_target(&before, &ids, &idx, aligned(p, "appearance.removeItem")?); + 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. @@ -1133,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`. @@ -1153,23 +1426,33 @@ 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. let mut first_at = None; let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied()); let mut active_at = None; - // Aligned rows of a mixed selection are copied right above themselves in each object. - if aligned(p, C)? && to.is_some() && shared_stack(&s.doc()?.doc, &ids).is_some() { + // Aligned rows of a mixed selection are copied right above themselves in each object. Rows of a graph design's art, + // which is left out, go to `to` in an object whose stack is the same as the art's. + let of = design_reference(s, p, C)?; + if aligned(p, C)? + && to.is_some() + && (shared_stack(&s.doc()?.doc, &ids).is_some() || (of.is_some() && appearances_differ(&s.doc()?.doc, &with_reference(of, &ids)))) + { return Err(bad(C, "`to` takes the rows of one object's stack, not aligned rows")); } let before = s.doc()?.doc.clone(); - let per = items_per_target(&before, &ids, &idx, aligned(p, C)?); + // With `to`, the art's stack is the same as the object's, so its rows are the object's, each of which must exist. + let per = + if to.is_some() { items_per_target(&before, &ids, &idx, aligned(p, C)?) } else { rows_per_target(&before, of, &ids, &idx, aligned(p, C)?) }; s.edit("Duplicate Item", |d, _| { let mut any = false; // 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(); @@ -1194,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(); @@ -1208,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); + } } } } @@ -1216,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`). @@ -1258,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::>() })) @@ -1271,15 +1559,20 @@ fn move_item(s: &mut Session, p: &Value) -> Result { let aligned = aligned(p, C)?; if p.get("from").and_then(Value::as_str) == Some("contents") { // A graph series group's own Contents row, not its paths, which have none. - let ids = edit_targets(s, p)?; + let ids = edit_targets(s, p, C)?; if ids.is_empty() { return Err(bad(C, "select objects or give ids")); } + // The Contents row's place counts the rows below it, which isn't one place in several different stacks either. + 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")); + } 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, &ids) { + 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")); } if p.get("indices").is_some() { @@ -1304,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. @@ -1350,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 })) @@ -1651,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/artboardalign.rs b/crates/engine/src/cmd/artboardalign.rs index 541ec94a4e..a3e585a8a0 100644 --- a/crates/engine/src/cmd/artboardalign.rs +++ b/crates/engine/src/cmd/artboardalign.rs @@ -6,8 +6,8 @@ use vectorcraft_doc::Scaling; use vectorcraft_geom::{Rect, Vec2}; use super::object::choice; -use super::panelcmds::{artboard_index, artboards_art, locked_and_hidden, named_or_selected, note_artboards}; -use super::{Affine, CommandSpec, NodeId, Result, Session, bad, check_switches, cmd, has_doc, switch_or}; +use super::panelcmds::{artboard_at, artboards_art, locked_and_hidden, named_or_selected, note_artboards, on_board}; +use super::{Affine, CommandSpec, NodeId, Result, Session, bad, check_switches, cmd, has_doc, index, switch_or}; use crate::EngineError; pub fn specs() -> Vec { @@ -63,13 +63,7 @@ fn boards(s: &mut Session, p: &Value, cmd: &str) -> Result { check_switches(p, &["patterns"], cmd)?; let to_artboard = choice(p, cmd, "to", &["selection", "artboard"])? == Some("artboard"); let indices = named_or_selected(s, p, cmd)?; - let given = |key: &str| -> Result> { - match p.get(key).filter(|v| !v.is_null()) { - Some(v) => artboard_index(&s.doc()?.doc, &json!({ "index": v }), cmd).map(Some), - None => Ok(None), - } - }; - let (named, recorded) = (given("artboard")?, given("activeArtboard")?); + let (named, recorded) = (artboard_at(&s.doc()?.doc, p, "artboard", cmd)?, artboard_at(&s.doc()?.doc, p, "activeArtboard", cmd)?); let move_art = switch_or(p, "moveArt", s.tool_options_of("artboard")["moveArt"].as_bool().unwrap_or(true), cmd)?; let locked_art = locked_and_hidden(s, p, move_art, cmd)?; note_artboards(s, p, &indices); @@ -78,8 +72,8 @@ fn boards(s: &mut Session, p: &Value, cmd: &str) -> Result { (false, _) => None, (true, Some(i)) => Some(i), (true, None) => { - let active = s.tool_options_of("artboard")["active"].clone(); - Some(artboard_index(&s.doc()?.doc, &json!({ "index": active }), cmd)?) + let active = s.tool_options_of("artboard")["active"].as_u64().map(index); + Some(active.map_or_else(|| Err(EngineError::Other("no such artboard".into())), |i| on_board(&s.doc()?.doc, i))?) } }; if let Some(i) = reference.filter(|_| named.is_none()) { diff --git a/crates/engine/src/cmd/assets.rs b/crates/engine/src/cmd/assets.rs index e30e6efcdc..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 ), @@ -89,7 +89,7 @@ pub fn specs() -> Vec { "Asset Export Settings", [], None, - "{exportPreset?: (a preset of document.exportPresets.list: its formats or preset, its format settings over the saved ones, its prefix (none when it has none), its folders (or subfolders: rows or none) with subfolders on for rows, and antiAlias; the other keys go over it), formats?, preset?: mobile|density|\"\" (none), settings?, prefix?, subfolders?, antiAlias?} change the export settings the Asset Export panel and Export for Screens share (document.exportSettings; the values of document.exportForScreens; null removes one): formats replace a preset, a preset replaces the formats → {settings}. Not an undo step", + "{exportPreset?: (a preset of document.exportPresets.list: its formats or preset, its format settings over the saved ones, its prefix (none when it has none), its folders (or subfolders: rows or none) with subfolders on for rows, and antiAlias; the other keys go over it), formats?, preset?: mobile|density|\"\" (none), settings?, prefix?, subfolders?: true|false (Create Sub-folders: true sorts the files into a folder per row; false puts assets.export's files in the folder itself and, given without exportPreset, sets a remembered folder per format or item to none as well), antiAlias?, openLocation?: true|false (Open Location after Export: remembered in document.exportSettings, not in presets or the reply; given alone to a document without settings, Create Sub-folders stays on)} change the export settings the Asset Export panel and Export for Screens share (document.exportSettings; the values of document.exportForScreens; null removes one): formats replace a preset, a preset replaces the formats → {settings}. Not an undo step", has_doc, settings_set ), @@ -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)")); } @@ -435,19 +461,35 @@ fn export(s: &mut Session, p: &Value) -> Result { fn settings_set(s: &mut Session, p: &Value) -> Result { const C: &str = "assets.settings.set"; let o = p.as_object().ok_or_else(|| bad(C, "give the settings to change, e.g. {\"formats\": [{\"format\": \"png\", \"scale\": \"2x\"}]}"))?; - if let Some(k) = o.keys().find(|k| !SCREEN_SETTINGS_KEYS.contains(&k.as_str()) && k.as_str() != "exportPreset") { - return Err(bad(C, format!("`{k}` isn't an export setting: {}", SCREEN_SETTINGS_KEYS.join(", ")))); + if let Some(k) = o.keys().find(|k| !SCREEN_SETTINGS_KEYS.contains(&k.as_str()) && !matches!(k.as_str(), "exportPreset" | "openLocation")) { + return Err(bad(C, format!("`{k}` isn't an export setting: {}, openLocation", SCREEN_SETTINGS_KEYS.join(", ")))); + } + for k in ["subfolders", "openLocation"] { + if o.get(k).is_some_and(|v| !v.is_boolean() && !v.is_null()) { + return Err(bad(C, format!("`{k}` is true or false"))); + } } let mut settings = s.doc()?.doc.export_settings.clone(); let mut given = o.clone(); + // Create Sub-folders is on for a document without settings (Export for Screens opens so), and + // Open Location after Export set on its own leaves it on. + if settings.is_empty() && o.len() == 1 && o.get("openLocation").is_some_and(Value::is_boolean) { + given.insert("subfolders".into(), json!(true)); + } if let Some(name) = given.remove("exportPreset") { let name = name.as_str().ok_or_else(|| bad(C, "`exportPreset` is the name of a preset of document.exportPresets.list"))?; with_screen_export_preset(s, C, &mut settings, name)?; } // Create Sub-folders is Export for Screens' folder per row: the dialog opens on the choice. + // Turned off on its own (the panel menu), it also ends a remembered folder per format or item; + // with an export preset, that preset's folder per format or item stays. + let folders = settings.get("folders").and_then(Value::as_str).map(str::to_string); + let sorted = folders.as_deref().is_some_and(|f| f != "none"); match given.get("subfolders").and_then(Value::as_bool) { Some(true) => _ = settings.insert("folders".into(), json!("rows")), - Some(false) if settings.get("folders").and_then(Value::as_str) == Some("rows") => _ = settings.insert("folders".into(), json!("none")), + Some(false) if folders.as_deref() == Some("rows") || (sorted && !o.contains_key("exportPreset")) => { + _ = settings.insert("folders".into(), json!("none")) + } _ => {} } overlay(&mut settings, &given); diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index 16ab1c76d4..34becd7c02 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -178,6 +178,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[ BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails }, BuiltinBrushLibrary { id: "energy-beams", name: "Energy Beams", make: energy_beams }, BuiltinBrushLibrary { id: "dry-media", name: "Dry Media", make: dry_media }, + BuiltinBrushLibrary { id: "tech-circuit", name: "Tech Circuit", make: tech_circuit }, ]; /// Built-in library `id`, made once. @@ -397,6 +398,59 @@ fn border(name: &str, side: Node, corner: Option, fit: PatternFit) -> Brus Brush { name: name.into(), kind } } +/// Tech Circuit: original conductor geometry, drawn as filled paths so widths and chamfers +/// survive brush warping. Pattern tiles meet at x = 0 and 24 with identical lead cross-sections. +fn tech_circuit() -> BrushLibrary { + let pad = |x: f64| { + black(polygon(&[ + (x - 4.0, -2.0), + (x - 2.0, -4.0), + (x + 2.0, -4.0), + (x + 4.0, -2.0), + (x + 4.0, 2.0), + (x + 2.0, 4.0), + (x - 2.0, 4.0), + (x - 4.0, 2.0), + ])) + }; + // 45-degree jogs lift the conductor to a parallel run and bring it back. + let trace = group(vec![ + black(polygon(&[ + (4.0, -1.0), + (23.0, -1.0), + (33.0, -11.0), + (61.0, -11.0), + (71.0, -1.0), + (96.0, -1.0), + (96.0, 1.0), + (70.0, 1.0), + (60.0, -9.0), + (34.0, -9.0), + (24.0, 1.0), + (4.0, 1.0), + ])), + pad(4.0), + pad(96.0), + ]); + let bus = group([-4.0, 0.0, 4.0].into_iter().map(|y| black(shapes::rectangle(Rect::new(0.0, y - 0.75, 24.0, y + 0.75)))).collect()); + let terminals = group(vec![ + // Overlap the ring's rim without filling the test point's hole. + black(shapes::rectangle(Rect::new(0.0, -0.6, 15.5, 0.6))), + black(shapes::rectangle(Rect::new(18.5, -0.6, 24.0, 0.6))), + pad(6.0), + ring(Point::new(17.0, 0.0), 3.0, 1.4), + ]); + built( + "Tech Circuit", + Document::new(100.0, 100.0), + vec![ + art("Circuit Trace", trace, Colorization::Tints), + border("Bus Lines", bus, None, PatternFit::Stretch), + border("Terminal Nodes", terminals, None, PatternFit::Stretch), + ], + ) +} + /// An invisible rectangle that fixes a tile's width. fn spacer(r: Rect) -> Node { Node::path(NodeId(0), shapes::rectangle(r), Appearance::default()) diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 32b0f9fcd0..c4f35dfc3f 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -19,14 +19,17 @@ use super::edit::{outermost, selected_roots}; use super::pathops::{remove_each, separate}; use super::swatch::{anchor, names_param}; use super::{ - CommandSpec, Result, Session, bad, check_numbers, cmd, color_param, find_command, has_doc, has_selection, id_param, named_ids, number_or, ok, - str_param, switch_or, + CommandSpec, Result, Session, bad, check_numbers, cmd, color_param, find_command, has_doc, has_selection, named_ids, number_or, ok, str_param, + switch_or, }; 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; @@ -180,7 +183,7 @@ pub fn specs() -> Vec { "Paintbrush", [], None, - "{…params as path.freehand, brush} paint a freehand stroke with a brush → {id}", + "{…params as path.freehand, brush?: name} paint a freehand stroke with a brush; without `brush` (or with null) the plain path is drawn; a `brush` that names no brush in the document, a `style` other than \"pencil\" or \"brush\", a `brush` for a path with no stroke (a continued or redrawn path without one, or a new filled \"pencil\" path while the stroke is None) and an unknown key are errors and nothing is drawn; the path and its brush are one undo step → {id}", has_doc, brush_freehand ), @@ -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/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index 1f63076cfd..7a92ff130a 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -1,20 +1,20 @@ use super::{ AppearanceItem, Arc, BTreeSet, Bristle, Brush, BrushKind, Color, Document, EngineError, Node, NodeId, NodeKind, Paint, Result, Session, Value, - anchor, bad, brush, check_numbers, find_command, id_param, ids_json, json, name_param, names_param, ok, roots, selection_art, set_unknown, - str_param, + anchor, bad, brush, check_numbers, find_command, ids_json, json, name_param, names_param, ok, roots, selection_art, set_unknown, str_param, }; // ---------- brushes ---------- -/// Brushable nodes (paths and compound paths) under `ids`. +/// Brushable nodes (paths and compound paths) under `ids`, in walk order, each listed once where it is first reached. pub(crate) fn brush_targets(d: &Document, ids: &[NodeId]) -> Vec { let mut out = vec![]; + let mut seen = std::collections::HashSet::new(); for id in ids { let Some(n) = d.node(*id) else { continue }; n.walk(&mut |c| { let own = matches!(c.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }); let in_compound = d.parent_of(c.id).and_then(|p| d.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. })); - if own && !in_compound && !out.contains(&c.id) { + if own && !in_compound && seen.insert(c.id) { out.push(c.id); } }); @@ -729,16 +729,112 @@ pub(super) fn expand_brush(s: &mut Session, p: &Value) -> Result { Ok(json!({ "ids": ids_json(&out) })) } +/// Paints a `path.freehand` stroke with the brush `brush` names, in one undo step with the path. +/// A `brush` left out or null draws the plain path; a `brush` that is not a string or names no +/// brush in the document, a `style` other than "pencil" or "brush", and a `brush` for a path with +/// no stroke are errors before anything is drawn. pub(super) fn brush_freehand(s: &mut Session, p: &Value) -> Result { - let name = str_param(p, "brush").map(str::to_string).filter(|n| s.doc().is_ok_and(|st| brush::find(&st.doc, n).is_some())); + const C: &str = "brush.freehand"; + let name = match crate::cmd::text_param(p, "brush", C)? { + None => None, + Some(n) if brush::find(&s.doc()?.doc, n).is_some() => Some(n.to_string()), + Some(n) => return Err(bad(C, format!("no brush named `{n}`"))), + }; + match p.get("style") { + None | Some(Value::Null) => {} + Some(v) if matches!(v.as_str(), Some("pencil" | "brush")) => {} + Some(v) => return Err(bad(C, format!("`style` must be \"pencil\" or \"brush\", not {v}"))), + } let spec = find_command("path.freehand").ok_or_else(|| EngineError::UnknownCommand("path.freehand".into()))?; - let r = crate::cmd::run_checked(s, spec, p)?; - let (Some(name), Some(id)) = (name, id_param(&r, "id")) else { return Ok(r) }; - s.edit("Paintbrush", |d, _| { - if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) { - st.brush = Some(name.clone()); - } - Ok(()) - })?; - Ok(r) + let checked = crate::schemas::check(spec, p, s.replaying())?; + crate::cmd::draw2::freehand_brushed(s, checked.as_ref().unwrap_or(p), name.as_deref()) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_doc::Appearance; + use vectorcraft_geom::PathData; + + /// The collector with a linear search of its output, kept to compare results with. + fn listed_targets(d: &Document, ids: &[NodeId]) -> Vec { + let mut out = vec![]; + for id in ids { + let Some(n) = d.node(*id) else { continue }; + n.walk(&mut |c| { + let own = matches!(c.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }); + let in_compound = d.parent_of(c.id).and_then(|p| d.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. })); + if own && !in_compound && !out.contains(&c.id) { + out.push(c.id); + } + }); + } + out + } + + fn path(d: &mut Document) -> Node { + Node::path(d.alloc_id(), PathData::default(), Appearance::default()) + } + + fn compound(d: &mut Document, children: Vec) -> Node { + Node::new(d.alloc_id(), NodeKind::Compound { children: children.into_iter().map(Arc::new).collect(), rule: Default::default() }) + } + + fn add(d: &mut Document, node: Node) -> NodeId { + let layer = d.layers.first().map(|l| l.id); + d.insert(layer, usize::MAX, node).unwrap() + } + + #[test] + fn brush_targets_list_each_target_once_in_first_reached_order() { + let mut d = Document::new(400.0, 300.0); + let a = path(&mut d); + let a = add(&mut d, a); + let mut guide = path(&mut d); + if let NodeKind::Path { guide: g, .. } = &mut guide.kind { + *g = true; + } + let guide = add(&mut d, guide); + let mut clip = path(&mut d); + if let NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + let clip = add(&mut d, clip); + // A group holding a path and a compound path of two members. + let p1 = path(&mut d); + let p1_id = p1.id; + let (m1, m2) = (path(&mut d), path(&mut d)); + let m1_id = m1.id; + let cp1 = compound(&mut d, vec![m1, m2]); + let cp1_id = cp1.id; + let group = Node::group(d.alloc_id(), vec![Arc::new(p1), Arc::new(cp1)]); + let group = add(&mut d, group); + // A compound path holding a compound path. + let m3 = path(&mut d); + let cp3 = compound(&mut d, vec![m3]); + let cp3_id = cp3.id; + let cp2 = compound(&mut d, vec![cp3]); + let cp2 = add(&mut d, cp2); + + let ids = [cp1_id, a, group, p1_id, a, guide, clip, m1_id, cp2, cp3_id, NodeId(u64::MAX)]; + let got = brush_targets(&d, &ids); + assert_eq!(got, [cp1_id, a, p1_id, cp2], "repeats keep their first place; guides, clipping paths and compound members are left out"); + assert_eq!(got, listed_targets(&d, &ids)); + assert!(brush_targets(&d, &[]).is_empty()); + + // Many paths in groups, each group listed with some of its members. + let mut ids = vec![]; + for _ in 0..50 { + let members: Vec = (0..20).map(|_| path(&mut d)).collect(); + let member_ids: Vec = members.iter().map(|m| m.id).collect(); + let g = Node::group(d.alloc_id(), members.into_iter().map(Arc::new).collect()); + let g = add(&mut d, g); + ids.push(member_ids[7]); + ids.push(g); + ids.push(member_ids[3]); + } + let got = brush_targets(&d, &ids); + assert_eq!(got.len(), 50 * 20); + assert_eq!(got, listed_targets(&d, &ids)); + } } 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 3fc5953619..39dc0db8a2 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -14,7 +14,7 @@ use std::collections::{HashMap, HashSet}; use std::sync::Arc; use serde_json::{Value, json}; -use vectorcraft_color::{Color, Paint}; +use vectorcraft_color::{BlendMode, Color, Paint}; use vectorcraft_doc::appearance::{AppearanceItem, FillLayer, LineCap, LineJoin, StrokeLayer}; use vectorcraft_doc::{Appearance, Document, GapOptions, GapSize, LiveShape, Node, NodeId, NodeKind, Selection, TraceView}; use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath}; @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Shape Builder", [], None, - "{ids?|id?: [id…] (default: selection), points: [[x,y]…] (drag path; one point = click; may be left out with rect), rect?: [x, y, width, height] (Shift-drag marquee from where the drag started, x and y, to x+width and y+height; width and height may be negative: touches every region whose outline crosses the rectangle or has an anchor inside it and the region holding the whole rectangle, the region under x, y comes first and the one under the opposite corner comes next; with points, it also touches the regions along them; for pickColorFrom, x, y is the drag's first point and the opposite corner is its last), erase?: bool (erase mode, Alt: deletes the regions touched, and the pieces of open paths that cut regions and the edges (outline pieces between the points where paths meet; see shapeBuilder.regions) within tolerance, except that a point in a region no more than twice the tolerance across there touches the region; a deleted edge opens its path there, and edges bounding a deleted region go with it; what is left of each path keeps its look, with gradients fitted to its bounds kept where they were on it, its name, opacity mask and attributes, and its fill rule unless merged regions shaped it), splitStroke?: false (In Merge Mode, Clicking Stroke Splits the Path; not with erase or rect: when the one point of a click is within tolerance of a stroke, the path that stroke is on splits in two instead of a merge: the path keeps the rest of it, and a copy of the path holding the run of it from the anchor or crossing point before the click to the one after it, in the path's direction, goes directly above it; both keep the path's gradients where they were on it; the other objects stay as they are; with pickColorFrom \"swatches\" or fill, the run's stroke takes that paint; a path in a Live Paint group or a Shaper Group does not split, and nor does a path the run is all of, such as a lone line, or all but 0.05 pt or less of (a ten-thousandth of the larger side of a path over 500 pt)), tolerance?: pt (2, erase or splitStroke), gap?: pt (0–72; 0: Gap Detection off), openFilledAsClosed?: true (Consider Open Filled Paths as Closed: a filled open path bounds a region as if an invisible edge closed it; false: it cuts the regions it crosses like an unfilled one), pickColorFrom?: \"artwork\" (default: the merged shape takes the look of the front-most object under the first point, else under the last point, else of the front-most object) | \"swatches\" (the current fill, with the rest of the look of the front-most object over the first region the drag touches that an object covers, else of the front-most object), fill?: \"#rrggbb\" | {color|swatch|gradient|none} (overrides pickColorFrom)} replaces the paths it uses where they are; other selected objects (type, hidden or locked objects, clipping paths) stay, and a group goes only when it is left empty → {ids (selected after: each selected object still there, or what took its place), merged, regions, lines, edges (counts deleted, merged or split), split?: id (the run split off, after a split)}; after a split, ids are the roots, with the rest and the run in place of the path when it was one", + "{ids?|id?: [id…] (default: selection), points: [[x,y]…] (drag path; one point = click; may be left out with rect), rect?: [x, y, width, height] (Shift-drag marquee from where the drag started, x and y, to x+width and y+height; width and height may be negative: touches every region whose outline crosses the rectangle or has an anchor inside it and the region holding the whole rectangle, the region under x, y comes first and the one under the opposite corner comes next; with points, it also touches the regions along them; for pickColorFrom, x, y is the drag's first point and the opposite corner is its last), erase?: bool (erase mode, Alt: deletes the regions touched, and the pieces of open paths that cut regions and the edges (outline pieces between the points where paths meet; see shapeBuilder.regions) within tolerance, except that a point in a region no more than twice the tolerance across there touches the region; a deleted edge opens its path there, and edges bounding a deleted region go with it; what is left of each path keeps its look, with gradients fitted to its bounds kept where they were on it, its name, opacity mask and attributes, and its fill rule unless merged regions shaped it), splitStroke?: false (In Merge Mode, Clicking Stroke Splits the Path; not with erase or rect: when the one point of a click is within tolerance of a stroke, the path that stroke is on splits in two instead of a merge: the path keeps the rest of it, and a copy of the path holding the run of it from the anchor or crossing point before the click to the one after it, in the path's direction, goes directly above it; both keep the path's gradients where they were on it; the other objects stay as they are; with pickColorFrom \"swatches\" or fill, the run's stroke takes that paint; a path in a Live Paint group or a Shaper Group does not split, and nor does a path the run is all of, such as a lone line, or all but 0.05 pt or less of (a ten-thousandth of the larger side of a path over 500 pt)), tolerance?: pt (2, erase or splitStroke), gap?: pt (0–72; 0: Gap Detection off), openFilledAsClosed?: true (Consider Open Filled Paths as Closed: a filled open path bounds a region as if an invisible edge closed it, where filled means any fill row is shown, painted and above 0% opacity, whichever row is on top; false: it cuts the regions it crosses like an unfilled one), pickColorFrom?: \"artwork\" (default: the merged shape takes the look of the front-most object under the first point, else under the last point, else of the front-most object) | \"swatches\" (the current fill, with the rest of the look of the front-most object over the first region the drag touches that an object covers, else of the front-most object), fill?: \"#rrggbb\" | {color|swatch|gradient|none} (overrides pickColorFrom)} replaces the paths it uses where they are; other selected objects (type, hidden or locked objects, clipping paths) stay, and a group goes only when it is left empty → {ids (selected after: each selected object still there, or what took its place), merged, regions, lines, edges (counts deleted, merged or split), split?: id (the run split off, after a split)}; after a split, ids are the roots, with the rest and the run in place of the path when it was one", has_selection_or_ids, sb_merge ), @@ -72,7 +72,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Live Paint"], Some("Cmd+Alt+X"), - "{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with its front-most covering source's fill; with a Live Paint group among them, add the others to it as livePaint.merge does; a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step) → {id, faces, edges}", + "{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with the fill rows that draw (shown, with paint and an opacity above 0) of its front-most covering source that has one and an opacity above 0, and each edge with the stroke rows that draw (also a weight above 0) of its source, in order with their settings and with that source's opacity and blending mode (on a path cut into several edges, dashes go on along the path with the lengths set, without the fit of dashes aligned to corners and path ends, arrowheads stay at its own ends, and a width profile or brush stays only on an edge that runs the whole path); a face or edge given no such row has one unpainted row; with a Live Paint group among them, add the others to it as livePaint.merge does; a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step) → {id, faces, edges}", has_selection_or_ids, lp_make ), @@ -99,7 +99,7 @@ pub fn specs() -> Vec { "Expand", ["Object", "Live Paint"], None, - "{id?, ids?: [id…] (instead of id)} turn Live Paint groups into plain groups of their painted faces and edges → {ids}", + "{id?, ids?: [id…] (instead of id)} turn Live Paint groups into plain groups of the faces and edges that draw, with all their fill and stroke rows: a shown face or edge with an opacity above 0 and a shown fill or stroke row that has paint and an opacity above 0 (a stroke also a weight above 0), whichever row is on top → {ids}", has_selection_or_ids, lp_expand ), @@ -117,7 +117,7 @@ pub fn specs() -> Vec { "Live Paint Bucket", [], None, - "{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces; when every face it reaches already has the paint, nothing changes (no undo step, and the recent colors stay as they are) → {group, face}", + "{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), scope?: \"one\" (default: the face alone) | \"connected\" (a double-click: also each face reached across edges that are hidden or draw no stroke, as a flood from the face; a stroked edge, a hidden face or a Gap Detection gap stops it) | \"samePaint\" (a triple-click: also every face of the group whose fill is match; \"connected\" and \"samePaint\" are refused with points), match?: paint (as the document stores it, the `fill` of a face's appearance; scope samePaint only; default: the face's fill), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces: each face reached has its fills replaced by one fill with the paint, shown, fully opaque and blending normally, in the place of its topmost fill (none leaves one fill of none), and its strokes and its own opacity stay as they are; when every face it reaches already has only that one fill, nothing changes (no undo step, and the recent colors stay as they are) → {group, face, count (faces reached)}", has_doc, lp_fill ), @@ -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), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point; when it already has the paint and the width, nothing changes (no undo step, and the recent colors stay as they are) → {group, edge}", + "{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; also paints every edge of the group, hidden edges skipped, that the polyline crosses or comes within 0.0001 pt of), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match; \"connected\" and \"samePaint\" are refused with points), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), through?: [id…] (scope connected only; at most 4096 of the group's edges, each given once, counted as drawing with stroke paint match whatever they draw with, such as another edge a double-click's clicks painted; any other id is an error), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}", has_doc, lp_stroke_edge ), @@ -135,7 +135,7 @@ pub fn specs() -> Vec { "Live Paint Info", [], None, - "{group, id?: object id (default: the selection)} → {faces: [{id, fill, bounds}], edges: [{id, stroke, width}], sources, gapOptions: {detect, size: \"small\"|\"medium\"|\"large\"|pt, points, color: #rrggbb} (as livePaint.gapOptions sets them), gaps: [[x0,y0,x1,y1]…] (as livePaint.gapOptions returns them)}", + "{group?|id?: Live Paint group id (one required; id is read when group is left out)} → {faces: [{id, fill (top fill), bounds, appearance: [row…]}], edges: [{id, stroke (top stroke), width (top stroke's), appearance: [row…]}], where a row is {index (in the part's fill and stroke stack, bottom first), kind: \"fill\"|\"stroke\", paint, opacity: 0..1, visible, width?: pt (strokes only), drawn (the part is shown with opacity above 0, and the row is shown, has paint and opacity above 0, a stroke also width above 0)}, sources, gapOptions: {detect, size: \"small\"|\"medium\"|\"large\"|pt, points, color: #rrggbb} (as livePaint.gapOptions sets them), gaps: [[x0,y0,x1,y1]…] (as livePaint.gapOptions returns them)}", has_doc, lp_info ), @@ -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\", 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) ), @@ -414,22 +414,274 @@ fn source_nodes(n: &Node) -> Vec> { if is_live_paint(n) { b::sources(n).and_then(|g| g.children().cloned()).unwrap_or_default() } else { vec![Arc::new(n.clone())] } } +/// Does appearance row `i` draw: it is shown, has paint and an opacity above 0, and a stroke also +/// has a weight above 0? +fn row_draws(i: &AppearanceItem) -> bool { + match i { + AppearanceItem::Fill(f) => f.visible && !f.paint.is_none() && f.opacity > 0.0, + AppearanceItem::Stroke(s) => s.visible && !s.paint.is_none() && s.opacity > 0.0 && s.width > 0.0, + } +} + +/// What a source path gives the faces and edges made from it. +struct SourceStyle { + /// The fill rows that draw, in paint order (none when the path's opacity is 0). + fills: Vec, + /// The stroke rows that draw, in paint order (none when the path's opacity is 0). + strokes: Vec, + /// The top stroke's weight, for an edge given no stroke that draws. + width: f64, + opacity: f32, + blend: BlendMode, +} + +impl SourceStyle { + /// The style of source path `n`: its rows keep their order and settings, gradients fitted to + /// its bounds keep that fit, and the strokes' pen pressure, tilt, bearing and rotation stay + /// with the path. + fn of(n: &Node) -> Self { + let mut a = (*n.appearance).clone().without_pressure(); + if a.has_unplaced_gradient() + && let Some(bounds) = n.geometric_bounds() + { + a.pin_gradients(bounds); + } + let width = a.stroke().map_or(1.0, |s| s.width); + let (mut fills, mut strokes) = (vec![], vec![]); + if n.opacity > 0.0 { + for i in a.items.into_iter().filter(row_draws) { + if i.is_fill() { fills.push(i) } else { strokes.push(i) } + } + } + Self { fills, strokes, width, opacity: n.opacity, blend: n.blend } + } + + /// Give part `n` the rows `rows` of this source with its opacity and blending mode; with no + /// rows, `n` keeps the unpainted row it has. + fn paint(&self, n: &mut Node, rows: &[AppearanceItem]) { + if rows.is_empty() { + return; + } + n.appearance = Appearance { items: rows.to_vec(), ..Default::default() }.into(); + n.opacity = self.opacity; + n.blend = self.blend; + } +} + +/// How far, in points, a place on an edge may be from its source path and still be on it. +const ON_SOURCE: f64 = 0.05; + +/// Does stroke row `i` have settings that depend on where along its path a piece of it lies or +/// which way it runs: dashes, arrowheads, a width profile, a brush, or a gradient along or across +/// the stroke? +fn depends_on_place(i: &AppearanceItem) -> bool { + matches!(i, AppearanceItem::Stroke(s) if s.dash.is_some() || s.start_arrow.is_some() || s.end_arrow.is_some() || s.profile.is_some() || s.brush.is_some() || s.gradient_mode != vectorcraft_doc::StrokeGradientMode::Within) +} + +/// One subpath's segments with the length along it where each starts, then its whole length, and +/// a grid of square cells listing the segments whose bounds, grown by [`ON_SOURCE`], reach into +/// each cell, so finding the segments near a point does not look at every segment. +struct Track { + segs: Vec, + at: Vec, + closed: bool, + cell: f64, + grid: HashMap<(i64, i64), Vec>, + /// Segments that reach into more than [`Track::MAX_CELLS`] cells, or that come after the grid + /// holds [`Track::CELLS_PER_SEGMENT`] entries per segment, looked at for every point. + wide: Vec, +} + +impl Track { + const ACCURACY: f64 = 1e-4; + const MAX_CELLS: i64 = 4096; + const CELLS_PER_SEGMENT: usize = 16; + + fn new(sp: &SubPath) -> Self { + use kurbo::{ParamCurveArclen, Shape as _}; + let mut bp = kurbo::BezPath::new(); + sp.to_bezpath_into(&mut bp); + let segs: Vec = bp.segments().collect(); + let mut at = Vec::with_capacity(segs.len() + 1); + let mut len = 0.0; + for s in &segs { + at.push(len); + len += s.arclen(Self::ACCURACY); + } + at.push(len); + let boxes: Vec = segs.iter().map(|s| s.bounding_box().inflate(ON_SOURCE, ON_SOURCE)).collect(); + // Cells about as wide as an average segment's bounds. + let mean = boxes.iter().map(|b| b.width().max(b.height())).sum::() / boxes.len().max(1) as f64; + let cell = if mean.is_finite() { mean.max(4.0 * ON_SOURCE) } else { 4.0 * ON_SOURCE }; + let mut grid: HashMap<(i64, i64), Vec> = HashMap::new(); + let mut wide = vec![]; + // The grid holds at most this many entries in all. + let mut budget = boxes.len().saturating_mul(Self::CELLS_PER_SEGMENT); + for (k, b) in boxes.iter().enumerate() { + let (x0, y0) = Self::cell_of(Point::new(b.x0, b.y0), cell); + let (x1, y1) = Self::cell_of(Point::new(b.x1, b.y1), cell); + let cells = x1.saturating_sub(x0).saturating_add(1).saturating_mul(y1.saturating_sub(y0).saturating_add(1)); + let Some(cells) = usize::try_from(cells).ok().filter(|&c| cells <= Self::MAX_CELLS && c <= budget) else { + wide.push(k); + continue; + }; + budget -= cells; + for x in x0..=x1 { + for y in y0..=y1 { + grid.entry((x, y)).or_default().push(k); + } + } + } + Self { segs, at, closed: sp.closed, cell, grid, wide } + } + + fn cell_of(p: Point, cell: f64) -> (i64, i64) { + ((p.x / cell).floor() as i64, (p.y / cell).floor() as i64) + } + + fn len(&self) -> f64 { + self.at.last().copied().unwrap_or(0.0) + } + + /// The lengths along the subpath to each of its segments' places nearest `p` that are within + /// [`ON_SOURCE`] of it (more than one where the subpath passes `p` again). + fn places(&self, p: Point) -> Vec { + use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveNearest}; + let near = self.grid.get(&Self::cell_of(p, self.cell)).map(Vec::as_slice).unwrap_or_default(); + let mut out = vec![]; + for &k in near.iter().chain(&self.wide) { + let Some(s) = self.segs.get(k) else { continue }; + let n = s.nearest(p, 1e-9); + if n.distance_sq <= ON_SOURCE * ON_SOURCE { + out.push(self.at.get(k).copied().unwrap_or(0.0) + s.subsegment(0.0..n.t).arclen(Self::ACCURACY)); + } + } + out + } + + /// The signed length from `a` to `b` along the subpath (the shorter way round a closed one). + fn step(&self, a: f64, b: f64) -> f64 { + let (d, len) = (b - a, self.len()); + if self.closed && len > 0.0 { d - len * (d / len).round() } else { d } + } + + /// Of `places`, the one nearest along the subpath to `target`. + fn nearest(&self, places: &[f64], target: f64) -> Option { + places.iter().copied().min_by(|x, y| self.step(*x, target).abs().total_cmp(&self.step(*y, target).abs())) + } +} + +/// Where edge `edge` runs along its source path, whose subpaths' tracks are `tracks`: the length +/// along the source subpath to the edge's start, whether the edge starts at that subpath's start and +/// ends at its end (an open subpath), and whether it runs the whole subpath. The middle of the +/// edge's first segment places it, and its ends are taken where they lie that far along the source, +/// so a path that passes a point twice is told apart. An edge that runs against the direction of its +/// source is reversed first, and a closed edge as long as its closed source is started at the anchor +/// where its source starts (one with no anchor there, or a shorter loop cut from a source that +/// crosses itself, does not count as running the whole subpath). `None` when the edge is +/// not a single piece found on the source. +fn edge_run(tracks: &[Track], edge: &mut PathData) -> Option<(f64, bool, bool, bool)> { + use kurbo::{ParamCurve, ParamCurveArclen}; + let [sp] = edge.subpaths.as_slice() else { return None }; + if sp.segment_count() == 0 { + return None; + } + let (a, z) = (sp.anchors.first()?.p, if sp.closed { sp.anchors.first()?.p } else { sp.anchors.last()?.p }); + let first = sp.segment(0); + let mid = first.eval(0.5); + let half = first.subsegment(0.0..0.5).arclen(Track::ACCURACY); + let length = sp.anchor_arc_positions().last().copied().unwrap_or(0.0); + let edge_closed = sp.closed; + // (how far off the fit is, track, start, end, runs forward) for the subpath that fits best. + let mut found: Option<(f64, &Track, f64, f64, bool)> = None; + for track in tracks { + // The start lies half the first segment before its middle along the source, or after it + // when the edge runs the other way: take the place and way that fit best. + let starts_at = track.places(a); + let mut best: Option<(f64, f64, bool)> = None; + for pm in track.places(mid) { + for forward in [true, false] { + let Some(pa) = track.nearest(&starts_at, if forward { pm - half } else { pm + half }) else { continue }; + let miss = (if forward { track.step(pa, pm) } else { track.step(pm, pa) } - half).abs(); + if best.is_none_or(|(m, _, _)| miss < m) { + best = Some((miss, pa, forward)); + } + } + } + let Some((miss, pa, forward)) = best else { continue }; + let target = if forward { pa + length } else { pa - length }; + let Some(pz) = track.nearest(&track.places(z), target) else { continue }; + let miss = miss + track.step(pz, target).abs(); + if found.is_none_or(|(m, ..)| miss < m) { + found = Some((miss, track, pa, pz, forward)); + } + } + let (_, track, pa, pz, forward) = found?; + let (from, to) = if forward { (pa, pz) } else { (pz, pa) }; + if !forward { + edge.reverse(); + } + let open = !track.closed; + let starts = open && from <= ON_SOURCE; + let ends = open && to >= track.len() - ON_SOURCE; + if open { + return Some((from, starts, ends, starts && ends)); + } + // A closed edge runs the whole closed subpath, from the anchor the planar map starts it at. + // Start it at the anchor where the source starts, so settings that follow the path begin there. + let start = track.segs.first().map(|s| s.start())?; + let moved = edge_closed + && (length - track.len()).abs() <= ON_SOURCE.max(track.len() * 1e-4) + && edge.subpaths.first_mut().is_some_and(|sp| match sp.anchors.iter().position(|a| a.p.distance(start) <= ON_SOURCE) { + Some(k) => { + sp.anchors.rotate_left(k); + true + } + None => false, + }); + Some((if moved { 0.0 } else { from }, false, false, moved)) +} + +/// Fit stroke row `row` of a source path to an edge cut from it, which runs as [`edge_run`] says +/// (`None`: not known): its dashes go on from where the edge starts along the source, with the +/// lengths set and without the fit of dashes aligned to corners and path ends, its arrowheads stay only at the source's own ends, and its width profile and brush, which spread +/// over the whole path, stay only on an edge that runs the whole path. +fn fit_to_edge(row: &mut AppearanceItem, run: Option<(f64, bool, bool, bool)>) { + let AppearanceItem::Stroke(s) = row else { return }; + let (from, starts, ends, whole) = run.unwrap_or((0.0, false, false, false)); + if !whole { + if let Some(d) = &mut s.dash + && run.is_some() + { + d.offset += from; + d.align_corners = false; + } + s.profile = None; + s.brush = None; + } + if !starts { + s.start_arrow = None; + } + if !ends { + s.end_arrow = None; + } +} + /// The planar map's inputs from `sources` (paths and compound paths, back → front), with the -/// fill, stroke and stroke width of each. -fn source_shapes(sources: &[Arc]) -> (Vec, Vec<(Paint, Paint, f64)>) { +/// style of each. +fn source_shapes(sources: &[Arc]) -> (Vec, Vec) { let mut lv = vec![]; for n in sources { b::leaf_shapes(n, &mut lv); } let mut shapes = vec![]; - let mut styles: Vec<(Paint, Paint, f64)> = vec![]; + let mut styles: Vec = vec![]; for l in lv { if let Some((path, rule)) = b::node_outline(l) && !path.is_empty() { shapes.push(po::Shape::new(path, rule, styles.len() as u64)); - let a = &l.appearance; - styles.push((a.fill_paint(), a.stroke_paint(), a.stroke().map(|s| s.width).unwrap_or(1.0))); + styles.push(SourceStyle::of(l)); } } (shapes, styles) @@ -462,17 +714,35 @@ fn build_children(d: &mut Document, sources: Vec>, max_gap: Option> = HashMap::new(); for e in edges { - let Some((_, stroke, w)) = styles.get(e.key as usize) else { continue }; + let key = e.key as usize; + let Some(s) = styles.get(key) else { continue }; + let mut path = e.path; + let mut rows = s.strokes.clone(); + if rows.iter().any(depends_on_place) { + let source = tracks + .entry(key) + .or_insert_with(|| shapes.get(key).map(|src| src.path.subpaths.iter().map(Track::new).collect()).unwrap_or_default()); + let run = edge_run(source, &mut path); + for r in &mut rows { + fit_to_edge(r, run); + } + } let id = d.alloc_id(); - let mut n = Node::path(id, e.path, stroke_only(stroke.clone(), *w)); + let mut n = Node::path(id, path, stroke_only(Paint::None, s.width)); n.name = Some(EDGE_NAME.into()); + s.paint(&mut n, &rows); children.push(Arc::new(n)); } Ok((children, nfaces, nedges)) @@ -481,8 +751,9 @@ fn build_children(d: &mut Document, sources: Vec>, max_gap: Option = old.subpaths.iter().map(Track::new).collect(); + let run = n.path_data_mut().and_then(|path| edge_run(&tracks, path)); + let mut a = (*n.appearance).clone(); + for r in &mut a.items { + fit_to_edge(r, run); + } + n.appearance = a.into(); +} diff --git a/crates/engine/src/cmd/buildcmds/live_paint.rs b/crates/engine/src/cmd/buildcmds/live_paint.rs index fb9e6c32ac..7938c07879 100644 --- a/crates/engine/src/cmd/buildcmds/live_paint.rs +++ b/crates/engine/src/cmd/buildcmds/live_paint.rs @@ -1,7 +1,8 @@ use super::{ - Appearance, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId, Paint, PathData, Point, - Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, ids_json, is_live_paint, - json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes, switch_or, + Appearance, AppearanceItem, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId, + PathData, Point, Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, + fit_to_old_edge, ids_json, is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, + source_nodes, source_shapes, switch_or, }; /// `options` as stored on a Live Paint group: none for the defaults. @@ -84,6 +85,38 @@ pub(super) fn lp_make(s: &mut Session, p: &Value) -> Result { Ok(json!({ "id": id.0, "faces": faces, "edges": edges })) } +/// How far, in points, the middle of an edge Merge makes may be from the old edge it lies on. +const ON_OLD_EDGE: f64 = 1e-3; + +/// What Merge carries from a face or edge to the part it makes again in its place, another path: +/// the appearance, visibility, opacity and blending mode. Gradients fitted to the old outline keep +/// that fit, and the strokes' pen pressure, tilt, bearing and rotation stay behind. +struct Carried { + appearance: Appearance, + visible: bool, + opacity: f32, + blend: vectorcraft_color::BlendMode, +} + +impl Carried { + fn of(n: &Node) -> Self { + let mut appearance = (*n.appearance).clone().without_pressure(); + if appearance.has_unplaced_gradient() + && let Some(bounds) = n.geometric_bounds() + { + appearance.pin_gradients(bounds); + } + Self { appearance, visible: n.visible, opacity: n.opacity, blend: n.blend } + } + + fn onto(self, n: &mut Node) { + n.appearance = self.appearance.into(); + n.visible = self.visible; + n.opacity = self.opacity; + n.blend = self.blend; + } +} + /// Add the other `roots` (back → front) to the first Live Paint group among them, which keeps its /// id, the paint of its faces and edges, and its own properties apart from the Gap Options, which /// are merged; returns (group, faces, edges). @@ -95,20 +128,11 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result .ok_or_else(|| EngineError::Other("Live Paint Merge: select a Live Paint group and the paths to add".into()))?; check_live_paint_takes(d, roots)?; let old = d.node(target).cloned().ok_or(EngineError::NoNode(target))?; - // Paint to carry over: (point inside face, fill) and (point on edge, stroke). - let keep_faces: Vec<(Point, Paint)> = b::faces(&old) - .iter() - .filter(|f| !f.appearance.fill_paint().is_none()) - .filter_map(|f| Some((po::interior_point(f.path_data()?)?, f.appearance.fill_paint()))) - .collect(); - let keep_edges: Vec<(Point, Appearance)> = b::edges(&old) - .iter() - .filter_map(|e| { - let pd = e.path_data()?; - let sp = pd.subpaths.first().filter(|sp| sp.segment_count() > 0)?; - Some((kurbo::ParamCurve::eval(&sp.segment(0), 0.5), (*e.appearance).clone())) - }) - .collect(); + // Paint to carry over: (point inside face, paint) for faces that draw; edges are matched to the + // old edges below. + let keep_faces: Vec<(Point, Carried)> = + b::faces(&old).iter().filter(|f| draws(f)).filter_map(|f| Some((po::interior_point(f.path_data()?)?, Carried::of(f)))).collect(); + let old_parts = old.clone(); let mut sources = source_nodes(&old); for r in roots { if *r != target { @@ -126,20 +150,32 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result *ch = children; } g.extras_mut().live_paint_gaps = stored_gap_options(options); - for (pt, paint) in keep_faces { + for (pt, carried) in keep_faces { if let Some(fid) = face_at(&g, pt).map(|f| f.id) && let Some(ch) = g.children_mut() && let Some(f) = ch.iter_mut().find(|c| c.id == fid) { - Arc::make_mut(f).appearance.set_fill(paint); + carried.onto(Arc::make_mut(f)); } } - for (pt, app) in keep_edges { - if let Some(eid) = edge_near(&g, pt, 0.5).map(|e| e.id) - && let Some(ch) = g.children_mut() - && let Some(e) = ch.iter_mut().find(|c| c.id == eid) - { - Arc::make_mut(e).appearance = app.into(); + // Each edge whose middle lies on an old edge, every piece of an edge an added path cuts + // included, takes the old edge's paint, with its rows fitted to its part of the old edge. + if let Some(ch) = g.children_mut() { + for c in ch.iter_mut().filter(|c| c.name.as_deref() == Some(EDGE_NAME)) { + let Some(mid) = c + .path_data() + .and_then(|pd| pd.subpaths.first()) + .filter(|sp| sp.segment_count() > 0) + .map(|sp| kurbo::ParamCurve::eval(&sp.segment(0), 0.5)) + else { + continue; + }; + let Some(was) = edge_near(&old_parts, mid, ON_OLD_EDGE) else { continue }; + let e = Arc::make_mut(c); + Carried::of(was).onto(e); + if let Some(outline) = was.path_data() { + fit_to_old_edge(e, outline); + } } } let mut merged = Beside::replacing(d, roots); @@ -191,6 +227,13 @@ pub(super) fn lp_release(s: &mut Session, p: &Value) -> Result { Ok(json!({ "ids": ids_json(&ids) })) } +/// Does face or edge `n` draw on the canvas: it is shown, its opacity is above 0, and a fill or +/// stroke row of its appearance draws (see [`Appearance::has_drawn_fill`] and +/// [`Appearance::has_drawn_stroke`])? +fn draws(n: &Node) -> bool { + n.visible && n.opacity > 0.0 && (n.appearance.has_drawn_fill() || n.appearance.has_drawn_stroke()) +} + pub(super) fn lp_expand(s: &mut Session, p: &Value) -> Result { let targets = live_targets(s, p)?; s.edit("Expand Live Paint", |d, sel| { @@ -205,8 +248,7 @@ pub(super) fn lp_expand(s: &mut Session, p: &Value) -> Result { if let Some(ch) = n.children_mut() { ch.retain(|c| match c.name.as_deref() { Some(SOURCES_NAME) => false, - Some(FACE_NAME) => !c.appearance.fill_paint().is_none(), - Some(EDGE_NAME) => !c.appearance.stroke_paint().is_none() && c.appearance.stroke_width() > 0.0, + Some(FACE_NAME | EDGE_NAME) => draws(c), _ => true, }); } @@ -329,44 +371,106 @@ pub(super) fn lp_gap_options(s: &mut Session, p: &Value) -> Result { Ok(json!({ "ids": ids_json(&targets), "faces": faces, "gaps": gaps_json(&gaps), "closed": closed })) } -pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result { - const C: &str = "livePaint.fill"; - let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?; +/// Which parts a Live Paint Bucket click paints besides the one under the pointer. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum LpScope { + /// The part under the pointer alone (a click). + One, + /// A face and the faces reached from it across edges that draw no stroke ([`b::flood_faces`]), + /// or an edge and the edges joined to it end to end that draw with the same stroke paint + /// ([`b::connected_edges`], [`b::lp_stroke_paint`]) (a double-click). + Connected, + /// Every face with the same fill, or every edge that draws with the same stroke paint, in the + /// group (a triple-click). + SamePaint, +} + +/// The `scope` of `livePaint.fill` and `livePaint.strokeEdge`: `one` when left out or null. +fn scope_param(p: &Value, c: &str) -> Result { + match p.get("scope").filter(|v| !v.is_null()) { + None => Ok(LpScope::One), + Some(v) => match v.as_str() { + Some("one") => Ok(LpScope::One), + Some("connected") => Ok(LpScope::Connected), + Some("samePaint") => Ok(LpScope::SamePaint), + _ => Err(bad(c, "scope must be \"one\", \"connected\" or \"samePaint\"")), + }, + } +} + +/// The `match` of `livePaint.fill` and `livePaint.strokeEdge`: a paint as the document stores it, +/// None when left out or null. With `allowed` false (a scope that compares no paints) a `match` is +/// an error naming `scopes`, the scopes it applies to. +fn match_param(p: &Value, c: &str, allowed: bool, scopes: &str) -> Result> { + let Some(v) = p.get("match").filter(|v| !v.is_null()) else { return Ok(None) }; + if !allowed { + return Err(bad(c, format!("match applies only with scope {scopes}"))); + } + serde_json::from_value::(v.clone()).map(Some).map_err(|_| bad(c, "match must be a paint as the document stores it")) +} + +/// The drag path of `livePaint.fill` or `livePaint.strokeEdge` (command `c`) pressed at `start`: +/// `points` followed by each chunk of `continuation`, where every chunk holds 1 to +/// [`b::LP_FILL_CHUNK_POINTS`] finite canvas points and starts at the last point of the chunk +/// before it (`points` at `start`). None when `points` is left out. With a `scope` other than +/// `one`, `points` is an error. +fn path_param(p: &Value, c: &str, start: Point, scope: LpScope) -> Result>>> { + if scope != LpScope::One && p.get("points").is_some() { + return Err(bad(c, "scope applies to a click: leave out points")); + } let parse_chunk = |input: &Value, start: Point| -> Result> { let values = input .as_array() .filter(|points| !points.is_empty() && points.len() <= b::LP_FILL_CHUNK_POINTS) - .ok_or_else(|| bad(C, "each path chunk must contain 1 to 4096 points"))?; + .ok_or_else(|| bad(c, "each path chunk must contain 1 to 4096 points"))?; let points: Vec<_> = values .iter() .map(|point| { - let pair = point.as_array().filter(|pair| pair.len() == 2).ok_or_else(|| bad(C, "points must be [x,y] pairs"))?; - let x = pair.first().and_then(Value::as_f64).ok_or_else(|| bad(C, "point x must be a number"))?; - let y = pair.get(1).and_then(Value::as_f64).ok_or_else(|| bad(C, "point y must be a number"))?; + let pair = point.as_array().filter(|pair| pair.len() == 2).ok_or_else(|| bad(c, "points must be [x,y] pairs"))?; + let x = pair.first().and_then(Value::as_f64).ok_or_else(|| bad(c, "point x must be a number"))?; + let y = pair.get(1).and_then(Value::as_f64).ok_or_else(|| bad(c, "point y must be a number"))?; let point = Point::new(x, y); if !finite(point) { - return Err(bad(C, "points must be finite canvas points")); + return Err(bad(c, "points must be finite canvas points")); } Ok(point) }) .collect::>()?; if points.first() != Some(&start) { - return Err(bad(C, "path chunks must share their boundary point")); + return Err(bad(c, "path chunks must share their boundary point")); } Ok(points) }; - let points = p.get("points"); + let Some(points) = p.get("points") else { + return if p.get("continuation").is_some() { Err(bad(c, "continuation requires points")) } else { Ok(None) }; + }; let continuation = match p.get("continuation") { None => &[][..], - Some(input) if points.is_some() => input.as_array().ok_or_else(|| bad(C, "continuation must be an array of path chunks"))?.as_slice(), - Some(_) => return Err(bad(C, "continuation requires points")), + Some(input) => input.as_array().ok_or_else(|| bad(c, "continuation must be an array of path chunks"))?.as_slice(), }; + let mut chunks: Vec> = Vec::with_capacity(continuation.len() + 1); + let mut last = start; + for input in std::iter::once(points).chain(continuation) { + let chunk = parse_chunk(input, last)?; + last = chunk.last().copied().unwrap_or(last); + chunks.push(chunk); + } + Ok(Some(chunks)) +} + +pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result { + const C: &str = "livePaint.fill"; + let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?; + let scope = scope_param(p, C)?; + let like = match_param(p, C, scope == LpScope::SamePaint, "\"samePaint\"")?; + let path = path_param(p, C, pt, scope)?; crate::cmd::paint::check_keep_model(p, C)?; let paint = paint_from(s, p)?.unwrap_or_else(|| s.paint.fill.clone()); let group = object_param(p, "group", C)?; let roots = if group.is_none() { root_ids(s, p)? } else { vec![] }; // The faces the click or drag paints in Live Paint group `gid`: the visible face at the point, - // and every visible face the drag crosses; → (the face at the point, the faces). + // the faces its scope adds, and every visible face the drag crosses; → (the face at the point, + // the faces). let targets_in = |d: &Document, gid: NodeId| -> Result<(NodeId, std::collections::BTreeSet)> { let fid = d .node(gid) @@ -374,7 +478,19 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result { .map(|f| f.id) .ok_or_else(|| EngineError::Other("no Live Paint face at that point".into()))?; let mut targets = std::collections::BTreeSet::from([fid]); - if let Some(points) = points { + if scope != LpScope::One { + let n = d.node(gid).ok_or(EngineError::NoNode(gid))?; + if scope == LpScope::Connected { + targets.extend(b::flood_faces(n, fid)); + } else { + let like = match &like { + Some(m) => m.clone(), + None => d.node(fid).ok_or(EngineError::NoNode(fid))?.appearance.fill_paint(), + }; + targets.extend(b::faces(n).into_iter().filter(|f| f.visible && f.appearance.fill_paint() == like).map(|f| f.id)); + } + } + if let Some(chunks) = &path { let n = d.node(gid).ok_or(EngineError::NoNode(gid))?; // Use the existing region-crossing probes, so even a face narrower than the distance // between pointer events is filled. Reversing matches visible_face_at's front first. @@ -390,11 +506,8 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result { } } let map = b::BuilderMap { regions, ..Default::default() }; - let mut last = pt; - for input in std::iter::once(points).chain(continuation) { - let chunk = parse_chunk(input, last)?; - last = chunk.last().copied().unwrap_or(last); - targets.extend(map.hits_along(&chunk, None).regions.iter().filter_map(|i| face_ids.get(*i).copied())); + for chunk in chunks { + targets.extend(map.hits_along(chunk, None).regions.iter().filter_map(|i| face_ids.get(*i).copied())); } } Ok((fid, targets)) @@ -423,34 +536,37 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result { } } }; - let (g, face) = match live { + let (g, face, count) = match live { Some(gid) => { let (fid, targets) = targets_in(&s.doc()?.doc, gid)?; - // Faces that already have the paint stay as they are: when every face has it, nothing - // changes and no undo step is recorded. + let count = targets.len(); + // Faces that already have only the fill the bucket would leave ([`bucket_keeps`]) stay as + // they are: when every face does, nothing changes and no undo step is recorded. let d = &s.doc()?.doc; - let unpainted: Vec = targets.into_iter().filter(|t| d.node(*t).is_none_or(|f| f.appearance.fill_paint() != paint)).collect(); + let unpainted: Vec = + targets.into_iter().filter(|t| d.node(*t).is_none_or(|f| !bucket_keeps(&f.appearance, true, &paint, 0.0))).collect(); if unpainted.is_empty() { - return Ok(json!({ "group": gid.0, "face": fid.0 })); + return Ok(json!({ "group": gid.0, "face": fid.0, "count": count })); } s.edit("Live Paint Bucket", |d, _| { for target in unpainted { - d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone()); + bucket_paint(&mut d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance, true, &paint, 0.0); } - Ok((gid, fid)) + Ok((gid, fid, count)) })? } None => s.edit("Live Paint Bucket", |d, sel| { let gid = make_live(d, sel, &roots)?.0; let (fid, targets) = targets_in(d, gid)?; + let count = targets.len(); for target in targets { - d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone()); + bucket_paint(&mut d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance, true, &paint, 0.0); } - Ok((gid, fid)) + Ok((gid, fid, count)) })?, }; s.remember_paint(&paint); - Ok(json!({ "group": g.0, "face": face.0 })) + Ok(json!({ "group": g.0, "face": face.0, "count": count })) } pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result { @@ -464,31 +580,170 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "width out of range")); } let tol = number_or(p, "tolerance", 4.0, C)?.clamp(0.0, 1000.0); - let (eid, unchanged) = { + let scope = scope_param(p, C)?; + let like = match_param(p, C, scope != LpScope::One, "\"connected\" or \"samePaint\"")?; + let path = path_param(p, C, pt, scope)?; + let through: Vec = match p.get("through") { + None => vec![], + Some(_) if scope != LpScope::Connected => return Err(bad(C, "through applies to scope \"connected\"")), + Some(v) => { + let ids = v.as_array().filter(|ids| ids.len() <= 4096).ok_or_else(|| bad(C, "through must be an array of at most 4096 edge ids"))?; + ids.iter() + .map(|id| id.as_u64().map(NodeId).ok_or_else(|| bad(C, "through must be an array of at most 4096 edge ids"))) + .collect::>()? + } + }; + 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")))?; - let e = b::visible_edge_near(n, pt, tol).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?; - // An edge that already has the paint and the width (or has no stroke and gets none) stays as - // it is, and no undo step is recorded. - let unchanged = match e.appearance.stroke() { - Some(st) => st.paint == paint && st.width == width, - None => paint.is_none(), - }; - (e.id, unchanged) - }; - if unchanged { - return Ok(json!({ "group": g.0, "edge": eid.0 })); - } - let edge = s.edit("Live Paint Bucket", |d, _| { - let e = d.node_mut(eid).ok_or(EngineError::NoNode(eid))?; - e.appearance.set_stroke(paint.clone()); - if let Some(st) = e.appearance.stroke_mut() { - st.width = width; + // 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"))); } - Ok(eid) + 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)); + let targets = match scope { + // A drag also reaches every edge of the group that is not hidden and that its path + // crosses or touches. + LpScope::One => std::iter::once(eid) + .chain( + path.as_deref() + .map(|chunks| b::visible_edges_along(n, chunks)) + .unwrap_or_default() + .into_iter() + .map(|e| e.id) + .filter(|id| *id != eid), + ) + .collect(), + LpScope::Connected => b::connected_edges_through(n, eid, &like, &through), + LpScope::SamePaint => std::iter::once(eid) + .chain(b::edges(n).into_iter().filter(|e| e.visible && e.id != eid && b::lp_stroke_paint(e) == like).map(|e| e.id)) + .collect(), + }; + let count = targets.len(); + // An edge that already has only the stroke the bucket would leave ([`bucket_keeps`]) stays + // as it is; when every edge does, nothing changes and no undo step is recorded. + let changed: Vec = + targets.into_iter().filter(|t| d.node(*t).is_none_or(|e| !bucket_keeps(&e.appearance, false, &paint, width))).collect(); + (eid, count, changed) + }; + if changed.is_empty() { + return Ok(json!({ "group": g.0, "edge": eid.0, "count": count })); + } + s.edit("Live Paint Bucket", |d, _| { + for target in &changed { + bucket_paint(&mut d.node_mut(*target).ok_or(EngineError::NoNode(*target))?.appearance, false, &paint, width); + } + Ok(()) })?; s.remember_paint(&paint); - Ok(json!({ "group": g.0, "edge": edge.0 })) + Ok(json!({ "group": g.0, "edge": eid.0, "count": count })) +} + +/// Whether the Live Paint Bucket leaves appearance `a` as it is when it paints its fills (`fill`) +/// or strokes with `paint` (a stroke at `width`): it has exactly one row of that kind, shown, fully +/// opaque, blending normally and with the paint (a stroke also with the width, unless the paint is +/// none), or it has no row of that kind and the paint is none. +fn bucket_keeps(a: &Appearance, fill: bool, paint: &super::Paint, width: f64) -> bool { + let mut rows = a.items.iter().filter(|i| i.is_fill() == fill); + match (rows.next(), rows.next()) { + (None, _) => paint.is_none(), + (Some(row), None) => { + row.visible() + && row.opacity() == 1.0 + && row.blend() == vectorcraft_color::BlendMode::Normal + && row.paint() == paint + && match row { + AppearanceItem::Fill(_) => true, + AppearanceItem::Stroke(st) => paint.is_none() || st.width == width, + } + } + (Some(_), Some(_)) => false, + } +} + +/// Paint the fills (`fill`) or strokes of appearance `a` with `paint` (a stroke at `width`), as the +/// Live Paint Bucket does: every row of that kind is replaced by one row, shown, fully opaque and +/// blending normally, in the place of the topmost row of that kind. The new row keeps the other +/// settings (a stroke's dashes, caps and arrowheads, a row's effects) of the topmost row of that +/// kind that is shown, or of the topmost one when every row is hidden. Rows of the other kind stay +/// as they are. With no row of that kind, a fill is added below the strokes and a stroke above the +/// fills. +fn bucket_paint(a: &mut Appearance, fill: bool, paint: &super::Paint, width: f64) { + let of_kind = |i: &AppearanceItem| i.is_fill() == fill; + let Some(top) = a.items.iter().rposition(of_kind) else { + if fill { + a.set_fill(paint.clone()); + } else { + a.items.push(AppearanceItem::Stroke(super::StrokeLayer::new(paint.clone(), width))); + } + return; + }; + let base = a.items.iter().rposition(|i| of_kind(i) && i.visible()).unwrap_or(top); + let Some(mut row) = a.items.get(base).cloned() else { return }; + match &mut row { + AppearanceItem::Fill(f) => { + f.paint = paint.clone(); + f.opacity = 1.0; + f.blend = vectorcraft_color::BlendMode::Normal; + f.visible = true; + } + AppearanceItem::Stroke(st) => { + st.paint = paint.clone(); + st.width = width; + st.opacity = 1.0; + st.blend = vectorcraft_color::BlendMode::Normal; + st.visible = true; + } + } + let mut row = Some(row); + a.items = std::mem::take(&mut a.items) + .into_iter() + .enumerate() + .filter_map(|(i, item)| { + if i == top { + row.take() + } else if of_kind(&item) { + None + } else { + Some(item) + } + }) + .collect(); +} + +/// Every fill and stroke row of face or edge `n`, bottom first, as `livePaint.info` lists them. A +/// row is `drawn` when the part is shown with an opacity above 0 and the row is shown, has paint +/// and has an opacity above 0 (a stroke also a weight above 0): the rule of [`draws`], row by row. +fn appearance_rows(n: &Node) -> Vec { + let part_shown = n.visible && n.opacity > 0.0; + n.appearance + .items + .iter() + .enumerate() + .map(|(i, item)| { + let shown = part_shown && item.visible() && !item.paint().is_none() && item.opacity() > 0.0; + let mut row = json!({ + "index": i, + "kind": item.kind_name(), + "paint": item.paint().label(), + "opacity": item.opacity(), + "visible": item.visible(), + }); + let drawn = match item { + AppearanceItem::Fill(_) => shown, + AppearanceItem::Stroke(st) => { + row["width"] = json!(st.width); + shown && st.width > 0.0 + } + }; + row["drawn"] = json!(drawn); + row + }) + .collect() } pub(super) fn lp_info(s: &mut Session, p: &Value) -> Result { @@ -502,12 +757,24 @@ pub(super) fn lp_info(s: &mut Session, p: &Value) -> Result { .iter() .map(|f| { let bb = f.geometric_bounds().unwrap_or(Rect::ZERO); - json!({ "id": f.id.0, "fill": f.appearance.fill_paint().label(), "bounds": [bb.x0, bb.y0, bb.x1, bb.y1] }) + json!({ + "id": f.id.0, + "fill": f.appearance.fill_paint().label(), + "bounds": [bb.x0, bb.y0, bb.x1, bb.y1], + "appearance": appearance_rows(f), + }) }) .collect(); let edges: Vec = b::edges(n) .iter() - .map(|e| json!({ "id": e.id.0, "stroke": e.appearance.stroke_paint().label(), "width": e.appearance.stroke_width() })) + .map(|e| { + json!({ + "id": e.id.0, + "stroke": e.appearance.stroke_paint().label(), + "width": e.appearance.stroke_width(), + "appearance": appearance_rows(e), + }) + }) .collect(); let sources = b::sources(n).and_then(|g| g.children()).map(|c| c.len()).unwrap_or(0); let options = n.gap_options(); diff --git a/crates/engine/src/cmd/buildcmds/shape_builder.rs b/crates/engine/src/cmd/buildcmds/shape_builder.rs index fea79a0e6a..472ba2208b 100644 --- a/crates/engine/src/cmd/buildcmds/shape_builder.rs +++ b/crates/engine/src/cmd/buildcmds/shape_builder.rs @@ -63,7 +63,7 @@ pub(super) fn sb_merge(s: &mut Session, p: &Value) -> Result { && let Some(&q) = pts.first() && let Some((i, run)) = map.stroke_at(&outlines, q, tol) && let (Some(leaf), Some(drawn)) = (leaves.get(i), outlines.get(i)) - && let Some(rest) = po::cut_out(drawn, &run, open_filled_as_closed && !leaf.appearance.fill_paint().is_none(), b::outline_snap(drawn)) + && let Some(rest) = po::cut_out(drawn, &run, open_filled_as_closed && leaf.appearance.has_drawn_fill(), b::outline_snap(drawn)) && rest.length() > b::outline_snap(drawn) { // The path keeps the rest of it, and a copy of it with the run under the click goes diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 11519b84be..203fd62338 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -12,6 +12,7 @@ use super::{ thread_local! { static BOX_TESTS: std::cell::Cell = const { std::cell::Cell::new(0) }; static CANDIDATE_VISITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static TRACES_ON_THIS_THREAD: std::cell::Cell = const { std::cell::Cell::new(0) }; } // ---------- Image Trace ---------- @@ -22,6 +23,32 @@ 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 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 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 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"; /// The `view` param ([`TraceView`] id), if given. @@ -288,9 +315,10 @@ fn trace_library(c: &str, s: &Session, params: &mut tr::TraceParams) -> Result Result { /// (by the boxes of everything they paint, effects included, within one point); otherwise it /// 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. A group among `items` (Auto Grouping) is refused. +/// their edge pixels may change. The seam fills' group, when it is the lowest item, stays as it is, +/// 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}; use vectorcraft_color::tint_percent; + // The seam fills come first, under every path: kept there, they move under nothing. + let mut items = items; + let seams: Vec> = if items.first().is_some_and(|n| is_seam_fills(n)) { items.drain(..1).collect() } else { vec![] }; // Grouped by the paint: unlinked (its #rrggbb), linked (the swatch and its exact tint), a // gradient, or another paint (its label). The name is apart from it: a swatch may be named as // a color's `#rrggbb` or as "Gradients". @@ -443,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")); } @@ -516,22 +552,31 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec>) -> Result> = groups .into_iter() .map(|run| { let mut g = Node::group(d.alloc_id(), run.members); g.name = Some(run.name); Arc::new(g) }) - .collect()) + .collect(); + Ok(seams.into_iter().chain(groups).collect()) } -/// What a trace depends on: the object traced (an image, or an Image Trace object traced again), -/// its image, the image's encoded bytes, and the settings it is traced with. The tracer makes the -/// same paths of the same inputs, so a trace made away from the command ([`TraceRun`]) stands in -/// for the command's own. +/// What a trace depends on: the document it is made in and the content it was reverted to, the +/// object traced (an image, or an Image Trace object traced again), its image, the image's encoded +/// bytes, and the settings it is traced with. The tracer makes the same paths of the same inputs, +/// so a trace made away from the command ([`TraceRun`]) stands in for the command's own in the same +/// document until File › Revert replaces its content. #[derive(Clone, Debug, PartialEq)] struct TraceInputs { + /// The [`DocState::uid`](crate::DocState::uid) of the document traced in. A trace made in one + /// document never stands in for one in another, however alike their images and settings. + doc: u64, + /// The document's [`DocState::reverts`](crate::DocState::reverts) when the trace was prepared. + /// A trace prepared before File › Revert never stands in for one after it, even when the + /// restored image, pixels, object and settings are the same. + reverts: u64, target: NodeId, image: Box, /// The settings traced with, as JSON. @@ -600,20 +645,25 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result { let bytes = Arc::clone(&blob.bytes); let library = trace_library(c, s, &mut params)?; let traced_with = serde_json::to_value(¶ms).map_err(|e| EngineError::Other(e.to_string()))?; - let inputs = TraceInputs { target, image, params: traced_with, swatches: params.swatches.clone(), bytes }; + let st = s.doc()?; + let inputs = TraceInputs { doc: st.uid, reverts: st.reverts, target, image, params: traced_with, swatches: params.swatches.clone(), bytes }; Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library }) } -/// What a trace made of an image: the size in pixels it was decoded at, and the paths. +/// What a trace made of an image: the size in pixels it was decoded at, the paths, and their seam +/// fills, if any ([`seams_within`]). pub struct Traced { inputs: TraceInputs, raster: (u32, u32), res: tr::TraceResult, + seams: Option, } impl Traced { - /// Hand it to the next run of its command with the same inputs ([`TraceRun::params`]), which - /// applies it as one undo step instead of tracing again. Any other trace drops it. + /// Hand it to the next run of its command with the same inputs ([`TraceRun::params`]) in the + /// document it was made in, which applies it as one undo step instead of tracing again. Any + /// other trace drops it and traces again, a trace in another document included, and so does + /// the command after File › Revert replaced the document's content. pub fn hand_in(self, s: &mut Session) { s.trace_hand_off = Some(self); } @@ -622,6 +672,8 @@ impl Traced { /// Decode the image bytes of `inputs` and trace them with `params`, telling `steps` how far it has /// got ([`tr::trace_watched`]); [`EngineError::Cancelled`] once `steps` answers `false`. fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result { + #[cfg(test)] + TRACES_ON_THIS_THREAD.with(|n| n.set(n.get() + 1)); // An image over the tracer's size is traced scaled down (the paths are scaled back). let raster = tr::Raster::decode_to_fit(&inputs.bytes).map_err(|e| EngineError::Other(e.to_string()))?; if !steps(0, 0) { @@ -631,7 +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()), })?; - Ok(Traced { inputs: inputs.clone(), raster: (raster.width, raster.height), res }) + 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 }) +} + +/// 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); + } } /// An Image Trace made away from its command, off the UI thread (#3098). [`TraceRun::prepare`] @@ -686,17 +858,30 @@ impl TraceRun { } /// Does it still apply: would the command trace the same object, image, pixels and settings - /// now? + /// now, in the document it was prepared in, with no File › Revert since? pub fn current(&self, s: &Session) -> bool { prepare(s, self.command, &self.params).is_ok_and(|now| now.inputs == self.prepared.inputs) } + /// Has File › Revert replaced the content of the document it was prepared in since then? False + /// when that document is no longer open. + pub fn reverted(&self, s: &Session) -> bool { + let TraceInputs { doc, reverts, .. } = self.prepared.inputs; + s.documents().iter().any(|st| st.uid == doc && st.reverts != reverts) + } + /// Decode and trace the image, telling `steps` how far it has got → what it traced, or why it /// failed or stopped ([`EngineError::Cancelled`] once `steps` answers `false`). It touches no /// document, so it can run on any thread. pub fn run(&self, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result { trace_now(&self.prepared.inputs, &self.prepared.trace, steps) } + + /// How many images this thread has decoded and traced so far. + #[cfg(test)] + pub(crate) fn traces_on_this_thread() -> usize { + TRACES_ON_THIS_THREAD.with(std::cell::Cell::get) + } } pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result { @@ -711,19 +896,19 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result traced, _ => trace_now(&inputs, &trace, &|_, _| true)?, }; let TraceInputs { target, image: img, .. } = inputs; let mut warnings = keep_warnings(&trace, &res); warnings.extend(trace_warnings((img.width, img.height), raster, res.worked_at)); - // Pixel space of the decoded raster → the image object's pixel space → document. - let sx = img.width.max(1) as f64 / raster.0.max(1) as f64; - let sy = img.height.max(1) as f64 / raster.1.max(1) as f64; - let xf = img.xf * vectorcraft_geom::Affine::scale_non_uniform(sx, sy); + let xf = raster_xf(&img, raster); // Document units per raster pixel (stroke widths). let unit = xf.determinant().abs().sqrt(); + // Seam fills: strokes when the image is scaled alike in every direction; on an image stretched + // more one way, the trace outlined them in raster pixels ([`seams_within`]). + let seam_unit = seam_unit(img.xf, xf); let (npaths, anchors, colors) = (res.paths.len(), res.anchor_count(), res.palette.len()); let label = if expand { "Image Trace (Make and Expand)" } else { "Image Trace" }; // A library color fills with the swatch's displayed color (its model kept), unlinked. @@ -749,8 +934,50 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result> = seam_fills + .iter() + .flat_map(|f| &f.strokes) + .filter_map(|tp| { + 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; + } + let mut n = shape_node(d, outline.transformed(xf), None); + n.appearance = fill_only(paint_of(tp)).into(); + Some(Arc::new(n)) + }) + .collect(); let mut traced = Vec::with_capacity(res.paths.len()); for tp in res.paths { + let paint = paint_of(&tp); let path = tp.path.transformed(xf); let mut n = shape_node(d, path, None); // Shapes: a path the tracer found to be a shape is that live shape. @@ -759,10 +986,6 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result Appearance { @@ -778,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)?; @@ -799,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; @@ -1098,9 +1360,104 @@ mod color_group_tests { #[cfg(test)] mod trace_limit_tests { - use super::{MAX_TRACE_ANCHORS, keep_warnings, 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] + fn seam_fills_count_against_the_anchor_limit() { + // Two colors side by side, the edge between them anti-aliased: one seam fill along it. + let img = tr::Raster::from_fn(24, 16, |x, _| { + let share = (10.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 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, (24, 16)); + assert!(all.is_some(), "{res:?}"); + let anchors = res.anchor_count(); + 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, (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] fn keep_warnings_name_matched_colors_that_produce_no_paths() { let params = tr::TraceParams { keep_colors: vec!["#ff0000".into()], ..tr::TraceParams::default() }; @@ -1135,7 +1492,7 @@ mod trace_limit_tests { assert_eq!(w, ["Flat Logo traced the image at 946 × 710 pixels, averaged down from 16000 × 12000."]); } - // A 4000 × 3000 photo at High Fidelity Photo makes about 1.9 million anchors, which must fit; - // the limit still guards memory (about 90 bytes an anchor). Checked when the tests build. + // A 4000 × 3000 photo at Limited 64 colors, Paths 90, Corners 25 and Noise 4 makes about + // 1.9 million anchors, which must fit; the limit still guards memory (about 90 bytes an anchor). Checked when the tests build. const _: () = assert!(MAX_TRACE_ANCHORS >= 2_000_000 && MAX_TRACE_ANCHORS <= 16_000_000); } diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 446634d21c..4e086569ae 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -32,7 +32,7 @@ use crate::DocState; pub fn specs() -> Vec { let mut v = vec![ - cmd!(query "clipboard.exportSvg", "Clipboard as SVG", [], None, "{} → {svg} the copied objects as standalone SVG (null when the clipboard is empty)", always, export_svg), + cmd!(query "clipboard.exportSvg", "Clipboard as SVG", [], None, "{} → {svg} the copied objects as standalone SVG (null when the clipboard is empty). Under automation read roots it is refused while the SVG would name a linked image's file outside them (an image whose pixels the clipboard doesn't hold; a relative path is followed from the document the objects came from while it is open)", always, export_svg), cmd!( query "clipboard.importSvg", "Load SVG into Clipboard", @@ -435,14 +435,37 @@ impl Clipboard { } impl Session { - /// The internal clipboard as standalone SVG (`None` when it is empty). + /// The internal clipboard as standalone SVG (`None` when it is empty, and when the SVG would name + /// a linked image's file the caller asking now may not be shown: [`Self::clipboard_svg_refused`]). pub fn clipboard_svg(&self) -> Option { + if self.clipboard_svg_refused() { + return None; + } self.clipboard.svg() } + + /// Would the internal clipboard's SVG name a linked image's file outside the read roots in + /// force? It names the file of an image whose pixels the clipboard doesn't hold. A relative + /// path is followed from the document the objects came from while it is open; otherwise it + /// counts as outside. + pub fn clipboard_svg_refused(&self) -> bool { + self.check_clipboard_svg("clipboard.exportSvg").is_err() + } + + /// [`Self::clipboard_svg_refused`] as `cmd`'s error, which names no file or folder. + fn check_clipboard_svg(&self, cmd: &str) -> Result<()> { + if crate::file_access::current().is_none() || !self.clipboard.has_art() { + return Ok(()); + } + let from = self.docs.iter().find(|d| Some(d.uid) == self.clipboard.source_doc); + let base = from.map_or_else(super::links::LinkBase::default, super::links::LinkBase::of); + super::fileio::check_images_in(cmd, "svg", &self.clipboard.to_document(), base, &json!({})) + } } fn export_svg(s: &mut Session, _: &Value) -> Result { - Ok(json!({ "svg": s.clipboard_svg() })) + s.check_clipboard_svg("clipboard.exportSvg")?; + Ok(json!({ "svg": s.clipboard.svg() })) } fn import_svg(s: &mut Session, p: &Value) -> Result { 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 2395c51f8e..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 (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) }) @@ -513,14 +524,16 @@ pub(crate) fn edit_if_changed(s: &mut Session, label: &str, f: impl FnOnce(&D } /// Run `recolor` on `d` (it returns how many objects it changed) over `roots`, then store on their graphs what it changed -/// on the graph series marks among `roots` and inside them, so the marks keep their new paint when the graph is drawn -/// again. +/// on the graph series marks and graph labels among `roots` and inside them, so the marks and every label of a kind keep +/// their new paint when the graph is drawn again. pub(crate) fn keeping_series_paint(d: &mut Document, roots: &[NodeId], recolor: impl FnOnce(&mut Document) -> Result) -> Result { let marks = super::graph::series_marks_in(d, roots); - let before = (!marks.is_empty()).then(|| d.clone()); + let labels = super::graph::labels_in(d, roots); + let before = (!marks.is_empty() || !labels.is_empty()).then(|| d.clone()); 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, Some(roots)); } Ok(n) } diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 66295f50f2..a529a3bea9 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -9,13 +9,14 @@ //! ([`use_front_profiles`]): when they are assigned, when the working settings change, and when the //! document comes to the front or its assignment comes back (an open, a switch, a close, a revert, //! an undo or a rollback, [`Session::sync_front_profiles`]); the working spaces stay as Edit → Color -//! Settings set them. +//! Settings set them. A document drawn while another is in front draws through its own profiles +//! ([`doc_cms`]). use std::collections::BTreeMap; use std::sync::Arc; use serde_json::{Value, json}; -use vectorcraft_color::cms::{self, ColorSettings, Intent, Model, ProofTarget}; +use vectorcraft_color::cms::{self, ColorSettings, Intent, Model, Policy, ProofTarget}; use vectorcraft_color::recolor::Neutral; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::ColorMode; @@ -36,7 +37,7 @@ pub fn specs() -> Vec { "Color Settings…", ["Edit"], Some("Cmd+Shift+K"), - "{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool} set the working spaces → {rgb, cmyk, intent, bpc, profiles: [{name, kind, builtin}]}. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults", + "{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\"} set the working spaces and the color management policies → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, profiles: [{name, kind, builtin}]}. A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults", always, color_settings ), @@ -63,7 +64,7 @@ pub fn specs() -> Vec { "Assign Profile…", ["Edit"], None, - "{rgb?: profile|null, cmyk?: profile|null} tag the document with profiles (color numbers are kept; null: the working space). Colors then show and convert through the profiles assigned; the working spaces stay as edit.colorSettings set them → {rgb, cmyk}", + "{rgb?: profile|null, cmyk?: profile|null} tag the document with profiles (color numbers are kept; null: no profile, Don't Color Manage This Document, so colors show through the working space; the working space's name: that profile stays assigned when the working space changes). Colors then show and convert through the profiles assigned; the working spaces stay as edit.colorSettings set them → {rgb, cmyk}", has_doc, assign_profile ), @@ -162,12 +163,26 @@ fn on_param(p: &Value, key: &str, cmd: &str) -> Result> { switch_or(p, key, false, cmd).map(Some) } +/// The policy `p` gives for `key`, one of `allowed`, or `None` when `p` leaves it out. +fn policy_param(p: &Value, key: &str, allowed: &[Policy], cmd: &str) -> Result> { + let Some(v) = text_param(p, key, cmd)? else { return Ok(None) }; + match Policy::parse(v).filter(|x| allowed.contains(x)) { + Some(x) => Ok(Some(x)), + None => { + let ids: Vec<&str> = allowed.iter().map(Policy::id).collect(); + Err(bad(cmd, format!("`{key}` must be one of {}", ids.join(", ")))) + } + } +} + fn settings_json(st: &ColorSettings) -> Value { json!({ "rgb": st.rgb, "cmyk": st.cmyk, "intent": st.intent.id(), "bpc": st.bpc, + "rgbPolicy": st.rgb_policy.id(), + "cmykPolicy": st.cmyk_policy.id(), "profiles": cms::profiles().iter().map(|p| json!({"name": p.name, "kind": p.kind, "builtin": p.builtin})).collect::>(), }) } @@ -204,6 +219,12 @@ fn color_settings(s: &mut Session, p: &Value) -> Result { st.intent = i; } st.bpc = switch_or(p, "bpc", st.bpc, C)?; + if let Some(v) = policy_param(p, "rgbPolicy", &Policy::RGB, C)? { + st.rgb_policy = v; + } + if let Some(v) = policy_param(p, "cmykPolicy", &Policy::CMYK, C)? { + st.cmyk_policy = v; + } if st != before { cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?; // Saved for the next start when the app attached a settings file (#6335). @@ -236,6 +257,9 @@ fn load_profile(s: &mut Session, p: &Value) -> Result { } else if proof_targets(&info.name) { // A new file of the CMYK profile View → Proof Setup targets: redraw. touch_all(s); + } else { + // Documents behind the front one draw through their own profiles: those assigned it redraw. + touch_assigned(s, &info.name); } Ok(json!({"name": info.name, "kind": info.kind, "remembered": remembered})) } @@ -266,9 +290,21 @@ fn remove_profile(s: &mut Session, p: &Value) -> Result { if proof_targets(&info.name) { touch_all(s); } + // Documents behind the front one draw through their own profiles: those assigned it redraw. + touch_assigned(s, &info.name); Ok(json!({"removed": info.name})) } +/// Redraw the open documents assigned the profile `name`. +fn touch_assigned(s: &mut Session, name: &str) { + for d in &mut s.docs { + let (rgb, cmyk) = doc_profiles(&d.doc); + if [rgb, cmyk].iter().any(|n| n.as_deref() == Some(name)) { + d.revision += 1; + } + } +} + /// Whether View → Proof Setup targets the CMYK profile `name`. fn proof_targets(name: &str) -> bool { matches!(proof::view().setup.target, ProofTarget::Cmyk(t) if t == name) @@ -285,6 +321,14 @@ pub fn doc_profiles(d: &vectorcraft_doc::Document) -> (Option, Option Arc { + let (rgb, cmyk) = doc_profiles(d); + cms::for_document(rgb.as_deref(), cmyk.as_deref()) +} + fn assign_profile(s: &mut Session, p: &Value) -> Result { const C: &str = "edit.assignProfile"; let (mut rgb, mut cmyk) = doc_profiles(&s.doc()?.doc); @@ -506,7 +550,12 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode, if !convert { return 0; } - let conv = mode_converter(mode, intent, grays); + convert_colors(d, &mode_converter(mode, intent, grays)) +} + +/// Every color of `d` that [`set_color_mode`] converts, converted with `conv` → how many colors of +/// the art changed, as [`set_color_mode`] counts them. +fn convert_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Color) -> usize { for sw in d.swatches_iter_mut() { match &mut sw.paint { Paint::Solid { color, .. } => *color = conv(color), @@ -514,6 +563,11 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode, for st in &mut g.gradient.stops { st.color = conv(&st.color); } + if let Some(freeform) = &mut g.freeform { + for point in &mut freeform.points { + point.color = conv(&point.color); + } + } } _ => {} } @@ -597,6 +651,102 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode, in_art } +/// Apply the color management policies of Edit → Color Settings to `d`, a document being opened: +/// each RGB or CMYK profile it is tagged with that is not the working space of its model is kept +/// (Preserve Embedded Profiles), taken off with the color numbers kept (Off, Preserve Numbers), or +/// taken off after the colors of that model were converted from it into the working space with the +/// working intent (Convert to Working Space). A profile that is not available here is taken off +/// by Off and Preserve Numbers and kept by Convert to Working Space, which has nothing to convert +/// from. → a note for each profile, and whether `d` changed. +pub(crate) fn apply_open_policies(d: &mut vectorcraft_doc::Document) -> (Vec, bool) { + let working = cms::working_settings(); + let (rgb, cmyk) = doc_profiles(d); + let mut notes = Vec::new(); + // What each model's policy does with its profile: `None` keeps it; `Some` takes it off, after + // converting the colors from the profile it holds. + let mut decide = |label: &str, tag: Option, working: &str, policy: Policy, kind: cms::ProfileKind| -> Option> { + let tag = tag.filter(|t| t != working)?; + let available = cms::profile(&tag).is_some_and(|p| p.kind == kind); + match policy { + Policy::PreserveEmbedded => None, + Policy::Off | Policy::PreserveNumbers => { + notes.push(format!( + "the {label} profile “{tag}” the file is tagged with was not used: Color Settings' {label} policy is {}", + policy.label() + )); + Some(None) + } + Policy::Convert if available => { + notes.push(format!( + "the {label} colors were converted from the profile “{tag}” the file is tagged with into the working space “{working}”" + )); + Some(Some(tag)) + } + Policy::Convert => { + notes.push(format!("the {label} profile “{tag}” the file is tagged with is not available, so its colors were not converted")); + None + } + } + }; + let rgb_do = decide("RGB", rgb, &working.rgb, working.rgb_policy, cms::ProfileKind::Rgb); + let cmyk_do = decide("CMYK", cmyk, &working.cmyk, working.cmyk_policy, cms::ProfileKind::Cmyk); + if rgb_do.is_none() && cmyk_do.is_none() { + return (notes, false); + } + let (from_rgb, from_cmyk) = (rgb_do.clone().flatten(), cmyk_do.clone().flatten()); + if from_rgb.is_some() || from_cmyk.is_some() { + let source = cms::for_document(from_rgb.as_deref(), from_cmyk.as_deref()); + let dest = cms::working(); + let intent = working.intent; + let (rgb_on, cmyk_on) = (from_rgb.is_some(), from_cmyk.is_some()); + let conv = |c: &Color| match c { + Color::Rgb { .. } if rgb_on => source.convert_into(&dest, c, intent), + Color::Cmyk { .. } if cmyk_on => source.convert_into(&dest, c, intent), + _ => *c, + }; + convert_colors(d, &conv); + convert_setting_colors(d, &conv); + } + if rgb_do.is_some() { + d.color_profiles.rgb = None; + } + if cmyk_do.is_some() { + d.color_profiles.cmyk = None; + } + (notes, true) +} + +/// The colors of `d` outside its art that [`convert_colors`] leaves, converted with `conv`: each +/// artboard's background, the transparency grid and simulated paper colors of Document Setup, and +/// the fill and stroke of the character and paragraph styles. +fn convert_setting_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Color) { + for c in d.artboards.iter_mut().filter_map(|a| a.color.as_mut()) { + *c = conv(c); + } + for c in &mut d.setup.grid_colors { + *c = conv(c); + } + // A tint of a global swatch is the converted swatch's color at its tint, which + // [`convert_colors`] already gave it. + let bases = global_bases(d); + let mut f = |c: &Color, link: proof::Link| mode_color(c, link, &bases, conv); + for styles in [&mut d.char_styles, &mut d.para_styles] { + if !styles.iter().any(|s| s.attrs.contains_key("fill") || s.attrs.contains_key("stroke")) { + continue; + } + for def in styles.iter_mut() { + for key in ["fill", "stroke"] { + let Some(value) = def.attrs.get_mut(key) else { continue }; + let Ok(mut paint) = serde_json::from_value::(value.clone()) else { continue }; + map_paint_colors(&mut paint, &mut f); + if let Ok(v) = serde_json::to_value(&paint) { + *value = v; + } + } + } + } +} + /// [`proof::map_node_colors`] over `n`'s subtree, then [`map_more_colors`]. fn map_art_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { proof::map_node_colors(n, f); @@ -653,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() { @@ -662,11 +812,21 @@ fn map_graph_colors(g: &mut vectorcraft_doc::GraphSpec, f: &mut dyn FnMut(&Color } } let styles = &mut g.label_styles; - for st in [&mut styles.values, &mut styles.categories, &mut styles.legend].into_iter().flatten() { - map_paint_colors(&mut st.fill, f); + // A legend fill of the labels' own stays theirs when `f` makes it black. The default black legend fill stays black, + // so the labels on dark pie wedges are still drawn white. + styles.mark_own_legend_fill(); + let own = styles.legend_fill_is_own(); + for (st, fill) in [(&mut styles.values, true), (&mut styles.categories, true), (&mut styles.legend, own)] { + let Some(st) = st else { continue }; + if fill { + map_paint_colors(&mut st.fill, f); + } 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/compositefonts.rs b/crates/engine/src/cmd/compositefonts.rs index 3925612a14..131695e33e 100644 --- a/crates/engine/src/cmd/compositefonts.rs +++ b/crates/engine/src/cmd/compositefonts.rs @@ -1,15 +1,18 @@ //! Type › Composite Fonts…: the document's composite fonts ([`vectorcraft_doc::CompositeFont`]), //! which set each class of character (Kanji, Kana, Punctuation, Symbols, Roman, Numerals) in a -//! font of its own. Type names a composite font as its family, and the font menus list them first. -//! The font database holds the active document's composite fonts ([`sync`]); a file exported here -//! carries them to another document. +//! font of its own, and the characters of each custom character set in the set's font. Type names +//! a composite font as its family, and the font menus list them first. The font database holds the +//! active document's composite fonts ([`sync`]); a file exported here carries them to another +//! document. //! //! Behavior reference (public documentation): -//! . +//! , +//! custom character sets: +//! . use serde_json::{Map, Value, json}; -use vectorcraft_doc::text::{COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX}; -use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts}; +use vectorcraft_doc::text::{COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX}; +use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet}; use vectorcraft_text::FontDb; use super::fileio::{read_file_head, write_file}; @@ -26,6 +29,10 @@ const MAX_FILE_BYTES: usize = 4 << 20; /// The keys a part may give. const PART_KEYS: [&str; 7] = ["font", "style", "size", "baseline", "hScale", "vScale", "scaleAtCenter"]; +/// The keys a custom character set may give: its name and characters, then its part's values +/// (a set is never scaled at the center). +const SET_KEYS: [&str; 8] = ["name", "characters", "font", "style", "size", "baseline", "hScale", "vScale"]; + pub fn specs() -> Vec { vec![ cmd!( @@ -33,7 +40,7 @@ pub fn specs() -> Vec { "Composite Fonts", [], None, - "{} the active document's composite fonts → {fonts: [{name, parts: {kanji, kana, punctuation, symbols, roman, numerals: {font, style, size: % of the type size, baseline: % of the type size (positive raises), hScale: %, vScale: %, scaleAtCenter?: bool}}}]}", + "{} the active document's composite fonts → {fonts: [{name, parts: {kanji, kana, punctuation, symbols, roman, numerals: {font, style, size: % of the type size, baseline: % of the type size (positive raises), hScale: %, vScale: %, scaleAtCenter?: bool}}, custom?: [{name, characters, font, style, size, baseline, hScale, vScale}]}]}", has_doc, list ), @@ -42,7 +49,7 @@ pub fn specs() -> Vec { "Composite Fonts…", ["Type"], None, - "{fonts: [{name, parts: {kanji: {font, style?: \"Regular\", size?: % 10..400 = 100, baseline?: % -100..100 = 0}, kana?, punctuation?, symbols?, roman?, numerals?: {font, style?, size?, baseline?, hScale?, vScale?: % 10..400 = 100, scaleAtCenter?: bool = false}}}]} replace the active document's composite fonts (Type › Composite Fonts…'s OK), as one undo step, none when nothing changes. A composite font sets each class of character in its part's font: kanji (the base: ideographs, full-width letters and digits and anything no other class takes), kana (hiragana and katakana, both widths), punctuation (East Asian and full-width punctuation, quotes and dashes), symbols (arrows, math, shapes and other symbols), roman (half-width letters, their punctuation and spaces) and numerals (the digits 0 to 9); a part left out is the kanji part. size and baseline are percent of the type's size, hScale and vScale scale kana, roman and numerals only, and scaleAtCenter (kana only) scales them from the em box's center instead of the baseline. Names are trimmed, unique in any case, at most 255 characters, and may not name an installed font; a part's font may not be a composite font; at most 256. Type set in a composite font names it as its family (text.setStyle {font: name}), and the font menus list composite fonts first. A font taken out stays named by its type, which then shows as missing → {fonts}", + "{fonts: [{name, parts: {kanji: {font, style?: \"Regular\", size?: % 10..400 = 100, baseline?: % -100..100 = 0}, kana?, punctuation?, symbols?, roman?, numerals?: {font, style?, size?, baseline?, hScale?, vScale?: % 10..400 = 100, scaleAtCenter?: bool = false}}, custom?: [{name, characters?: string = \"\", font?, style?, size?, baseline?, hScale?, vScale?}]}]} replace the active document's composite fonts (Type › Composite Fonts…'s OK), as one undo step, none when nothing changes. A composite font sets each class of character in its part's font: kanji (the base: ideographs, full-width letters and digits and anything no other class takes), kana (hiragana and katakana, both widths), punctuation (East Asian and full-width punctuation, quotes and dashes), symbols (arrows, math, shapes and other symbols), roman (half-width letters, their punctuation and spaces) and numerals (the digits 0 to 9); a part left out is the kanji part. size and baseline are percent of the type's size, hScale and vScale scale kana, roman and numerals only, and scaleAtCenter (kana only) scales them from the em box's center instead of the baseline. custom lists custom character sets: each sets the characters it lists in its own font, style, size, baseline and scales (values left out are the kanji part's), ahead of their class; a character two sets list is set by the later one. A set's name is trimmed and unique in the font in any case; its characters are each listed once, at most 8192, none a control character or past U+FFFF; at most 64 sets. Names are trimmed, unique in any case, at most 255 characters, and may not name an installed font; a part's font may not be a composite font; at most 256. Type set in a composite font names it as its family (text.setStyle {font: name}), and the font menus list composite fonts first. A font taken out stays named by its type, which then shows as missing → {fonts}", has_doc, set ), @@ -51,7 +58,7 @@ pub fn specs() -> Vec { "Export Composite Fonts", [], None, - "{path?: .vccomposite file, names?: [name] (default: all), fonts?: [{name, parts}] (as type.compositeFonts.set takes them)} write the active document's composite fonts (all, or those named, any case), or the fonts given, to a file type.compositeFonts.import reads; without path the file's text comes back as data → {path, count} | {data, count}", + "{path?: .vccomposite file, names?: [name] (default: all), fonts?: [{name, parts}] (as type.compositeFonts.set takes them)} write the active document's composite fonts (all, or those named, any case), or the fonts given, to a file type.compositeFonts.import reads (a file over 4 MB is refused); without path the file's text comes back as data → {path, count} | {data, count}", has_doc, export ), @@ -121,8 +128,8 @@ fn list(s: &mut Session, _: &Value) -> Result { /// copy of the Kanji part, and keys or values a part can't take refused. fn parse_font(v: &Value, c: &str) -> Result { let o = v.as_object().ok_or_else(|| bad(c, "each font must be {name, parts}"))?; - if let Some(k) = o.keys().find(|k| !["name", "parts"].contains(&k.as_str())) { - return Err(bad(c, format!("unknown key `{k}`; a font takes name and parts"))); + if let Some(k) = o.keys().find(|k| !["name", "parts", "custom"].contains(&k.as_str())) { + return Err(bad(c, format!("unknown key `{k}`; a font takes name, parts and custom"))); } let raw = o.get("name").and_then(Value::as_str).ok_or_else(|| bad(c, "each font needs a name"))?; let name = CompositeFont::clean_name(raw) @@ -140,7 +147,17 @@ fn parse_font(v: &Value, c: &str) -> Result { serde_json::from_value(p.clone()).map(Some).map_err(|e| bad(c, format!("`{name}`: {}: {e}", class.key()))) }; let kanji = part(CharClass::Kanji)?.ok_or_else(|| bad(c, format!("`{name}`: give the kanji part")))?; - let mut f = CompositeFont { name: name.clone(), parts: CompositeParts::all(kanji) }; + let custom = match o.get("custom") { + None => Vec::new(), + Some(Value::Array(sets)) => { + if sets.len() > CUSTOM_SETS_MAX { + return Err(bad(c, format!("`{name}`: a composite font keeps at most {CUSTOM_SETS_MAX} character sets"))); + } + sets.iter().map(|s| parse_set(s, &name, &kanji, c)).collect::>>()? + } + Some(_) => return Err(bad(c, format!("`{name}`: custom must be a list of character sets"))), + }; + let mut f = CompositeFont { name: name.clone(), parts: CompositeParts::all(kanji), custom }; for class in CharClass::ALL.into_iter().skip(1) { if let Some(p) = part(class)? { *f.parts.get_mut(class) = p; @@ -150,6 +167,38 @@ fn parse_font(v: &Value, c: &str) -> Result { Ok(f) } +/// Custom character set `v` of composite font `font` from command parameters or a file: its name +/// trimmed, the part values it leaves out those of `kanji`, and keys or values it can't take +/// refused. [`CompositeFont::check`] checks its characters and values. +fn parse_set(v: &Value, font: &str, kanji: &CompositePart, c: &str) -> Result { + let o = v.as_object().ok_or_else(|| bad(c, format!("`{font}`: each character set must be {{name, characters, font…}}")))?; + if let Some(k) = o.keys().find(|k| !SET_KEYS.contains(&k.as_str())) { + return Err(bad(c, format!("`{font}`: unknown key `{k}` in a character set"))); + } + let raw = o.get("name").and_then(Value::as_str).ok_or_else(|| bad(c, format!("`{font}`: each character set needs a name")))?; + let name = CompositeFont::clean_name(raw) + .ok_or_else(|| bad(c, format!("`{raw}` can't name a character set (1 to {COMPOSITE_NAME_MAX} characters, no control characters)")))?; + let characters = match o.get("characters") { + None => String::new(), + Some(Value::String(s)) => s.clone(), + Some(_) => return Err(bad(c, format!("`{font}`: `{name}`: characters must be a string"))), + }; + // Checked here as well as by `check`, so a huge list is refused before it is copied again. + if characters.chars().nth(CUSTOM_CHARS_MAX).is_some() { + return Err(bad(c, format!("`{font}`: `{name}`: a character set keeps at most {CUSTOM_CHARS_MAX} characters"))); + } + let mut part = serde_json::to_value(kanji).map_err(|e| bad(c, e.to_string()))?; + if let Some(p) = part.as_object_mut() { + for k in &SET_KEYS[2..] { + if let Some(given) = o.get(*k) { + p.insert(k.to_string(), given.clone()); + } + } + } + let part: CompositePart = serde_json::from_value(part).map_err(|e| bad(c, format!("`{font}`: `{name}`: {e}")))?; + Ok(CustomCharSet { name, characters, part }) +} + /// Error unless `fonts` can stand together in a document: names unique in any case, none naming /// an installed font, no part set in a composite font, and at most [`COMPOSITE_FONTS_MAX`]. fn check_set(fonts: &[CompositeFont], c: &str) -> Result<()> { @@ -167,10 +216,10 @@ fn check_set(fonts: &[CompositeFont], c: &str) -> Result<()> { } } for f in fonts { - for class in CharClass::ALL { - let font = &f.parts.get(class).font; + let classes = CharClass::ALL.into_iter().map(|class| (class.key(), &f.parts.get(class).font)); + for (part, font) in classes.chain(f.custom.iter().map(|s| (s.name.as_str(), &s.part.font))) { if names.contains(&font.to_lowercase()) || db.composite_font(font).is_some() { - return Err(bad(c, format!("`{}`: {} is set in `{font}`, a composite font", f.name, class.key()))); + return Err(bad(c, format!("`{}`: {} is set in `{font}`, a composite font", f.name, part))); } } } @@ -260,6 +309,9 @@ fn export(s: &mut Session, p: &Value) -> Result { let mut file = Map::new(); file.insert("compositeFonts".into(), json!(fonts)); let text = serde_json::to_string_pretty(&file).map_err(|e| bad(C, e.to_string()))?; + if text.len() > MAX_FILE_BYTES { + return Err(bad(C, "the composite fonts make a file larger than 4 MB, which Import can't read; export fewer of them")); + } match path { Some(path) => { write_file(path, text.as_bytes())?; diff --git a/crates/engine/src/cmd/compositefonts/tests.rs b/crates/engine/src/cmd/compositefonts/tests.rs index 434f2e383a..751cb49ef0 100644 --- a/crates/engine/src/cmd/compositefonts/tests.rs +++ b/crates/engine/src/cmd/compositefonts/tests.rs @@ -478,6 +478,75 @@ fn an_opened_file_measures_its_type_in_its_own_composite_fonts() { assert_eq!(actual.cached_bounds, Some(expected)); } +/// The label of dimension `id` in `doc`. +fn label(doc: &vectorcraft_doc::Document, id: u64) -> vectorcraft_doc::TextObject { + let node = doc.node(NodeId(id)).unwrap(); + node.children().unwrap().iter().find_map(|n| if let NodeKind::Text(t) = &n.kind { Some((**t).clone()) } else { None }).unwrap() +} + +/// The center of label `t`'s measured box on the page. +fn label_center(t: &vectorcraft_doc::TextObject) -> vectorcraft_geom::Point { + t.xf * t.cached_bounds.unwrap().center() +} + +/// Whether every character of label `t` is filled in CMYK. +fn label_in_cmyk(t: &vectorcraft_doc::TextObject) -> bool { + !t.runs.is_empty() && t.runs.iter().all(|r| matches!(r.style.fill.color(), Some(vectorcraft_color::Color::Cmyk { .. }))) +} + +/// The native file of a CMYK document whose composite font `name` sets Roman at full size, with a +/// dimension whose label is set in it and whose label's characters are saved in RGB, so opening +/// the file draws the dimension again → (the file, the dimension's id, the center of its label as +/// drawn in the document's own composite font). +fn dimension_file(name: &str) -> (Vec, u64, vectorcraft_geom::Point) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400, "colorMode": "cmyk"})).unwrap(); + let mut full = font(name); + full["parts"]["roman"]["size"] = json!(100); + s.execute("type.compositeFonts.set", &json!({"fonts": [full]})).unwrap(); + let line = s.execute("shape.line", &json!({"x1": 100, "y1": 100, "x2": 172, "y2": 100})).unwrap()["id"].as_u64().unwrap(); + let id = s + .execute( + "dimension.create", + &json!({"source": {"kind": "segment", "edge": {"node": line, "subpath": 0, "segment": 0}}, + "options": {"units": "in", "precision": 2, "fontFamily": name, "fontSize": 20}}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(); + let mut doc = (*s.doc().unwrap().doc).clone(); + let drawn = label(&doc, id); + assert!(label_in_cmyk(&drawn)); + let center = label_center(&drawn); + let mut label_id = None; + doc.node(NodeId(id)).unwrap().walk(&mut |n| { + if matches!(n.kind, NodeKind::Text(_)) { + label_id = Some(n.id); + } + }); + if let Some(NodeKind::Text(t)) = doc.node_mut(label_id.unwrap()).map(|n| &mut n.kind) { + for r in &mut t.runs { + r.style.fill = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb8(0, 0, 0)); + } + } + (vectorcraft_format::save_file(&doc), id, center) +} + +/// A file whose dimensions are drawn again when it opens (their art is not in the document's color +/// mode) draws their labels in its own composite fonts, not in those of the front document, which +/// defines the label's font name with Roman at half size: each label stays centered on its anchor. +#[test] +fn an_opened_file_draws_its_dimension_labels_in_its_own_composite_fonts() { + let (bytes, id, center) = dimension_file("CF Dimension"); + let mut s = session(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Dimension")]})).unwrap(); + let file = crate::cmd::fileio::read_for_open("dimension.vectorcraft", &bytes, None, &json!({}), false, false).unwrap(); + crate::cmd::fileio::open_read(&mut s, file).unwrap(); + let opened = label(&s.doc().unwrap().doc, id); + assert!(label_in_cmyk(&opened)); + assert!((label_center(&opened) - center).hypot() < 1e-6, "{:?} vs {center:?}", label_center(&opened)); +} + /// Threaded type read from a file flows through its frames in the file's own composite fonts, when /// no open document defines them. #[test] @@ -536,6 +605,40 @@ fn a_document_replaced_in_the_back_is_measured_when_the_front_one_closes() { assert_eq!(actual.cached_bounds, Some(expected)); } +/// A document replaced in front (File › Revert) whose dimensions are drawn again draws their labels +/// in its new composite fonts, not in those it had before. +#[test] +fn a_document_replaced_in_front_draws_its_dimension_labels_in_its_own_composite_fonts() { + let (bytes, id, center) = dimension_file("CF Reverted"); + let mut s = session(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Reverted")]})).unwrap(); + assert!(s.replace_document(0, vectorcraft_format::load(&bytes).unwrap())); + let replaced = label(&s.doc().unwrap().doc, id); + assert!(label_in_cmyk(&replaced)); + assert!((label_center(&replaced) - center).hypot() < 1e-6, "{:?} vs {center:?}", label_center(&replaced)); +} + +/// A document replaced in the back draws its dimension labels in its own composite fonts, while the +/// front document keeps its definition of the same name registered; the labels stay where they are +/// when the document comes to the front. +#[test] +fn a_document_replaced_in_the_back_draws_its_dimension_labels_in_its_own_composite_fonts() { + let (bytes, id, center) = dimension_file("CF Back Dimension"); + let mut s = session(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Back Dimension")]})).unwrap(); + assert!(s.replace_document(0, vectorcraft_format::load(&bytes).unwrap())); + assert_eq!(s.active_index(), Some(1)); + let front = vectorcraft_text::FontDb::global().composite_font("CF Back Dimension").unwrap(); + assert_eq!(front.parts.get(vectorcraft_doc::CharClass::Roman).size, 50.0); + let replaced = label(&s.documents()[0].doc, id); + assert!(label_in_cmyk(&replaced)); + assert!((label_center(&replaced) - center).hypot() < 1e-6, "{:?} vs {center:?}", label_center(&replaced)); + assert!(s.set_active(0)); + let shown = label(&s.doc().unwrap().doc, id); + assert!((label_center(&shown) - center).hypot() < 1e-6, "{:?} vs {center:?}", label_center(&shown)); +} + /// The type of document `index` with id `id`, wherever its tab is. fn text_in(s: &Session, index: usize, id: u64) -> vectorcraft_doc::TextObject { match &s.documents()[index].doc.node(NodeId(id)).unwrap().kind { @@ -568,10 +671,11 @@ fn a_document_replaced_in_the_back_is_measured_before_it_comes_to_the_front() { } /// Type a document replaced in the back sets in a composite font that only the front document -/// defines is measured in that font while the front one is registered, and again, as missing, when -/// the replaced document comes to the front. +/// defines is measured as missing, though the front one is registered, also when the replaced +/// document defines no composite font, and still as missing when it comes to the front. #[test] -fn a_document_replaced_in_the_back_measures_a_font_it_lacks_again_in_front() { +fn a_document_replaced_in_the_back_measures_a_font_it_lacks_as_missing() { + let db = vectorcraft_text::FontDb::global(); let mut s = session(); let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab12", "size": 20, "font": "CF Lacked"})).unwrap()["id"].as_u64().unwrap(); let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc); @@ -579,8 +683,16 @@ fn a_document_replaced_in_the_back_measures_a_font_it_lacks_again_in_front() { s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Lacked")]})).unwrap(); assert!(s.replace_document(0, vectorcraft_format::load(&bytes).unwrap())); let back = text_in(&s, 0, id); - let expected = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &back).bounds; - assert_eq!(back.cached_bounds, Some(expected)); + assert!(s.documents()[0].doc.composite_fonts.is_empty()); + let in_front = vectorcraft_text::layout(db, &back).bounds; + // The same type set in a family nothing defines. + let mut nowhere = back.clone(); + for r in &mut nowhere.runs { + r.style.font_family = "No Such Family CF Lacked".into(); + } + let missing = vectorcraft_text::layout(db, &nowhere).bounds; + assert!((in_front.width() - missing.width()).abs() > 1e-6, "the front document's font draws otherwise"); + assert_eq!(back.cached_bounds, Some(missing)); assert!(s.set_active(0)); assert!(vectorcraft_text::FontDb::global().composite_font("CF Lacked").is_none()); let actual = text(&s, id); @@ -744,3 +856,127 @@ fn composite_fonts_export_and_import() { assert!(s.execute("type.compositeFonts.export", &json!({"path": " "})).is_err()); let _ = std::fs::remove_dir_all(&dir); } + +/// `font(name)` with two custom character sets: "Marks" (x and A) in Inter at 150%, and "A only" +/// (A) in Source Sans 3, which sets A since it comes later. +fn font_with_sets(name: &str) -> Value { + let mut v = font(name); + v["custom"] = json!([ + {"name": " Marks ", "characters": "xA", "font": "Inter", "size": 150, "hScale": 90}, + {"name": "A only", "characters": "A"}, + ]); + v +} + +/// Custom character sets are set with the font as one undo step, take values they leave out from +/// the Kanji part, set the characters they list ahead of their class (the later set winning), are +/// saved with the document, and measure type again when they change. +#[test] +fn custom_character_sets_set_their_characters() { + let mut s = session(); + let before = steps(&s); + let r = s.execute("type.compositeFonts.set", &json!({"fonts": [font_with_sets("CF Sets")]})).unwrap(); + assert_eq!(r["fonts"][0]["custom"][0]["name"], "Marks"); + assert_eq!(steps(&s), before + 1); + let f = s.doc().unwrap().doc.composite_fonts[0].clone(); + assert_eq!(f.custom.len(), 2); + assert_eq!((f.custom[0].part.font.as_str(), f.custom[0].part.size, f.custom[0].part.h_scale), ("Inter", 150.0, 90.0)); + assert_eq!((f.custom[1].part.font.as_str(), f.custom[1].part.size), ("Source Sans 3", 100.0)); + // The same sets again change nothing. + s.execute("type.compositeFonts.set", &json!({"fonts": [font_with_sets("CF Sets")]})).unwrap(); + assert_eq!(steps(&s), before + 1); + let back = vectorcraft_format::load(&vectorcraft_format::save_file(&s.doc().unwrap().doc)).unwrap(); + assert_eq!(*back.composite_fonts, *s.doc().unwrap().doc.composite_fonts); + + let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "xAB", "size": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "font": "CF Sets"})).unwrap(); + let db = vectorcraft_text::FontDb::global(); + let face = |family: &str| db.face(family, "Regular").unwrap().id(); + let lay = vectorcraft_text::layout(db, &text(&s, id)); + let fonts: Vec = lay.glyphs.iter().map(|g| g.font_id).collect(); + assert_eq!(fonts, [face("Inter"), face("Source Sans 3"), face("JetBrains Mono")]); + // Taking x out of Marks sets it in its class's font again, measured in the same step. + let wide = text(&s, id).cached_bounds.unwrap().width(); + let mut fewer = font_with_sets("CF Sets"); + fewer["custom"][0]["characters"] = json!("A"); + s.execute("type.compositeFonts.set", &json!({"fonts": [fewer]})).unwrap(); + assert!(text(&s, id).cached_bounds.unwrap().width() < wide - 1.0); + s.execute("edit.undo", &json!({})).unwrap(); + assert!((text(&s, id).cached_bounds.unwrap().width() - wide).abs() < 1e-6); +} + +/// Bad custom character sets are refused with an error and no undo step. +#[test] +fn bad_custom_character_sets_are_refused() { + let mut s = session(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font_with_sets("CF Sets Base")]})).unwrap(); + let before = steps(&s); + let with = |f: &dyn Fn(&mut Value)| { + let mut v = font_with_sets("CF Sets Refused"); + f(&mut v); + json!({"fonts": [v]}) + }; + let many: String = (0x4E00u32..).filter_map(char::from_u32).take(8193).collect(); + let sets: Vec = (0..65).map(|i| json!({"name": format!("S{i}")})).collect(); + for bad in [ + with(&|v| v["custom"] = json!("Marks")), + with(&|v| v["custom"] = Value::Null), + with(&|v| v["custom"][0]["characters"] = Value::Null), + with(&|v| v["custom"][0] = json!("Marks")), + with(&|v| v["custom"][0]["name"] = json!(" ")), + with(&|v| { + v["custom"][0].as_object_mut().unwrap().remove("name"); + }), + with(&|v| v["custom"][1]["name"] = json!("marks")), + with(&|v| v["custom"][0]["characters"] = json!(["※"])), + with(&|v| v["custom"][0]["characters"] = json!("※※")), + with(&|v| v["custom"][0]["characters"] = json!("A\n")), + with(&|v| v["custom"][0]["characters"] = json!("😀")), + with(&|v| v["custom"][0]["characters"] = json!(many.clone())), + with(&|v| v["custom"] = json!(sets.clone())), + with(&|v| v["custom"][0]["size"] = json!(5)), + with(&|v| v["custom"][0]["size"] = json!("50")), + with(&|v| v["custom"][0]["scaleAtCenter"] = json!(true)), + with(&|v| v["custom"][0]["scaleAtCenter"] = json!(false)), + with(&|v| v["custom"][0]["font"] = json!("")), + with(&|v| v["custom"][0]["font"] = json!("CF Sets Base")), + with(&|v| v["custom"][0]["width"] = json!(3)), + ] { + let e = s.execute("type.compositeFonts.set", &bad); + assert!(e.is_err(), "accepted {bad}"); + assert_eq!(names(&s), ["CF Sets Base"]); + assert_eq!(steps(&s), before); + } + // A set without characters is kept: it sets nothing. + let ok = with(&|v| v["custom"][0]["characters"] = json!("")); + s.execute("type.compositeFonts.set", &ok).unwrap(); + assert_eq!(s.doc().unwrap().doc.composite_fonts[0].custom[0].characters, ""); +} + +/// Export writes the custom character sets and Import reads them back; a file whose set is bad is +/// refused. +#[test] +fn custom_character_sets_export_and_import() { + let mut s = session(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font_with_sets("CF Sets IO")]})).unwrap(); + let data = s.execute("type.compositeFonts.export", &json!({})).unwrap(); + let mut t = session(); + t.execute("type.compositeFonts.import", &json!({"data": data["data"]})).unwrap(); + assert_eq!(*t.doc().unwrap().doc.composite_fonts, *s.doc().unwrap().doc.composite_fonts); + let text = data["data"].as_str().unwrap().replace("\"A only\"", "\"marks\""); + let mut u = session(); + assert!(u.execute("type.compositeFonts.import", &json!({"data": text})).is_err()); + assert!(names(&u).is_empty()); + // Fonts whose file would be larger than Import reads are refused. + let full: String = (0x4E00u32..).filter_map(char::from_u32).take(8192).collect(); + let sets: Vec = (0..64).map(|i| json!({"name": format!("S{i}"), "characters": full})).collect(); + let big: Vec = (0..3) + .map(|i| { + let mut f = font(&format!("CF Sets Big {i}")); + f["custom"] = json!(sets); + f + }) + .collect(); + let e = s.execute("type.compositeFonts.export", &json!({"fonts": big})).unwrap_err(); + assert!(e.to_string().contains("4 MB"), "{e}"); +} diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index ebef729fd3..c5d3d70fd2 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 ), @@ -53,10 +53,19 @@ pub fn specs() -> Vec { "Flare", [], None, - "{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?} → {id}", + "{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: places the rings along the path anew, keeping their count and sizes)} → {id}", has_doc, flare ), + cmd!( + "shape.circleThroughPoints", + "Circle Through Points", + [], + None, + "{points?: [[x, y], [x, y], [x, y]] (left out: the three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the three points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same or three on one line are an error, and nothing is drawn", + has_doc, + circle_through_points + ), cmd!("shape.line", "Line Segment", [], None, "{x1, y1, x2, y2, fill?: bool (Fill Line: the current fill, else none)} → {id}", has_doc, line), cmd!("shape.spiral", "Spiral", [], None, "{cx, cy, radius, decay=80 (%), segments=10, clockwise?} → {id}", has_doc, spiral), cmd!( @@ -64,7 +73,7 @@ pub fn specs() -> Vec { "Arc", [], None, - "{x1, y1, x2, y2, closed?, slope?} or {x, y, lengthX, lengthY, reference?, baseAlong?: x|y, slope?, closed?, fillArc?} → {id}", + "{x1, y1, x2, y2, closed?, slope?: −100…100 (default 100), rotation?: deg clockwise about (x1, y1)} or {x, y, lengthX, lengthY, reference?: 0–8 (default 0), baseAlong?: x|y (either case; default x), slope?: −100…100 (default 50), closed?, fillArc?, rotation?: deg clockwise about the reference point (x, y)} (0: upright); a reference or baseAlong given as anything else (null included) or a slope outside its range is an error and draws nothing → {id}", has_doc, arc ), @@ -73,7 +82,7 @@ pub fn specs() -> Vec { "Rectangular Grid", [], None, - "{x, y, width, height, rows=5, columns=5, rowSkew=0, columnSkew=0 (−500…500 %: + crowds the horizontal dividers toward the top, the vertical ones toward the right), frame=true (the outside as one rectangle, else its four sides), fill=false (the current fill, else none), rotation?: deg clockwise about the centre (0: upright)} → {id}", + "{x, y, width, height, rows=5, columns=5 (whole numbers; at most 999), rowSkew=0, columnSkew=0 (−500…500 %: + crowds the horizontal dividers toward the top, the vertical ones toward the right), frame=true (the outside as one rectangle, else its four sides), fill=false (the current fill, else none), rotation?: deg clockwise about the centre (0: upright)} → {id}", has_doc, rect_grid ), @@ -82,7 +91,7 @@ pub fn specs() -> Vec { "Polar Grid", [], None, - "{x, y, width, height, concentric=5, radial=5, concentricSkew=0, radialSkew=0 (−500…500 %: + crowds the ellipses toward the outside, the radial dividers clockwise of the top one), compound=false (the ellipses pair up into compound-path rings), fill=false (the current fill, else none), rotation?: deg clockwise about the centre (0: upright)} → {id}", + "{x, y, width, height, concentric=5, radial=5 (whole numbers; at most 999), concentricSkew=0, radialSkew=0 (−500…500 %: + crowds the ellipses toward the outside, the radial dividers clockwise of the top one), compound=false (the ellipses pair up into compound-path rings), fill=false (the current fill, else none), rotation?: deg clockwise about the centre (0: upright)} → {id}", has_doc, polar_grid ), @@ -131,14 +140,21 @@ pub(crate) fn add_look(s: &mut Session, label: &str, kind: NodeKind, look: NewAr /// [`add_look`] that selects the new object only when `select` is set; otherwise the selection /// stays as it was. pub(crate) fn insert_look(s: &mut Session, label: &str, kind: NodeKind, look: NewArt, name: Option, select: bool) -> Result { - insert_look_turned(s, label, kind, look, name, select, 0.0) + insert_look_turned(s, label, kind, look, name, select, 0.0, true) } /// [`add_art`] for an object made turned by a `rotation` param (degrees, clockwise on the page): /// its bounding box turns with it, as after the Rotate tool. fn add_art_turned(s: &mut Session, label: &str, kind: NodeKind, rotation: f64) -> Result { let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); - insert_look_turned(s, label, kind, look, None, true, bbox_turn(rotation)) + insert_look_turned(s, label, kind, look, None, true, bbox_turn(rotation), true) +} + +/// [`add_art`] for an object whose geometry must stay where it was computed: it is not +/// pixel-aligned, even while the document's Align New Objects to Pixel Grid is on. +fn add_art_unaligned(s: &mut Session, label: &str, kind: NodeKind) -> Result { + let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); + insert_look_turned(s, label, kind, look, None, true, 0.0, false) } /// The bounding-box angle (counter-clockwise, as `Node::bbox_angle` and the Rotate tool keep it) @@ -162,8 +178,10 @@ fn constrained_turn(s: &Session, rotation: f64) -> f64 { } } -/// [`insert_look`] with the new object's bounding box turned to `bbox_angle`. A new path or -/// compound path is pixel-aligned while the document's Align New Objects to Pixel Grid is on. +/// [`insert_look`] with the new object's bounding box turned to `bbox_angle`. With `align`, a new +/// path or compound path is pixel-aligned while the document's Align New Objects to Pixel Grid is +/// on. +#[allow(clippy::too_many_arguments)] fn insert_look_turned( s: &mut Session, label: &str, @@ -172,6 +190,7 @@ fn insert_look_turned( name: Option, select: bool, bbox_angle: f64, + align: bool, ) -> Result { let parent = s.doc()?.target_parent()?; let mode = s.draw_mode; @@ -181,7 +200,9 @@ fn insert_look_turned( let id = d.alloc_id(); let mut n = Node::new(id, kind); look.apply(d, &mut n); - super::object::align_new_object(d, &mut n); + if align { + super::object::align_new_object(d, &mut n); + } n.name = name; n.bbox_angle = bbox_angle; let mut into = None; @@ -299,7 +320,8 @@ fn path_kind(path: PathData, live: Option) -> NodeKind { /// (): /// a box (rectangle, ellipse, grid) runs along the turned axes from `pivot`, the point the dialog /// placed at the click (its top-left corner `x`, `y`, or a grid's reference point), which stays -/// put; a polygon or star turns its base orientation about its centre. The params as they are at +/// put; an arc sized by its lengths turns about its reference point `x`, `y`, which the dialog +/// placed at the click; a polygon or star turns its base orientation about its centre. The params as they are at /// 0° or a whole turn, for other commands and when they already carry a `rotation`. pub fn constrain_click(s: &Session, cmd: &str, mut params: Value, pivot: Point) -> Value { let base = s.prefs.constrain_angle; @@ -318,6 +340,9 @@ pub fn constrain_click(s: &Session, cmd: &str, mut params: Value, pivot: Point) "shape.polygon" | "shape.star" => { o.insert("rotation".into(), json!(rotation)); } + "shape.arc" if o.contains_key("lengthX") || o.contains_key("lengthY") => { + o.insert("rotation".into(), json!(rotation)); + } _ => {} } params @@ -362,10 +387,93 @@ 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 +/// points ([`selected_anchor_points`]). One undo step, named as an Ellipse tool drag is. +fn circle_through_points(s: &mut Session, p: &Value) -> Result { + const C: &str = "shape.circleThroughPoints"; + let points = match p.get("points").filter(|v| !v.is_null()) { + Some(v) => three_points(v).ok_or_else(|| bad(C, "`points` must be three [x, y] pairs of numbers"))?, + None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select three anchor points, or give `points`"))?, + }; + let [a, b, c] = points; + let (center, radius) = shapes::circle_through(a, b, c) + .ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?; + let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius); + let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; + // Not pixel-aligned: the circle stays through the points. + let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?; + out["cx"] = json!(center.x); + out["cy"] = json!(center.y); + out["radius"] = json!(radius); + Ok(out) +} + +/// The three points `[[x, y], [x, y], [x, y]]` holds, each pair two finite numbers. +fn three_points(v: &Value) -> Option<[Point; 3]> { + let pair = |v: &Value| match v.as_array().map(Vec::as_slice) { + Some([x, y]) => x.as_f64().zip(y.as_f64()).filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)), + _ => None, + }; + match v.as_array().map(Vec::as_slice) { + Some([a, b, c]) => Some([pair(a)?, pair(b)?, pair(c)?]), + _ => None, + } +} + +/// The positions of the selected anchor points, when there are exactly three. They are counted as +/// the other anchor commands count them ([`super::path::anchor_targets`]): a selected path with +/// anchors picked by Direct Selection gives those, and a path selected whole gives all of its own. +/// A selected segment's ends are not selected anchor points, so a selection with segments gives +/// none; so does a selection holding an object that is not a path, or an anchor that is gone. +fn selected_anchor_points(s: &Session) -> Result> { + let st = s.doc()?; + if st.selection.segments.values().any(|set| !set.is_empty()) { + return Ok(None); + } + let mut points = Vec::with_capacity(4); + for id in &st.selection.objects { + let Some(pd) = st.doc.node(*id).and_then(|n| n.path_data()) else { return Ok(None) }; + match st.selection.anchors.get(id) { + Some(set) => { + for &(si, ai) in set.iter().take(4) { + let Some(a) = pd.subpaths.get(si).and_then(|sp| sp.anchors.get(ai)) else { return Ok(None) }; + points.push(a.p); + } + } + None => points.extend(pd.anchors().take(4).map(|(_, _, a)| a.p)), + } + if points.len() > 3 { + return Ok(None); + } + } + Ok(match points.as_slice() { + &[a, b, c] => Some([a, b, c]), + _ => None, + }) } /// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or @@ -429,6 +537,7 @@ fn flare(s: &mut Session, p: &Value) -> Result { "direction", "pathLength", "seed", + "ringSeed", ]; check_numbers(p, &numbers, "shape.flare")?; let pct = |k: &str, d: f64| (f64_or(p, k, d) / 100.0).clamp(0.0, 10.0); @@ -450,14 +559,28 @@ fn flare(s: &mut Session, p: &Value) -> Result { c + vectorcraft_geom::Vec2::new(a.cos(), -a.sin()) * f64_or(p, "pathLength", 300.0) } }; - // Deterministic pseudo-random sizes (same parameters → same flare). - let mut seed = p.get("seed").and_then(Value::as_u64).unwrap_or(0x2545_f491_4f6c_dd1d) | 1; - let mut rnd = move || { - seed ^= seed << 13; - seed ^= seed >> 7; - seed ^= seed << 17; - (seed >> 11) as f64 / (1u64 << 53) as f64 + // Deterministic pseudo-random sizes (same parameters → same flare). `ringSeed` places the rings + // along the path from a sequence of its own; their count and sizes and the other parts stay. + let seed_of = |key: &str| match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => v.as_u64().map(Some).ok_or_else(|| bad("shape.flare", format!("`{key}` must be a whole number of at least 0, not {v}"))), }; + // The generator's state is odd (never 0). + let random = |mut state: u64| { + move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + (state >> 11) as f64 / (1u64 << 53) as f64 + } + }; + let mut rnd = random(seed_of("seed")?.unwrap_or(0x2545_f491_4f6c_dd1d) | 1); + // Each `ringSeed` below 2^53 (what a JSON number holds exactly) gets a state of its own. + let ring_seed = match seed_of("ringSeed")? { + Some(r) if r >= 1 << 53 => return Err(bad("shape.flare", format!("`ringSeed` must be below 2^53, not {r}"))), + r => r, + }; + let mut ring_at = ring_seed.map(|r| random((r << 1) | 1)); let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, vectorcraft_color::Color::WHITE) }; let radial = |centre: Point, radius: f64, stops: Vec| { let mut g = GradientPaint::new(Gradient::new(GradientKind::Radial, stops)); @@ -495,6 +618,7 @@ fn flare(s: &mut Session, p: &Value) -> Result { // Rings along the path to the end point (Largest = % of the average ring size). for _ in 0..rings { let t = rnd(); + let t = ring_at.as_mut().map_or(t, |next| next()); let at = c + (end - c) * t; let rr = (r * largest * (0.25 + rnd() * 0.75)).max(0.5); let solid = rnd() < 0.5; @@ -556,26 +680,56 @@ fn spiral(s: &mut Session, p: &Value) -> Result { } fn arc(s: &mut Session, p: &Value) -> Result { + let rotation = if p.get("rotation").is_some() { f64_req(p, "rotation", "shape.arc")? } else { 0.0 }; + if !rotation.is_finite() { + return Err(bad("shape.arc", "rotation must be finite")); + } let closed = switch_or(p, "closed", false, "shape.arc")?; let fill_arc = switch_or(p, "fillArc", false, "shape.arc")?; - let base_x = !matches!(p.get("baseAlong").and_then(Value::as_str), Some("y" | "Y")); - let path = if p.get("lengthX").is_some() || p.get("lengthY").is_some() { + // Given values are checked in both forms, null included; only a left-out key takes its default. + let base_x = match p.get("baseAlong") { + None => true, + Some(Value::String(v)) if v.eq_ignore_ascii_case("x") || v.eq_ignore_ascii_case("y") => v.eq_ignore_ascii_case("x"), + Some(_) => return Err(bad("shape.arc", "`baseAlong` must be one of x, y")), + }; + let reference = match p.get("reference") { + None => 0, + Some(v) => match (v.as_u64(), v.as_f64()) { + (Some(n), _) if n <= 8 => n as usize, + (None, Some(x)) if (0.0..=8.0).contains(&x) && x.fract() == 0.0 => x as usize, + _ => return Err(bad("shape.arc", "`reference` must be a whole number from 0 to 8")), + }, + }; + let slope = |default: f64| { + let (key, lo, hi) = ("slope", -100.0, 100.0); + let v = number_or(p, key, default, "shape.arc")?; + if (lo..=hi).contains(&v) { Ok(v) } else { Err(bad("shape.arc", format!("`{key}` must be from {lo} to {hi}, not {v}"))) } + }; + // The upright path, and the point `rotation` turns it about. + let (path, pivot) = if p.get("lengthX").is_some() || p.get("lengthY").is_some() { let anchor = Point::new(f64_req(p, "x", "shape.arc")?, f64_req(p, "y", "shape.arc")?); - let reference = p.get("reference").and_then(Value::as_u64).unwrap_or(0) as usize; - shapes::arc_segment( + let path = shapes::arc_segment( anchor, reference, number_or(p, "lengthX", 100.0, "shape.arc")?, number_or(p, "lengthY", 100.0, "shape.arc")?, base_x, - number_or(p, "slope", 50.0, "shape.arc")?, + slope(50.0)?, closed, - ) + ); + (path, anchor) } else { let a = Point::new(f64_req(p, "x1", "shape.arc")?, f64_req(p, "y1", "shape.arc")?); let b = Point::new(f64_req(p, "x2", "shape.arc")?, f64_req(p, "y2", "shape.arc")?); - let slope = number_or(p, "slope", 100.0, "shape.arc")?; - shapes::arc(a, b, slope, closed, base_x) + (shapes::arc(a, b, slope(100.0)?, closed, base_x), a) + }; + // 0 and whole turns leave the path as it is; quarter turns are exact. + let bbox_angle = bbox_turn(rotation); + let path = if bbox_angle == 0.0 { + path + } else { + let c = pivot.to_vec2(); + path.transformed(Affine::translate(c) * vectorcraft_geom::rotate_deg(rotation) * Affine::translate(-c)) }; let fill = if fill_arc { s.paint.fill.clone() } else { vectorcraft_color::Paint::None }; let look = s.new_art_look( @@ -583,7 +737,7 @@ fn arc(s: &mut Session, p: &Value) -> Result { if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() }, s.paint.stroke_width.max(0.1), ); - add_look(s, "Arc", path_kind(path, None), look, None) + insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, bbox_angle, true) } /// The grid `paths` (bottom first) as one selected group in the new-art stroke, filled with the @@ -621,13 +775,11 @@ fn grid_group(s: &mut Session, label: &str, (paths, bbox_angle): (Vec, Ok(json!({ "id": id.0 })) } -/// A grid's divider count `count` (an error unless it is a number or null; 5 unless it is a JSON -/// whole number of 0 or more, so 4.0 gives 4 and 2.5 gives 5; at most 999) with its skew `key` in percent (0 when -/// absent, clamped to ±[`shapes::GRID_SKEW_MAX`]). +/// A grid's divider count `count` (5 when absent or null; a whole number of 0 or more, so 4.0 gives +/// 4, and anything else, such as 2.5, -1 or `"3"`, is an error; at most 999) with its skew `key` in +/// percent (0 when absent, clamped to ±[`shapes::GRID_SKEW_MAX`]). fn dividers(p: &Value, count: &str, key: &str, cmd: &str) -> Result<(u32, f64)> { - check_numbers(p, &[count], cmd)?; - let whole = |v: &Value| v.as_u64().or_else(|| v.as_f64().filter(|f| f.is_finite() && *f >= 0.0 && f.fract() == 0.0).map(|f| f as u64)); - let n = p.get(count).and_then(whole).unwrap_or(5).min(999) as u32; + let n = count_or(p, count, 5, cmd)?.min(999) as u32; let skew = match p.get(key) { None | Some(Value::Null) => 0.0, Some(v) => v.as_f64().filter(|v| v.is_finite()).ok_or_else(|| bad(cmd, format!("`{key}` must be a number")))?, @@ -765,7 +917,8 @@ fn text_create(s: &mut Session, p: &Value) -> Result { // Lays the text out (and sizes an Auto Size frame). super::typecmd::refresh_bounds(&mut t); } - let made = insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation))?; + let made = + insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation), true)?; let id = made.get("id").and_then(Value::as_u64).map(NodeId); let made = super::typecmd::with_bounds(s, id, made); let mut made = super::typecmd::with_overflow(s, id.as_slice(), made); @@ -847,7 +1000,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(); @@ -865,8 +1019,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/cut.rs b/crates/engine/src/cmd/cut.rs index 48f2c31e62..43f3aec881 100644 --- a/crates/engine/src/cmd/cut.rs +++ b/crates/engine/src/cmd/cut.rs @@ -356,7 +356,8 @@ fn mirror_open(sp: &SubPath, axis: &Axis, m: Affine) -> Vec { if !end_on { run.reverse(); } - let Some((last, body)) = run.anchors.split_last() else { return vec![] }; + let run = run.anchors.into_vec(); + let Some((last, body)) = run.split_last() else { return vec![] }; let q = axis.project(last.p); let mut anchors = body.to_vec(); anchors.push(Anchor::with_handles(q, last.h_in, m * last.h_in)); diff --git a/crates/engine/src/cmd/dimension.rs b/crates/engine/src/cmd/dimension.rs index 44ac08d7ad..183cbd3746 100644 --- a/crates/engine/src/cmd/dimension.rs +++ b/crates/engine/src/cmd/dimension.rs @@ -495,7 +495,8 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result { /// Redraw the dimensions of an opened document whose art isn't in its colour mode: files saved /// before dimensions followed the colour mode have RGB dimensions in CMYK documents. A dimension -/// that can't be redrawn keeps the art it has. +/// that can't be redrawn keeps the art it has. The labels are measured in the document's own +/// composite fonts, also when another document's definitions of the same names are registered. pub(crate) fn conform(doc: &mut Document) { if !doc.dimensions { return; @@ -521,6 +522,10 @@ pub(crate) fn conform(doc: &mut Document) { } } }); + if stale.is_empty() { + return; + } + let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts); for (id, d) in stale { // An error leaves this dimension as it was; the others are still redrawn. let _ = replace(doc, id, d); diff --git a/crates/engine/src/cmd/distortcmds.rs b/crates/engine/src/cmd/distortcmds.rs index 2dbb7a9a18..1e78f210e6 100644 --- a/crates/engine/src/cmd/distortcmds.rs +++ b/crates/engine/src/cmd/distortcmds.rs @@ -26,7 +26,7 @@ pub use perspective::perspective_click; use perspective::{ attach, edit_text, grid_set, grid_show, persp_draw, persp_move, persp_nudge, persp_transform, plane_match, plane_move, plane_set, release, }; -pub(crate) use perspective::{finish_edit_text, grid_of, perspective_rewrite, silent, store_grid, transform_again}; +pub(crate) use perspective::{finish_edit_text, grid_kept, grid_of, perspective_rewrite, silent, store_grid, transform_again}; pub fn specs() -> Vec { vec![ @@ -107,7 +107,7 @@ pub fn specs() -> Vec { "Perspective Grid Preset", [], None, - "{kind: 1|2|3 (its normal view) | name: a preset (see perspective.presets.list)} reset the grid to the preset fitted to the first artboard (and show it; attached objects stay attached)", + "{kind: 1|2|3 (its normal view) | name: a preset (see perspective.presets.list)} reset the grid to the preset fitted to the first artboard (and show it; attached objects stay attached). No undo step when the document already holds that grid; when only whether it shows or its active plane differs, those are set without one", has_doc, super::perspgrid::grid_preset ), @@ -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/distortcmds/perspective.rs b/crates/engine/src/cmd/distortcmds/perspective.rs index 62b72a8e0f..90d58541a6 100644 --- a/crates/engine/src/cmd/distortcmds/perspective.rs +++ b/crates/engine/src/cmd/distortcmds/perspective.rs @@ -18,7 +18,7 @@ pub(crate) fn store_grid(d: &mut Document, g: &PerspectiveGrid) { /// Whether `d` holds `g` as [`store_grid`] writes it (with `attached` cleared): then storing `g` /// leaves `d` as it is. -fn grid_kept(d: &Document, g: &PerspectiveGrid) -> bool { +pub(crate) fn grid_kept(d: &Document, g: &PerspectiveGrid) -> bool { let mut g = g.clone(); g.attached.clear(); serde_json::to_value(&g).is_ok_and(|v| d.unknown.get(persp::DOC_KEY) == Some(&v)) @@ -70,13 +70,26 @@ pub(super) fn grid_show(s: &mut Session, p: &Value) -> Result { None | Some(Value::Null) => None, Some(_) => Some(switch_or(p, "visible", false, C)?), }; - let g = silent(s, |g| g.visible = want.unwrap_or(!g.visible))?; + // A hidden grid holds no plane for Automatic Plane Positioning. + let g = silent(s, |g| { + g.visible = want.unwrap_or(!g.visible); + if !g.visible { + g.inferred = None; + } + })?; Ok(json!({ "visible": g.visible })) } pub(super) fn plane_set(s: &mut Session, p: &Value) -> Result { let plane = str_param(p, "plane").and_then(Plane::parse).ok_or_else(|| bad("perspective.plane.set", "plane must be left|right|ground|none"))?; - silent(s, |g| g.plane = plane)?; + // The new active plane passes through the point Automatic Plane Positioning holds, unless no + // plane is active or that would put the plane behind the viewer. + silent(s, |g| { + g.plane = plane; + if g.inferred.is_some() && (plane == Plane::None || g.validate().is_err()) { + g.inferred = None; + } + })?; Ok(json!({ "plane": plane.id() })) } @@ -91,9 +104,14 @@ fn plane_param(g: &PerspectiveGrid, p: &Value, cmd: &str) -> Result { Ok(plane) } +/// The objects a perspective command acts on: the outermost of `ids` (each once, in the order first +/// given), else the selection's roots. pub(super) fn roots(s: &Session, p: &Value) -> Result> { match named_ids(p)? { - Some(v) => Ok(outermost(&s.doc()?.doc, v)), + Some(v) => { + let mut seen = std::collections::HashSet::new(); + Ok(outermost(&s.doc()?.doc, v.into_iter().filter(|id| seen.insert(*id)).collect())) + } None => selected_roots(s), } } @@ -138,6 +156,9 @@ pub(super) fn attach(s: &mut Session, p: &Value) -> Result { store_grid(d, &g); Ok(()) })?; + if !ids.is_empty() { + crate::cmd::perspgrid::plane_positioning_used(s, plane)?; + } Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "plane": plane.id() })) } @@ -205,8 +226,13 @@ fn persp_edit( return Err(EngineError::Other("select the objects to transform in perspective".into())); } let mut g = grid_of(&s.doc()?.doc); + // An object not in perspective yet attaches to `fallback` where that plane is now. + let attaches = { + let d = &s.doc()?.doc; + fallback.filter(|_| ids.iter().any(|id| g.attachment_of(d, *id).is_none())) + }; let kept = if copy && !stores_attachments(&s.doc()?.doc) { crate::cmd::object::preview_copies(s, ids, false)? } else { None }; - s.edit(label, |d, sel| { + let edited = s.edit(label, |d, sel| { g.adopt_stored_attachments(d); let targets = match &kept { // The document becomes the snapshot with the kept copies, not yet mapped, and the loop @@ -236,7 +262,11 @@ fn persp_edit( } store_grid(d, &g); Ok((targets, first)) - }) + })?; + if let Some(plane) = attaches { + crate::cmd::perspgrid::plane_positioning_used(s, plane)?; + } + Ok(edited) } /// Where the first of `ids` is in perspective (its plane and depth) when `ids` is not empty, every one @@ -430,6 +460,9 @@ pub(super) fn plane_move(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["offset", "by"], C)?; let old = grid_of(&s.doc()?.doc); let plane = plane_param(&old, p, C)?; + // A plane that Automatic Plane Positioning holds moves from where it is held, and the move + // places it there for good: the moved grid holds no plane (undoing the move holds it again). + let held = old.inferred; let from = old.offset(plane); let to = match (p.get("offset").and_then(Value::as_f64), p.get("by").and_then(Value::as_f64)) { (Some(o), _) => o, @@ -440,7 +473,7 @@ pub(super) fn plane_move(s: &mut Session, p: &Value) -> Result { if !matches!(objects, "none" | "move" | "copy") { return Err(bad(C, "objects must be none, move or copy")); } - let mut g = old.clone(); + let mut g = PerspectiveGrid { inferred: None, ..old.clone() }; g.set_offset(plane, to); g.validate().map_err(|e| bad(C, e))?; let label = match objects { @@ -458,8 +491,9 @@ pub(super) fn plane_move(s: &mut Session, p: &Value) -> Result { .collect() }; // A plane moved to where it is, with its objects or without them, moves nothing: when the - // document holds the grid already, the document and its undo history stay as they are. - if to == from && objects != "copy" && grid_kept(&s.doc()?.doc, &g) { + // document holds the grid already, the document and its undo history stay as they are (a + // plane held where it was placed stays held). + if to == from && objects != "copy" && grid_kept(&s.doc()?.doc, &PerspectiveGrid { inferred: held, ..g.clone() }) { let ids = if objects == "move" { on_plane(&s.doc()?.doc) } else { vec![] }; return Ok(json!({ "plane": plane.id(), "offset": to, "ids": ids.iter().map(|i| i.0).collect::>() })); } @@ -507,12 +541,19 @@ pub(super) fn plane_match(s: &mut Session, p: &Value) -> Result { named_id(p)?.or_else(|| st.selection.objects.first().copied()).ok_or_else(|| EngineError::Other("select an object in perspective".into()))?; let mut g = grid_of(&st.doc); let (plane, depth) = g.attachment_of(&st.doc, id).ok_or_else(|| EngineError::Other("the object isn't in perspective".into()))?; + // The moved grid holds no plane for Automatic Plane Positioning (undoing the move holds it + // again). + let held = g.inferred.take(); g.set_offset(plane, depth); g.plane = plane; g.validate().map_err(|e| bad("perspective.plane.matchObject", e))?; // When the plane is at the object and active already, and the document holds that grid, the - // document and its undo history stay as they are. - if grid_kept(&st.doc, &g) { + // document and its undo history stay as they are; a plane held elsewhere goes back to that + // place as view state. + if grid_kept(&st.doc, &PerspectiveGrid { inferred: held, ..g.clone() }) { + if held.is_some() { + silent(s, |g| g.inferred = None)?; + } return Ok(json!({ "plane": plane.id(), "offset": depth })); } s.edit("Move Plane to Match Object", |d, _| { @@ -573,6 +614,7 @@ pub(super) fn persp_draw(s: &mut Session, p: &Value) -> Result { st.history.recost_last(&st.doc); } res?; + crate::cmd::perspgrid::plane_positioning_used(s, plane)?; Ok(json!({ "id": id.0, "plane": plane.id() })) } diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index 4068c2506c..c7421ac391 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -344,44 +344,9 @@ fn spot_swatches(d: &Document) -> HashSet<&str> { first.into_iter().filter(|&(name, spot)| spot && name != vectorcraft_color::swatch::REGISTRATION).map(|(name, _)| name).collect() } -/// Which of gradient `g`'s stops color some part of it that draws, by the stretches -/// [`vectorcraft_color::Gradient::sample`] mixes in, for stops in any order: the pair of stop `k` -/// and stop `k + 1` covers the offsets above every offset of stops `0..=k` up to stop `k + 1`'s, -/// and both its stops count when that stretch has positive width and either stop is above opacity -/// 0. The first stop also counts when it is above opacity 0, since it colors the offsets up to its -/// own, and so does the last stop, since it colors the offsets above every stop's. Any other stop, -/// opaque or not, counts only through a pair: a stop out of order whose pairs have no width -/// (another stop before it reaches past both ends) colors nothing. A freeform gradient draws from -/// its points, so each of its stops counts while any stop is above opacity 0. -fn drawn_stops(g: &vectorcraft_color::Gradient) -> Vec { - let stops = &g.stops; - if g.kind == vectorcraft_color::GradientKind::Freeform { - let any = stops.iter().any(|s| s.opacity > 0.0); - return vec![any; stops.len()]; - } - let mut drawn = vec![false; stops.len()]; - if let (Some(first), Some(d)) = (stops.first(), drawn.first_mut()) { - *d = first.opacity > 0.0; - } - if let (Some(last), Some(d)) = (stops.last(), drawn.last_mut()) { - *d |= last.opacity > 0.0; - } - // `f32::max` skips a NaN offset, which the sampler never picks either. - let mut reach = f32::NEG_INFINITY; - for k in 0..stops.len().saturating_sub(1) { - reach = reach.max(stops[k].offset); - let (a, b) = (&stops[k], &stops[k + 1]); - if b.offset > reach && (a.opacity > 0.0 || b.opacity > 0.0) { - drawn[k] = true; - drawn[k + 1] = true; - } - } - drawn -} - /// The spot colors paint `p` prints (`spots`: [`spot_swatches`]): the spot swatch a solid color is -/// linked to, or those a gradient's drawn stops ([`drawn_stops`]) are linked to, each once, in the -/// order of the stops. A link at a tint of 0 prints no ink, a stop that colors only parts of a +/// linked to, or those a gradient's drawn stops ([`vectorcraft_color::Gradient::drawn_stops`]) are +/// linked to, each once, in the order of the stops. A link at a tint of 0 prints no ink, a stop that colors only parts of a /// gradient at an opacity of 0 prints none, and a color that only looks like a spot color is not /// linked to one. fn spot_labels(spots: &HashSet<&str>, p: &Paint) -> Vec { @@ -398,7 +363,7 @@ fn spot_labels(spots: &HashSet<&str>, p: &Paint) -> Vec { match p { Paint::Solid { swatch, tint, .. } => add(swatch, *tint), Paint::Gradient(g) => { - let drawn = drawn_stops(&g.gradient); + let drawn = g.gradient.drawn_stops(); g.gradient.stops.iter().zip(drawn).filter(|&(_, d)| d).for_each(|(s, _)| add(&s.swatch, s.tint)); } _ => {} @@ -892,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)) @@ -1535,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)); @@ -1662,39 +1657,6 @@ mod tests { assert!(!["Far", "Edge", "Seam"].iter().any(|n| text.contains(n)), "{text}"); } - /// A gradient's stops print where they color a stretch that draws, for stops in any order: the - /// sampler mixes stop `k` with stop `k + 1` above every offset of the stops before it, so an - /// out-of-order stop's pair can have no width. - #[test] - fn drawn_stops_follow_the_sampled_stretches() { - use vectorcraft_color::{Color, Gradient, GradientKind, GradientStop}; - let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, Color::BLACK) }; - let g = |stops: Vec| Gradient::new(GradientKind::Linear, stops); - // In order: the clear stop next to the opaque one, not the one after it. - assert_eq!(drawn_stops(&g(vec![stop(0.0, 1.0), stop(0.5, 0.0), stop(1.0, 0.0)])), vec![true, true, false]); - // Out of order: the pair (0.8, 0.3) has no width, so the clear stop at 0.3 mixes only with - // the clear stop at 0.8 before it, and the pair (0.3, 1.0) is sampled above 0.8. - assert_eq!(drawn_stops(&g(vec![stop(0.0, 0.0), stop(0.8, 0.0), stop(0.3, 0.0), stop(1.0, 1.0)])), vec![false, false, true, true]); - // An opaque stop out of order: the pairs (0, 0.8) and (0.7, 1) cover every offset, so the - // pairs next to the stop at 0.3 have no width and it colors nothing. - let out_of_order = |o: f32| g(vec![stop(0.0, 0.0), stop(0.8, o), stop(0.3, 1.0), stop(0.7, 0.0), stop(1.0, 0.0)]); - assert_eq!(drawn_stops(&out_of_order(0.0)), vec![false; 5]); - // With the stop at 0.8 opaque, the pairs next to it with width are drawn. - assert_eq!(drawn_stops(&out_of_order(1.0)), vec![true, true, false, false, false]); - // The last stop colors the offsets above every stop's, even when it is out of order. - assert_eq!(drawn_stops(&g(vec![stop(0.0, 0.0), stop(0.6, 0.0), stop(0.5, 1.0)])), vec![false, false, true]); - // The first stop colors the offsets up to its own. - assert_eq!(drawn_stops(&g(vec![stop(0.0, 1.0), stop(0.0, 0.0), stop(1.0, 0.0)])), vec![true, false, false]); - // One stop, every stop clear, and no stops at all. - assert_eq!(drawn_stops(&g(vec![stop(0.5, 1.0)])), vec![true]); - assert_eq!(drawn_stops(&g(vec![stop(0.0, 0.0), stop(1.0, 0.0)])), vec![false, false]); - assert!(drawn_stops(&g(vec![])).is_empty()); - // A freeform gradient draws from its points: its stops count while any is above opacity 0. - let mut free = g(vec![stop(0.0, 1.0), stop(0.5, 0.0), stop(1.0, 0.0)]); - free.kind = GradientKind::Freeform; - assert_eq!(drawn_stops(&free), vec![true, true, true]); - } - /// Brushes, Spot Color Objects, Pattern Objects and Gradient Objects leave out a hidden object, /// an object at an opacity of 0 and the objects inside a hidden layer or a group at an opacity of /// 0, with Selection Only too: their fills, strokes, characters and colorized pixels paint no @@ -1725,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 ae48ba02e6..709b4cda65 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -6,10 +6,11 @@ use std::collections::{BTreeSet, HashMap, HashSet}; use std::sync::Arc; use serde_json::{Value, json}; -use vectorcraft_doc::{CharStyle, Guide, Node, NodeId, NodeKind, SavedSelection, TextKind}; +use vectorcraft_doc::{CharStyle, Guide, Node, NodeId, NodeKind, SavedSelection, Selection, TextKind}; use vectorcraft_geom::Vec2; use super::edit::selected_roots; +use super::panelcmds::artboard_at; use super::pathops::Beside; use super::select::{first_selectable, is_selectable, selectable_ids, walk_selectable}; use super::{ @@ -201,7 +202,7 @@ pub fn specs() -> Vec { "Add Guide", [], None, - "{vertical: bool, pos: pt (x for vertical, y for horizontal), artboard?: index (an artboard guide: it runs across that artboard only and moves, is copied and is deleted with it; default a canvas guide, across the whole canvas), layer?: id (the layer it is on, shown, hidden, locked and deleted with it; default the current layer)} → {index}", + "{vertical: bool, pos: pt (x for vertical, y for horizontal), artboard?: index (0-based whole number; an artboard guide: it runs across that artboard only and moves, is copied and is deleted with it; default, or null, a canvas guide, across the whole canvas), layer?: id (the layer it is on, shown, hidden, locked and deleted with it; default the current layer)} → {index}", has_doc, guide_add ), @@ -269,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 + ), ] } @@ -467,16 +495,17 @@ fn direction_handles(s: &mut Session, _: &Value) -> Result { } } let total: usize = items.iter().map(|x| x.1.len()).sum(); - s.select(|_, sel| { - sel.clear(); - for (id, refs) in items { - sel.add(id); - sel.anchors.insert(id, refs); - } - })?; + s.select(|_, sel| select_anchors(sel, items))?; Ok(json!({ "anchors": total })) } +/// Replaces `sel` with the paths of `items` in order, each once, and direct-selects the anchors +/// listed with each path. A path listed twice keeps its first place and its last anchor set. +fn select_anchors(sel: &mut Selection, items: Vec<(NodeId, BTreeSet<(usize, usize)>)>) { + sel.set(items.iter().map(|(id, _)| *id)); + sel.anchors.extend(items); +} + fn save_selection(s: &mut Session, p: &Value) -> Result { const C: &str = "select.save"; let st = s.doc()?; @@ -767,15 +796,8 @@ fn clear_guides(s: &mut Session, _: &Value) -> Result { fn guide_add(s: &mut Session, p: &Value) -> Result { let pos = f64_req(p, "pos", "guide.add")?; let vertical = switch_or(p, "vertical", false, "guide.add")?; - let artboard = match p.get("artboard").filter(|v| !v.is_null()) { - Some(v) => { - let boards = &s.doc()?.doc.artboards; - let ab = v.as_u64().and_then(|i| boards.get(usize::try_from(i).ok()?)).ok_or_else(|| EngineError::Other("no such artboard".into()))?; - Some(ab.id) - } - None => None, - }; let st = s.doc()?; + let artboard = artboard_at(&st.doc, p, "artboard", "guide.add")?.and_then(|i| st.doc.artboards.get(i)).map(|a| a.id); let layer = match id_param(p, "layer") { Some(l) if st.doc.node(l).is_some_and(Node::is_layer) => Some(l), Some(_) => return Err(bad("guide.add", "layer must name a layer or sublayer")), @@ -1005,3 +1027,6 @@ fn close_all(s: &mut Session, _: &Value) -> Result { } Ok(json!({ "closed": n })) } + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/docmenu/tests.rs b/crates/engine/src/cmd/docmenu/tests.rs new file mode 100644 index 0000000000..d9cc140fb0 --- /dev/null +++ b/crates/engine/src/cmd/docmenu/tests.rs @@ -0,0 +1,68 @@ +//! The selection that Select ▸ Object ▸ Direction Handles builds. + +use std::collections::{BTreeSet, HashSet}; +use std::sync::Arc; + +use vectorcraft_doc::{NodeId, Selection, SymbolPart}; + +use super::select_anchors; + +type Items = Vec<(NodeId, BTreeSet<(usize, usize)>)>; + +/// Selects `items` one path at a time: a clear, then an add and an anchor insert per path. +fn one_by_one(sel: &mut Selection, items: Items) { + sel.clear(); + for (id, refs) in items { + sel.add(id); + sel.anchors.insert(id, refs); + } +} + +/// A selection with every field set, as one left by earlier selecting. +fn busy() -> Selection { + let mut sel = Selection::default(); + sel.set([NodeId(90), NodeId(91)]); + sel.anchors.insert(NodeId(90), BTreeSet::from([(0, 0)])); + sel.segments.insert(NodeId(91), BTreeSet::from([(0, 1)])); + sel.key = Some(NodeId(91)); + sel.target = Some(NodeId(92)); + sel.slices = vec![NodeId(93)]; + sel.guides = vec![NodeId(94)]; + sel.key_guide = Some(NodeId(94)); + sel.key_anchor = Some((NodeId(90), (0, 0))); + sel.symbol_part = Some(SymbolPart { instance: NodeId(95), path: vec![0, 1] }); + sel.on_path_member = Some(NodeId(96)); + sel.new_art = Arc::new(HashSet::from([NodeId(97)])); + sel +} + +fn refs(n: usize) -> BTreeSet<(usize, usize)> { + (0..n).map(|i| (0, i)).collect() +} + +#[test] +fn select_anchors_gives_the_selection_one_by_one_selecting_gives() { + let cases: Vec = vec![ + vec![], + vec![(NodeId(1), refs(4))], + (1..=500).map(|i| (NodeId(i), refs(4))).collect(), + // A path listed again keeps its first place and its last anchors. + vec![(NodeId(3), refs(1)), (NodeId(1), refs(4)), (NodeId(3), refs(2)), (NodeId(2), BTreeSet::new()), (NodeId(1), refs(3))], + ]; + for items in cases { + for start in [Selection::default(), busy()] { + let (mut want, mut got) = (start.clone(), start); + one_by_one(&mut want, items.clone()); + select_anchors(&mut got, items.clone()); + assert_eq!(got, want, "{items:?}"); + } + } + let mut got = busy(); + select_anchors(&mut got, vec![(NodeId(3), refs(1)), (NodeId(1), refs(4)), (NodeId(3), refs(2))]); + assert_eq!(got.objects, vec![NodeId(3), NodeId(1)]); + assert_eq!(got.anchors[&NodeId(3)], refs(2)); + assert!(got.segments.is_empty() && got.slices.is_empty() && got.guides.is_empty()); + assert_eq!((got.key, got.target, got.key_guide, got.key_anchor, got.on_path_member), (None, None, None, None, None)); + assert!(got.symbol_part.is_none()); + assert_eq!(*got.new_art, HashSet::from([NodeId(97)]), "selecting leaves the new-art list alone"); +} diff --git a/crates/engine/src/cmd/draw2.rs b/crates/engine/src/cmd/draw2.rs index d469c7a613..63ae0a3e4c 100644 --- a/crates/engine/src/cmd/draw2.rs +++ b/crates/engine/src/cmd/draw2.rs @@ -31,5 +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 53949fdaf0..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; 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]…] (pen pressure 0..1), size?: pt (10), sizeMode?: \"fixed\" (default) | \"pressure\" (Eraser Tool Options' Size set to Pressure: the tip is size − sizeVariation across where the pen presses lightest and size + sizeVariation where it presses hardest, as path.blob), sizeVariation?: pt (0), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100)} 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", + "{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 → {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 645c184b14..40a4c74d79 100644 --- a/crates/engine/src/cmd/draw2/cut.rs +++ b/crates/engine/src/cmd/draw2/cut.rs @@ -1,11 +1,15 @@ use super::common::{ - 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, ParamCurve, PathData, Point, Result, Session, SubPath, - Value, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po, + 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; /// Split a filled path into connected pieces (each outer contour with its holes). pub(in super::super) fn components(pd: &PathData) -> Vec { @@ -43,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![]); @@ -61,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) }; @@ -70,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); @@ -143,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); @@ -181,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()))?; @@ -207,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)?; @@ -223,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]) } @@ -271,19 +293,32 @@ 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)?; - let pressure = size_pressure(p, &samples, 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); + } + let pressure = if vary[2].0 == Variation::Pressure { size_pressure(p, &samples, C)? } else { None }; let pts: Vec = samples.into_iter().map(|s| s.pt).collect(); 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. @@ -318,6 +353,158 @@ 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, 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", 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()) { + None => Variation::Fixed, + Some(Value::String(id)) => Variation::parse(id).ok_or_else(|| bad(cmd, format!("{mode_key} is one of {ERASER_MODES}, not `{id}`")))?, + Some(other) => return Err(bad(cmd, format!("{mode_key} is one of {ERASER_MODES}, not {other}"))), + }; + let variation = number_or(p, var_key, 0.0, cmd)?; + if !(variation.is_finite() && variation >= 0.0) { + return Err(bad(cmd, format!("{var_key} must be 0 or more"))); + } + if variation > 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); + } + Ok(out) +} + +/// Does any of the Eraser's Angle, Roundness and Size vary with something other than Size on +/// Pressure? A mode whose variation is 0 does not vary. +fn varies_beyond_size_pressure(vary: &[(Variation, f64); 3]) -> bool { + vary.iter().enumerate().any(|(i, (mode, v))| *v > 0.0 && *mode != Variation::Fixed && !(i == 2 && *mode == Variation::Pressure)) +} + +/// `path.eraseRegion` with its tip varying along the drag ([`eraser_variations`]): the area the +/// tip covers is swept as a Calligraphic brush nib of the same angle, roundness, size, modes and +/// variations, with what the pen recorded along the drag. Random draws one value for the drag +/// and the pen modes follow the pen at each point; a drag without that recording (a mouse) takes +/// the value itself. `tip`: the angle, roundness and size. +fn erase_varied(s: &mut Session, samples: &[Sample], tip: [f64; 3], vary: [(Variation, f64); 3]) -> Result { + let [angle, roundness, size] = tip; + let mut pts: Vec = samples.iter().map(|s| s.pt).collect(); + // A press without a drag is a dab: a sweep needs some length. + if let [only] = pts[..] { + pts.push(only + Vec2::new(0.01, 0.0)); + } + // A nib's size is kept within 1296 pt and the stroke's width scales it: a larger tip is swept + // at a fraction of its size on a stroke as many times wider. + let [(am, av), (rm, rv), (sm, sv)] = vary; + let sv = if sm == Variation::Fixed { 0.0 } else { sv }; + let scale = ((size + sv) / Calligraphic::RANGES[2].1).max(1.0); + let nib = Calligraphic { + angle, + roundness: roundness.clamp(1.0, 100.0), + size: size / scale, + variation: [av, rv, sv / scale], + modes: Some([am, rm, sm]), + }; + let brush = Brush { name: "Eraser".into(), kind: BrushKind::Calligraphic(nib) }; + let mut stroke = StrokeLayer::new(Paint::None, scale); + PenRecord::of_samples(samples).write(&mut stroke); + let spine = SubPath::polyline(&pts, false); + let st = s.doc()?; + let pieces = vectorcraft_brush::stroke_pieces(&st.doc, &brush, &PathData::single(spine).to_bezpath(), &stroke); + let areas: Vec = pieces.iter().filter_map(|n| n.path_data().cloned()).collect(); + if areas.is_empty() { + return Ok(json!({ "ids": [] })); + } + let region = + po::try_unite_all(&areas.iter().map(|a| (a, FillRule::NonZero)).collect::>()).map_err(|e| EngineError::Other(e.to_string()))?; + let bp = region.to_bezpath(); + // The narrowest the tip gets across: an open path is sampled at least every half of it. + let low = |i: usize| match vary[i] { + (Variation::Fixed, _) => tip[i], + (_, v) => tip[i] - v, + }; + let short = low(2).max(MIN_BRUSH_SIZE) * low(1).clamp(1.0, 100.0) / 100.0; + let reach = (size + sv) / 2.0; + let mut plan: Vec<(NodeId, Vec)> = vec![]; + for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach))? { + 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(&pd, short / 2.0, &|q| fill_contains(&bp, FillRule::NonZero, q)) { + plan.push((id, pieces)); + } + } + apply_plan(s, "Eraser", plan) +} + fn apply_plan(s: &mut Session, label: &str, plan: Vec<(NodeId, Vec)>) -> Result { if plan.is_empty() { return Ok(json!({ "ids": [] })); diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 0439aaa081..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, @@ -46,7 +46,7 @@ fn fit_freehand(pts: &[Point], tol: f64, closed: bool) -> SubPath { let sp = vectorcraft_tools::draw2::catmull_rom(&marked, false); if sp.anchors.len() < 3 { // Two anchors closed would run back over the line itself. - return SubPath::new(sp.anchors, closed && n > 2); + return SubPath::of(sp.anchors, closed && n > 2); } let fitted = po::simplify_with( &PathData::single(sp.clone()), @@ -62,7 +62,7 @@ fn fit_freehand(pts: &[Point], tol: f64, closed: bool) -> SubPath { f.h_in = f.p; } } - SubPath::new(anchors, closed) + SubPath::of(anchors, closed) } /// The path of a freehand stroke: fitted at `tol` ([`fit_freehand`]), or with no `tol` the points @@ -133,13 +133,13 @@ fn redraw_section(pd: &PathData, pts: &[Point], tol: Option, within: f64) - *s0 = s1.p; let (Some(e0), Some(e1)) = (stroke.last_mut(), sp.anchors.get(end)) else { return None }; *e0 = e1.p; - let fit = stroke_subpath(&stroke, tol, false).anchors; + let fit = stroke_subpath(&stroke, tol, false).anchors.into_vec(); let (Some(f0), Some(f1)) = (fit.first().copied(), fit.last().copied()) else { return None }; let inner = fit.get(1..fit.len().saturating_sub(1)).unwrap_or_default(); let (before, after): (Vec, Vec) = if sp.closed { ((0..=(start + n - end) % n).filter_map(|k| sp.anchors.get((end + k) % n).copied()).collect(), vec![]) } else { - (sp.anchors.get(..=start)?.to_vec(), sp.anchors.get(end..)?.to_vec()) + (sp.anchors.get_range(..=start)?, sp.anchors.get_range(end..)?) }; let mut anchors = before; if let Some(a) = anchors.last_mut() { @@ -157,6 +157,34 @@ fn redraw_section(pd: &PathData, pts: &[Point], tol: Option, within: f64) - } pub(super) fn freehand(s: &mut Session, p: &Value) -> Result { + freehand_brushed(s, p, None) +} + +/// The object a brush on path `id` paints: the compound path a member path is in, else the path. +fn brush_target(d: &Document, id: NodeId) -> NodeId { + d.parent_of(id).filter(|p| d.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))).unwrap_or(id) +} + +/// Whether `ap` has a stroke a brush can paint: a stroke whose paint is not None. +fn can_brush(ap: &Appearance) -> bool { + ap.stroke().is_some_and(|st| !st.paint.is_none()) +} + +fn no_stroke(name: &str) -> EngineError { + bad("brush.freehand", format!("cannot apply brush `{name}`: path has no stroke")) +} + +/// Sets brush `name` on the stroke of object `id` of `d`. +fn set_brush(d: &mut Document, id: NodeId, name: &str) { + if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) { + st.brush = Some(name.to_string()); + } +} + +/// `path.freehand`, with the stroke painted with brush `brush_name` (one `brush.freehand` has +/// checked) in the same undo step as the path. A path without a stroke is an error before +/// anything changes. +pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&str>) -> Result { const C: &str = "path.freehand"; let samples = samples_param(p, "points", C)?; if samples.iter().any(|q| !within_input_bound(q.pt)) { @@ -173,6 +201,8 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result { let fit_tol = switch_or(p, "fit", true, C)?.then_some(tol); let closed = switch_or(p, "closed", false, C)?; let brush = str_param(p, "style") == Some("brush"); + // The undo step's name: a stroke painted with a brush is a Paintbrush stroke, whatever its style. + let label = if brush || brush_name.is_some() { "Paintbrush" } else { "Pencil" }; let keep_selected = switch_or(p, "keepSelected", true, C)?; let filled = switch_or(p, "fill", false, C)?; if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) { @@ -180,6 +210,12 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result { let at_start = str_param(ext, "end") == Some("start"); let (pd, _) = path_of(&s.doc()?.doc, id)?; let si = pd.subpaths.iter().rposition(|s| !s.closed && !s.anchors.is_empty()).ok_or_else(|| bad(C, "path has no open end"))?; + let target = brush_target(&s.doc()?.doc, id); + if let Some(name) = brush_name + && !s.doc()?.doc.node(target).is_some_and(|n| can_brush(&n.appearance)) + { + return Err(no_stroke(name)); + } let mut sp = pd.subpaths[si].clone(); let old_len = subpath_len(&sp); if at_start { @@ -191,6 +227,21 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result { 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, 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, sel| { + set_brush(d, target, name); + if keep_selected { + sel.set([id]); + } else { + sel.remove(id); + } + Ok(()) + })?; + } return Ok(json!({ "id": id.0 })); } // A stroke that ends on an open end of another path connects the two: (that path, its last @@ -217,11 +268,18 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result { } None => None, }; - // An extending stroke that ends within four Fidelities of the path's other end closes it: - // at least 6 pt and at most 400 pt, whatever the Fidelity it is fitted at. + // `closed`, when given, says whether the stroke closes the path: the Pencil and the + // Paintbrush send it, by their Close Paths When Ends Are Within and Alt at the release. + // Left out, an extending stroke that ends within four Fidelities of the path's other end + // closes it: at least 6 pt and at most 400 pt, whatever the Fidelity it is fitted at. let close_tol = (tol * 4.0).clamp(6.0, 400.0); - let closing = connect.is_none() && sp.anchors.len() >= 2 && pts.last().is_some_and(|p| p.distance(first) <= close_tol); - if closing && let Some(l) = pts.last_mut() { + let near_first = pts.last().is_some_and(|p| p.distance(first) <= close_tol); + let wants_close = if p.get("closed").is_some_and(|v| !v.is_null()) { closed } else { near_first }; + let closing = connect.is_none() && sp.anchors.len() >= 2 && wants_close; + // A stroke ending near the other end ends on it; one ending farther away closes with a + // straight segment back to it. + let ends_on_first = closing && near_first; + if ends_on_first && let Some(l) = pts.last_mut() { *l = first; } if let Some((_, _, y, _)) = &connect @@ -238,13 +296,23 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result { add.remove(0); } sp.anchors.extend(add); - if closing + if ends_on_first && sp.anchors.len() > 2 && let Some(l) = sp.anchors.pop() && let Some(a0) = sp.anchors.first_mut() { a0.h_in = l.h_in; sp.closed = true; + } else if closing && !ends_on_first && sp.anchors.len() > 2 { + // Closed from away from the other end: a straight segment back to it, whatever + // handles the open ends carried. + sp.closed = true; + if let Some(l) = sp.anchors.last_mut() { + l.h_out = l.p; + } + if let Some(f) = sp.anchors.first_mut() { + f.h_in = f.p; + } } for a in &mut sp.anchors { *a = Anchor::with_handles(a.p, a.h_in, a.h_out); @@ -254,12 +322,12 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result { // outgoing handle. let mut other_len = 0.0; if let Some((_, _, y, _)) = &connect - && let Some((y0, rest)) = y.anchors.split_first() + && let Some(y0) = y.anchors.first() { if let Some(last) = sp.anchors.last_mut() { *last = Anchor::with_handles(y0.p, last.h_in + (y0.p - last.p), y0.h_out); } - sp.anchors.extend_from_slice(rest); + sp.anchors.extend(y.anchors.iter().skip(1)); other_len = subpath_len(y); } // What the pen recorded along the path (in the direction it is continued in), followed by @@ -273,7 +341,7 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result { let drawn = old.extended(old_len, &pen, drawn_len - old_len); if connect.is_some() { drawn.extended(drawn_len, &other, other_len) } else { drawn } }); - s.edit(if brush { "Paintbrush" } else { "Pencil" }, |d, sel| { + s.edit(label, |d, sel| { let reverse = at_start && !sp.closed; if reverse { sp.reverse(); @@ -309,6 +377,9 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result { { if reverse { joined.reversed() } else { joined }.write(st); } + if let Some(name) = brush_name { + set_brush(d, target, name); + } if keep_selected { sel.set([id]); } else { @@ -329,11 +400,19 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result { // were, measured along the old path; fit them to the new length if strokes drawn with a // pen get redrawn. if let Some((si, sp)) = redraw_section(&pd, &pts, fit_tol, within) { - s.edit(if brush { "Paintbrush" } else { "Pencil" }, |d, sel| { + // A member path of a compound path is redrawn in it: the compound path is what is + // selected, and what a brush paints. + let whole = brush_target(&s.doc()?.doc, id); + if let Some(name) = brush_name + && !s.doc()?.doc.node(whole).is_some_and(|n| can_brush(&n.appearance)) + { + return Err(no_stroke(name)); + } + s.edit(label, |d, sel| { *path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| bad(C, "no such subpath"))? = sp; - // A member path of a compound path is redrawn in it: the compound path is what is - // selected. - let whole = d.parent_of(id).filter(|p| d.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))).unwrap_or(id); + if let Some(name) = brush_name { + set_brush(d, whole, name); + } if keep_selected { sel.set([whole]); } else { @@ -356,7 +435,15 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result { if let Some(st) = look.appearance.stroke_mut() { pen.write(st); } - let out = insert_look(s, if brush { "Paintbrush" } else { "Pencil" }, path_kind(PathData::single(sp)), look, None, keep_selected)?; + if let Some(name) = brush_name { + if !can_brush(&look.appearance) { + return Err(no_stroke(name)); + } + if let Some(st) = look.appearance.stroke_mut() { + st.brush = Some(name.to_string()); + } + } + let out = insert_look(s, label, path_kind(PathData::single(sp)), look, None, keep_selected)?; if !keep_selected { // A new stroke with Keep selected off leaves nothing selected: Illustrator starts the stroke // by dropping the earlier selection, it does not keep it (#5752). @@ -399,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 560990cec1..d0f480d132 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -13,9 +13,283 @@ use super::{ /// of path within the reach on either side of it. VectorCraft's own value. const SMOOTH_SPREAD: f64 = 1.0 / 3.0; +/// The degrees by which a path must turn at an anchor, and over the tool's reach and twice its reach +/// on either side of it, for the Smooth tool to keep the anchor as a corner ([`smooth_corners`]): a +/// turn of more than 57.5°, an angle inside the corner of less than 122.5°. VectorCraft's own value, +/// the same on every drag and at any Fidelity. +const SMOOTH_CORNER_DEG: f64 = 57.5; + +/// Most pieces a curved segment is cut into evenly, and most more pieces near each of its ends, to +/// measure lengths along it in [`smooth_corners`]. +const CORNER_PIECES: usize = 64; + +/// The control polygon's length of `c`, which is at least its length. +fn polygon_len(c: CubicBez) -> f64 { + c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3) +} + +/// The places (0 to 1, in order, without 0 and with 1) on the curved segment `c` that +/// [`smooth_corners`] measures it at: up to [`CORNER_PIECES`] evenly spaced, and near each end, over +/// a stretch at least three times `reach` long where the segment is that long, up to as many more +/// that are no more than `reach` / 8 apart along the control polygon, and as many again in each +/// stretch twice as long after it until the pieces reach three times `reach`. The turns over `reach` and +/// twice `reach` from an anchor are then measured along the curve however long the segment is. +fn corner_places(c: CubicBez, reach: f64) -> Vec { + let piece = reach / 8.0; + let pieces = |len: f64| if piece > 0.0 { (len / piece).ceil().clamp(1.0, CORNER_PIECES as f64) as usize } else { 1 }; + let k = pieces(polygon_len(c)).max(4); + let mut places: Vec = (1..=k).map(|j| j as f64 / k as f64).collect(); + if piece > 0.0 { + for from_start in [true, false] { + // The stretch from the end: halved until its control polygon is at most six reaches long. + let first = 1.0 / k as f64; + let mut t = first; + let part = |t: f64| if from_start { c.subsegment(0.0..t) } else { c.subsegment(1.0 - t..1.0) }; + for _ in 0..60 { + if polygon_len(part(t)) <= 6.0 * reach { + break; + } + t /= 2.0; + } + let side = |u: f64| if from_start { u } else { 1.0 - u }; + let m = pieces(polygon_len(part(t))); + let mut fine: Vec = (1..=m).map(|j| t * j as f64 / m as f64).collect(); + // Then the stretches twice as long in turn, cut as finely, up to the first even place, until + // the pieces reach three reaches from the end, so twice the reach is measured along the curve + // where a handle that does not reach out makes the curve start more slowly than its polygon. + let mut covered = 0.0; + let mut at = c.eval(side(0.0)); + for u in &fine { + let q = c.eval(side(*u)); + covered += at.distance(q); + at = q; + } + let (mut from, mut levels) = (t, 0); + while covered < 3.0 * reach && from < first && levels < 60 { + let to = (2.0 * from).min(first); + let piece_len = polygon_len(if from_start { c.subsegment(from..to) } else { c.subsegment(1.0 - to..1.0 - from) }); + let m = pieces(piece_len); + for j in 1..=m { + let u = from + (to - from) * j as f64 / m as f64; + let q = c.eval(side(u)); + covered += at.distance(q); + at = q; + fine.push(u); + } + (from, levels) = (to, levels + 1); + } + places.extend(fine.into_iter().map(side)); + } + } + places.retain(|u| *u > 0.0 && *u <= 1.0); + places.sort_by(f64::total_cmp); + places.dedup(); + places +} + +/// The degrees between the directions `u` and `v`, `None` when either has no length or is not a +/// number. +fn turn_between(u: kurbo::Vec2, v: kurbo::Vec2) -> Option { + let (lu, lv) = (u.hypot(), v.hypot()); + if !(lu.is_finite() && lv.is_finite() && lu > 1e-12 && lv > 1e-12) { + return None; + } + let deg = u.cross(v).atan2(u.dot(v)).abs().to_degrees(); + deg.is_finite().then_some(deg) +} + +/// Which anchors of `anchors` (a closed path when `closed`) the Smooth tool keeps as corners: those +/// where the path turns by more than [`SMOOTH_CORNER_DEG`] at the anchor itself, between the +/// direction it arrives along and the one it leaves along, and also over `reach` and over twice +/// `reach` on either side of it, between the direction from the point that far back along the path +/// to the anchor and the direction from the anchor to the point that far ahead. The points are taken +/// no farther than the ends of an open path, and no more than an eighth of the way round a closed +/// one. A jag or a bump smaller than the reach turns sharply at its anchor but not over twice the +/// reach, and an anchor in the middle of a tight curve turns over the reach but not at the anchor, so +/// neither is kept. An open path's first and last anchors are never corners. +fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec { + let n = anchors.len(); + let mut corners = vec![false; n]; + if n < 2 || (n < 3 && !closed) { + return corners; + } + // The distances on either side the turn is measured over: one reach and two, no more than an + // 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 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; + } + spans = spans.map(|r| r.min(total / 8.0)); + } + for (i, flag) in corners.iter_mut().enumerate() { + if !closed && (i == 0 || i == n - 1) { + continue; + } + let (prev, a, next) = (anchors[(i + n - 1) % n], anchors[i], anchors[(i + 1) % n]); + let arrive = [a.p - a.h_in, a.p - prev.h_out, a.p - prev.p].into_iter().find(|d| d.hypot() > 1e-12).unwrap_or_default(); + let leave = [a.h_out - a.p, next.h_in - a.p, next.p - a.p].into_iter().find(|d| d.hypot() > 1e-12).unwrap_or_default(); + if !turn_between(arrive, leave).is_some_and(|t| t > SMOOTH_CORNER_DEG) { + 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)); + } + corners +} + +/// 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 +/// points at [`corner_places`]. It gives the points at the distances `to` (in order, the nearer +/// first), an open path's end for one beyond the end, and `None` for one it did not reach within +/// `segments` segments, and the length it walked. Both points are `None` when it meets a length that +/// is not a number or is too large to add, and the length is then infinite. +fn walk(anchors: &[Anchor], closed: bool, from: (usize, bool), to: [f64; 2], reach: f64, segments: usize) -> ([Option; 2], f64) { + let (n, forward) = (anchors.len(), from.1); + let Some(mut here) = anchors.get(from.0).map(|a| a.p) else { return ([None; 2], 0.0) }; + let (mut at, mut gone) = (from.0, 0.0); + let mut found: [Option; 2] = [None; 2]; + let mut at_end = false; + 'segments: for _ in 0..segments { + let next = match (forward, closed) { + (true, _) if at + 1 < n => at + 1, + (true, true) => 0, + (false, _) if at > 0 => at - 1, + (false, true) => n - 1, + _ => { + at_end = true; + break; + } + }; + let (a, b) = (anchors[at], anchors[next]); + let c = if forward { CubicBez::new(a.p, a.h_out, b.h_in, b.p) } else { CubicBez::new(a.p, a.h_in, b.h_out, b.p) }; + let places = if c.p1 == c.p0 && c.p2 == c.p3 { vec![1.0] } else { corner_places(c, reach) }; + for u in places { + let q = if u >= 1.0 { c.p3 } else { c.eval(u) }; + let d = here.distance(q); + if !(d.is_finite() && (gone + d).is_finite()) { + return ([None; 2], f64::INFINITY); + } + for (slot, &dist) in found.iter_mut().zip(&to) { + if slot.is_none() && gone + d >= dist { + let t = if d > 0.0 { ((dist - gone) / d).clamp(0.0, 1.0) } else { 1.0 }; + *slot = Some(here.lerp(q, t)); + } + } + gone += d; + here = q; + if found.iter().all(Option::is_some) { + break 'segments; + } + } + at = next; + } + // An open path that ends after the last segment walked ends there too. + if !closed && at == if forward { n - 1 } else { 0 } { + at_end = true; + } + (found.map(|p| p.or(at_end.then_some(here))), gone) +} + +/// Whether `a` and `b` are the same anchors, to within a rounding error. +fn same_anchors(a: &[Anchor], b: &[Anchor]) -> bool { + let near = |p: Point, q: Point| p.distance(q) <= 1e-9; + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| near(x.p, y.p) && near(x.h_in, y.h_in) && near(x.h_out, y.h_out)) +} + +/// [`refit_run`] of the open run `anchors` cut at its anchors marked in `corners`: each part between +/// two corners is smoothed and refitted on its own, so each corner keeps its place and the direction +/// the path arrives and leaves along. `free` applies to the run's first and last anchors only. +fn refit_split(anchors: &[Anchor], corners: &[bool], tol: f64, sigma: f64, free: [bool; 2]) -> Vec { + let last = anchors.len().saturating_sub(1); + let mut cuts: Vec = (1..last).filter(|&i| corners.get(i).copied().unwrap_or(false)).collect(); + if cuts.is_empty() { + return refit_run(anchors, tol, sigma, free); + } + cuts.insert(0, 0); + cuts.push(last); + let mut out: Vec = Vec::with_capacity(anchors.len()); + for w in cuts.windows(2) { + let (a, b) = (w[0], w[1]); + let part = refit_run(&anchors[a..=b], tol, sigma, [free[0] && a == 0, free[1] && b == last]); + match out.pop() { + // The corner ends one part and starts the next: it keeps its place, and takes the handle + // in from the part before and the handle out from the part after. + Some(end) => { + let mut rest = part.into_iter(); + if let Some(start) = rest.next() { + out.push(Anchor::with_handles(anchors[a].p, end.h_in, start.h_out)); + } + out.extend(rest); + } + None => out.extend(part), + } + } + out +} + /// The options the Smooth tool refits with: the path smoothed along its length by a Gaussian of /// spread `sigma` (none at 0), then refitted within `tol` of that and within twice the distance the -/// smoothing moved it, keeping a corner only where the path turns back on itself. `free` says whether +/// smoothing moved it. The tool cuts the path at its corners first ([`smooth_corners`]), so within a +/// part the refit keeps a corner only where the path turns back on itself. `free` says whether /// the start and the end of the stretch refitted are ends of an open path, whose direction then /// follows the smoothed path within the reach rather than the first or last segment. fn refit_options(tol: f64, sigma: f64, free: [bool; 2]) -> SimplifyOptions { @@ -46,7 +320,85 @@ fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64, free: [bool; 2]) -> Vec (usize, f64) { + let mut best: Option<(f64, usize, f64)> = None; + for j in 0..orig.anchors.len() { + let hit = orig.segment(j).nearest(p, 1e-9); + if hit.distance_sq.is_finite() && hit.t.is_finite() && best.is_none_or(|(d, ..)| hit.distance_sq < d) { + best = Some((hit.distance_sq, j, hit.t)); + } + } + best.map_or((usize::MAX, f64::INFINITY), |(_, j, t)| (j, t)) +} + +/// The closed `sp` started at the point on it nearest `start`: at the anchor there, or at a new +/// anchor split into the segment there, which leaves the outline as it is. Of points equally near +/// `start`, the one earliest along `orig` (the path before smoothing) from its first anchor is used, +/// then the first in `sp`'s order. An open `sp`, or one with no segment or no finite nearest point, +/// is returned as it is. +fn start_nearest(mut sp: SubPath, start: Point, orig: &SubPath) -> SubPath { + let n = sp.anchors.len(); + if !sp.closed || n < 2 { + return sp; + } + // (distance, place along `orig` once a tie needs it, segment of `sp`, parameter) + type Best = (f64, Option<(usize, f64)>, usize, f64); + let mut best: Option = None; + for i in 0..n { + let c = sp.segment(i); + let hit = c.nearest(start, 1e-9); + if !hit.distance_sq.is_finite() || !hit.t.is_finite() { + continue; + } + let d = hit.distance_sq.sqrt(); + match &mut best { + None => best = Some((d, None, i, hit.t)), + Some((bd, bplace, bi, bt)) if (d - *bd).abs() <= START_TIE => { + let held = *bplace.get_or_insert_with(|| place_along(orig, sp.segment(*bi).eval(*bt))); + let place = place_along(orig, c.eval(hit.t)); + if place.0 < held.0 || (place.0 == held.0 && place.1 < held.1) { + best = Some((d, Some(place), i, hit.t)); + } + } + Some((bd, ..)) if d < *bd => best = Some((d, None, i, hit.t)), + Some(_) => {} + } + } + let Some((_, _, i, t)) = best else { return sp }; + let c = sp.segment(i); + let at = c.eval(t); + let first = if at.distance(c.p0) <= START_SNAP { + i + } else if at.distance(c.p3) <= START_SNAP { + (i + 1) % n + } else { + let mid = if sp.segment_is_line(i) { + Anchor::corner(at) + } else { + let (l, r) = (c.subsegment(0.0..t), c.subsegment(t..1.0)); + sp.anchors[i].h_out = l.p1; + sp.anchors[(i + 1) % n].h_in = r.p2; + Anchor::with_handles(at, l.p2, r.p1) + }; + sp.anchors.insert(i + 1, mid); + i + 1 + }; + sp.anchors.rotate_left(first); + sp } /// Pieces of curve that one Smooth drag measures against the drag while it searches the segments @@ -226,6 +578,9 @@ fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, share: usize) -> (SubP (out, marked) } +/// `sp` with the anchors in the drag's reach smoothed and refitted, `None` when none are in reach. +/// A closed path whose first anchor is in reach starts at the point of the refitted path nearest +/// that anchor's place (VectorCraft's own rule). fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f64, sigma: f64) -> Option { if sp.anchors.len() < 2 { return None; @@ -238,27 +593,56 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f return None; } if sp.closed { + let start = sp.anchors[0].p; let Some(k) = marked.iter().position(|m| !m) else { - // Everything is in range: smooth the whole closed path, across its start too. - let f = po::simplify_with(&PathData::single(sp.clone()), &refit_options(tol, sigma, [false; 2])); - return f.subpaths.into_iter().next(); + let corners = smooth_corners(&sp.anchors.contiguous(), true, radius); + let Some(c) = corners.iter().position(|c| *c) else { + // Everything is in range and nothing is a corner: smooth the whole closed path, + // across its start too. + let f = po::simplify_with(&PathData::single(sp.clone()), &refit_options(tol, sigma, [false; 2])); + return f.subpaths.into_iter().next().map(|r| start_nearest(r, start, sp)); + }; + // Cut the path open at a corner, which then ends the last part as well as starting the first. + let mut open = sp.anchors.to_vec(); + open.rotate_left(c); + let mut cut = corners; + cut.rotate_left(c); + open.push(open[0]); + cut.push(true); + let mut res = refit_split(&open, &cut, tol, sigma, [false; 2]); + if same_anchors(&res, &open) { + return None; + } + let l = res.pop()?; + if let Some(r0) = res.first_mut() { + *r0 = Anchor::with_handles(r0.p, l.h_in, r0.h_out); + } + // The path starts where it did when the refit keeps an anchor there, and otherwise at its + // point nearest there. + return Some(start_nearest(SubPath::new(res, true), start, sp)); }; // Rotate so an untouched anchor comes first, duplicate it at the end and treat as open. - let mut open = sp.clone(); - open.anchors.rotate_left(k); + let mut open = sp.anchors.to_vec(); + open.rotate_left(k); let mut m = marked.clone(); m.rotate_left(k); - open.anchors.push(open.anchors[0]); + open.push(open[0]); m.push(false); - open.closed = false; - let mut res = smooth_open(&open.anchors, &m, near, tol, sigma, false); + let mut res = smooth_open(&open, &m, near, tol, sigma, radius, false); + if same_anchors(&res, &open) { + return None; + } let l = res.pop()?; if let Some(r0) = res.first_mut() { r0.h_in = l.h_in; } - return Some(SubPath::new(res, true)); + // With k = 0 the first anchor is out of reach and still starts the result. + let res = SubPath::new(res, true); + return Some(if k == 0 { res } else { start_nearest(res, start, sp) }); } - Some(SubPath::new(smooth_open(&sp.anchors, &marked, near, tol, sigma, true), false)) + let anchors = sp.anchors.contiguous(); + let res = smooth_open(&anchors, &marked, near, tol, sigma, radius, true); + (!same_anchors(&res, &anchors)).then(|| SubPath::new(res, false)) } /// The segment `c`, which ends in the drag's reach (`near`) and starts outside it, split where it @@ -292,8 +676,10 @@ fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool) -> Option<(CubicBez /// drag's reach (`near`): a short drag smooths what is under it, and the rest of a long segment next /// to it stays as it was (#1512). With `open`, `anchors` are an open path, and the curve at its first /// or last anchor turns with the smoothing when a run's refit reaches that anchor; a run's other ends, -/// and those of the open run a closed path is cut into, keep their direction. -fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool, tol: f64, sigma: f64, open: bool) -> Vec { +/// and those of the open run a closed path is cut into, keep their direction. Each run keeps its +/// corners ([`smooth_corners`] within `radius`, the tool's reach, measured within the run), and a run +/// whose refit changes nothing stays as it was. +fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool, tol: f64, sigma: f64, radius: f64, open: bool) -> Vec { let n = anchors.len(); let mut runs = vec![]; let mut i = 0; @@ -334,7 +720,11 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool *outer = Anchor::with_handles(far.p3, far.p2, reach.p1); } let free = [open && lo == 0 && head.is_none(), open && hi == n - 1 && tail.is_none()]; - let new = refit_run(&piece, tol, sigma, free); + let corners = smooth_corners(&piece, false, radius); + let new = refit_split(&piece, &corners, tol, sigma, free); + if same_anchors(&new, &piece) { + continue; + } out.splice(lo..=hi, head.into_iter().chain(new).chain(tail)); } out @@ -621,6 +1011,89 @@ pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result { mod tests { use super::*; + /// A closed ring of four smooth anchors round (100, 100) with radius 50. + fn ring() -> SubPath { + let k = 0.5523 * 50.0; + let a = |x: f64, y: f64, dx: f64, dy: f64| Anchor::with_handles(Point::new(x, y), Point::new(x - dx, y - dy), Point::new(x + dx, y + dy)); + SubPath::new(vec![a(150.0, 100.0, 0.0, k), a(100.0, 150.0, -k, 0.0), a(50.0, 100.0, 0.0, -k), a(100.0, 50.0, k, 0.0)], true) + } + + /// A start between two anchors of a curve splits that curve there into two that trace it, and the + /// new anchor comes first. + #[test] + fn start_nearest_splits_a_curve_where_it_passes_the_start() { + let sp = ring(); + let old = sp.segment(0); + let start = old.eval(0.3) + (old.eval(0.3) - Point::new(100.0, 100.0)) * 0.1; + let out = start_nearest(sp.clone(), start, &sp); + assert!(out.closed && out.anchors.len() == 5, "{out:?}"); + let t = old.nearest(start, 1e-9).t; + assert!(out.anchors[0].p.distance(old.eval(t)) < 1e-9, "{out:?}"); + let (head, rest) = (out.segment(4), out.segment(0)); + for k in 0..=8 { + let u = f64::from(k) / 8.0; + assert!(head.eval(u).distance(old.eval(t * u)) < 1e-9); + assert!(rest.eval(u).distance(old.eval(t + (1.0 - t) * u)) < 1e-9); + } + for i in 1..4 { + assert_eq!(out.segment(i), sp.segment(i), "segment {i} stays"); + } + } + + /// A start within [`START_SNAP`] of an anchor starts the ring at that anchor, with no anchor added. + #[test] + fn start_nearest_starts_at_an_anchor_near_the_start() { + let sp = ring(); + let out = start_nearest(sp.clone(), Point::new(50.0, 100.0 + START_SNAP / 2.0), &sp); + let mut want = sp.anchors.clone(); + want.rotate_left(2); + assert_eq!(out.anchors, want); + } + + /// A start on a straight side of a triangle adds a corner point there without handles, and the + /// sides stay straight. + #[test] + fn start_nearest_splits_a_line_with_a_corner_point() { + let sp = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(50.0, 80.0)], true); + let out = start_nearest(sp.clone(), Point::new(40.0, -5.0), &sp); + let want: Vec = [(40.0, 0.0), (100.0, 0.0), (50.0, 80.0), (0.0, 0.0)].map(|(x, y)| Point::new(x, y)).to_vec(); + assert!(out.anchors.len() == 4 && out.anchors.iter().zip(&want).all(|(a, w)| a.p.distance(*w) < 1e-9), "{out:?}"); + assert!((0..4).all(|i| out.segment_is_line(i)), "{out:?}"); + } + + /// A ring whose last anchor lies on its first keeps its first anchor first, and gets no third + /// anchor at that place. + #[test] + fn start_nearest_keeps_the_first_of_two_anchors_on_one_place() { + let p = [(0.0, 0.0), (100.0, 0.0), (50.0, 80.0), (0.0, 0.0)].map(|(x, y)| Point::new(x, y)); + let sp = SubPath::polyline(&p, true); + assert_eq!(start_nearest(sp.clone(), p[0], &sp), sp); + } + + /// Of points equally near the start, the one earliest along the path before smoothing from its + /// first anchor comes first, whatever the smoothed path's order. The center of a square is equally + /// near the middle of each side. The square before smoothing starts at (-50, -50), so the middle + /// of its first side, (0, -50), comes first, though the smoothed copy starts at (50, 50). + #[test] + fn start_nearest_breaks_a_tie_by_the_order_before_smoothing() { + let p = [(-50.0, -50.0), (50.0, -50.0), (50.0, 50.0), (-50.0, 50.0)].map(|(x, y)| Point::new(x, y)); + let orig = SubPath::polyline(&p, true); + let mut sp = orig.clone(); + sp.anchors.rotate_left(2); + let out = start_nearest(sp, Point::new(0.0, 0.0), &orig); + assert!(out.closed && out.anchors.len() == 5, "{out:?}"); + assert!(out.anchors[0].p.distance(Point::new(0.0, -50.0)) < 1e-9, "{out:?}"); + assert!(out.anchors[1].p.distance(p[1]) < 1e-9, "{out:?}"); + } + + /// An open path, and a start that is not a number, leave the path as it is. + #[test] + fn start_nearest_leaves_an_open_path_or_a_start_without_a_place() { + let open = SubPath { closed: false, ..ring() }; + assert_eq!(start_nearest(open.clone(), Point::new(100.0, 50.0), &ring()), open); + assert_eq!(start_nearest(ring(), Point::new(f64::NAN, 0.0), &ring()), ring()); + } + /// Searching a curve 1,000,000 pt long under a drag of 1,000 points along it measures no more /// pieces than the budget it is given, and a search with none left gives one sample. #[test] @@ -649,4 +1122,128 @@ mod tests { assert_eq!(drag_stretches(&one), vec![0]); assert!((dist_to_stretches(&one, &[0], Point::new(13.0, 14.0)) - 5.0).abs() < 1e-12); } + + fn polyline(pts: &[(f64, f64)]) -> Vec { + pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect() + } + + /// Anchors on one point, anchors that are not numbers or are too far out to measure, and a + /// zigzag of 100,001 anchors 1 pt high give no corner and do not fail; a square's four anchors + /// are its corners, and an open path's ends never are. + #[test] + fn corners_are_found_only_where_the_path_turns_at_and_around_an_anchor() { + assert_eq!(smooth_corners(&polyline(&[(5.0, 5.0); 4]), false, 12.0), vec![false; 4]); + assert_eq!(smooth_corners(&polyline(&[(0.0, 0.0), (f64::NAN, 1.0), (10.0, 0.0)]), false, 12.0), vec![false; 3]); + assert_eq!(smooth_corners(&polyline(&[(0.0, 0.0), (1e308, 0.0), (1e308, 1e308), (-1e308, 0.0)]), true, 12.0), vec![false; 4]); + let zigzag: Vec<(f64, f64)> = (0..=100_000).map(|i| (f64::from(i), f64::from(i % 2))).collect(); + assert!(!smooth_corners(&polyline(&zigzag), false, 12.0).contains(&true)); + let square = polyline(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); + assert_eq!(smooth_corners(&square, true, 12.0), vec![true; 4]); + assert_eq!(smooth_corners(&square, false, 12.0), vec![false, true, true, false]); + assert_eq!(smooth_corners(&square, false, 0.0), vec![false, true, true, false], "with no reach the turn at the anchor decides"); + assert_eq!(smooth_corners(&square[..2], false, 12.0), vec![false; 2]); + } + + /// A 90° bump 400 pt high cut into 1 pt segments, between two long straight segments: with a 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_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)]; + pts.extend((0..steps).map(|j| { + let f = j as f64 / steps as f64; + (-400.0 + 400.0 * f, 400.0 * f) + })); + pts.extend((0..=steps).map(|j| { + let f = j as f64 / steps as f64; + (400.0 * f, 400.0 - 400.0 * f) + })); + pts.push((3000.0, 0.0)); + let anchors = polyline(&pts); + 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]); + } + + /// A 60° corner between two curved segments 1,000 pt long is found at a reach of 2 pt as it is + /// when each segment is cut into a thousand pieces: the turns over the reach are measured along the + /// curve near the anchor, not along a chord much longer than the reach. + #[test] + fn a_corner_between_long_curves_is_measured_along_them() { + // The curves arrive along x and leave at 60° to it, each bending away from the other. + let d = kurbo::Vec2::from_angle(-60f64.to_radians()); + let side = kurbo::Vec2::new(-d.y, d.x) * 1000.0; + let v = Point::new(0.0, 0.0); + let a = Anchor::with_handles(Point::new(-1000.0, 1000.0), Point::new(-1000.0, 1000.0), Point::new(-300.0, 1000.0)); + let b = Anchor::with_handles(v, Point::new(-300.0, 0.0), v + d * 300.0); + let end = v + d * 1000.0 + side; + let c = Anchor::with_handles(end, v + d * 300.0 + side, end); + let long = [a, b, c]; + let fine: Vec = { + let sp = SubPath::new(long.to_vec(), false); + let mut pts = vec![]; + for i in 0..2 { + let s = sp.segment(i); + for j in 0..1000 { + let p = s.subsegment(f64::from(j) / 1000.0..f64::from(j + 1) / 1000.0); + if j == 0 && i == 0 { + pts.push(Anchor::with_handles(p.p0, p.p0, p.p1)); + } else if let Some(last) = pts.last_mut() { + *last = Anchor::with_handles(last.p, last.h_in, p.p1); + } + pts.push(Anchor::with_handles(p.p3, p.p2, p.p3)); + } + } + pts + }; + let at_v = |anchors: &[Anchor]| { + let corners = smooth_corners(anchors, false, 2.0); + anchors.iter().zip(corners).find(|(x, _)| x.p == v).map(|(_, c)| c) + }; + assert_eq!(at_v(&fine), Some(true), "cut finely, the anchor is a corner"); + assert_eq!(at_v(&long), Some(true)); + } + + /// A line that meets a curve leaving with no handle, turning by 58° at the anchor and by about + /// 57.53° over twice a reach of 0.02 pt: the anchor is a corner, measured either way along the path, + /// as the stretch measured finely near the anchor covers twice the reach along the curve. + #[test] + fn a_corner_next_to_a_curve_without_a_handle_is_kept() { + let at = 58f64.to_radians(); + let prev = Anchor::corner(Point::new(-100.0 * at.cos(), -100.0 * at.sin())); + let v = Point::new(0.0, 0.0); + let a = Anchor::with_handles(v, v, v); + let end = Point::new(600.0, 600.0); + let next = Anchor::with_handles(end, Point::new(200.0, 0.0), end); + assert_eq!(smooth_corners(&[prev, a, next], false, 0.02), vec![false, true, false]); + let back = |x: Anchor| Anchor::with_handles(x.p, x.h_out, x.h_in); + assert_eq!(smooth_corners(&[back(next), back(a), back(prev)], false, 0.02), vec![false, true, false]); + } + + /// A jagged closed path whose length is less than twice the reach: its jags are not corners, + /// while a triangle that small keeps its three. + #[test] + fn a_small_jagged_loop_has_no_corners() { + let ring: Vec<(f64, f64)> = (0..16) + .map(|i| { + let (a, r) = (f64::from(i) / 16.0 * std::f64::consts::TAU, if i % 2 == 0 { 3.0 } else { 2.0 }); + (r * a.cos(), r * a.sin()) + }) + .collect(); + let jags = polyline(&ring); + let sp = SubPath::new(jags.clone(), true); + assert!(subpath_len(&sp) < 24.0); + assert!(smooth_corners(&jags, true, 1e-6).iter().all(|c| *c), "each jag turns sharply at its anchor"); + assert_eq!(smooth_corners(&jags, true, 12.0), vec![false; 16]); + assert_eq!(smooth_corners(&polyline(&[(0.0, 0.0), (6.0, 0.0), (3.0, 5.196)]), true, 12.0), vec![true; 3]); + } } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 9ecb5c3984..fbf5deb568 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) ), @@ -399,9 +399,7 @@ fn select_found(s: &mut Session, p: &Value, ids: &[NodeId]) -> Result { let compound = |n: &Node| matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. }); let members = st.isolation.and_then(|i| st.doc.ancestry(i)).is_some_and(|a| a.iter().any(|i| st.doc.node(*i).is_some_and(compound))); let found: BTreeSet = ids.iter().copied().collect(); - super::select::select_where(s, "document.find", p, |d, n| { - found.contains(&n.id) && (members || !d.parent_of(n.id).and_then(|p| d.node(p)).is_some_and(compound)) - }) + super::select::select_where(s, "document.find", p, |_, n, parent| found.contains(&n.id) && (members || !parent.is_some_and(compound))) } /// Render an artboard at an image's size, drawn as a PNG export draws it (linked images and placed @@ -526,26 +524,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")] @@ -808,11 +814,11 @@ fn new_document_from_state(s: &mut Session, p: &Value) -> Result { let created = date_param(p, "created", C)?; let st = s.doc()?; // The row as the panel lists it now: keeping an edit in progress below changes the rows. - let chosen = match p.get("index") { - None | Some(Value::Null) => None, - Some(v) => { - let state = v.as_u64().and_then(|row| st.history.state(&st.doc, index(row))); - Some(state.ok_or_else(|| bad(C, format!("no history state {v}")))?.clone()) + let chosen = match super::index_opt(p, "index", C)? { + None => None, + Some(row) => { + let v = &p["index"]; + Some(st.history.state(&st.doc, row).ok_or_else(|| bad(C, format!("no history state {v}")))?.clone()) } }; settle_interaction(s)?; @@ -1181,9 +1187,7 @@ fn clear(s: &mut Session, p: &Value) -> Result { d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id))); } if is_explicit { - for id in &ids { - sel.remove(*id); - } + sel.remove_all(ids.iter().copied()); sel.prune(d); } else { sel.clear(); @@ -1276,23 +1280,28 @@ pub(crate) fn place_clip(s: &mut Session, clip: &Clipboard, center: vectorcraft_ /// The artboards Paste in Place, in Front or in Back puts a copy on, in artboard order: `artboard` /// (the active one, #693), else `artboards`, else, while the Artboard tool is chosen with several /// artboards selected, those (noted in the journal as `artboards`, so a replay pastes on the same -/// ones); `None` when none is named. A named index that is not an artboard of the document, a -/// repeated one or an empty list is an error. +/// ones); `None` when none is named. A named value that is not a whole number (null included), a +/// named index that is not an artboard of the document, a repeated one or an empty list is an +/// error; every value is checked for its form before any is checked against the artboards. fn paste_targets(s: &mut Session, p: &Value, cmd: &str) -> Result>> { let n = s.doc()?.doc.artboards.len(); - let one = |v: &Value| v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < n); - let single = match p.get("artboard") { - Some(v) => Some(one(v).ok_or_else(|| bad(cmd, "`artboard` must be the index of an artboard of the document"))?), - None => None, - }; - let listed = match p.get("artboards") { + let single = p.get("artboard").map(|v| v.as_u64().map(index).ok_or_else(|| bad(cmd, "`artboard` must be a whole number"))).transpose()?; + let entries = match p.get("artboards") { Some(v) => { let list = v.as_array().filter(|a| !a.is_empty()).ok_or_else(|| bad(cmd, "`artboards` must be a list of artboard indices"))?; - let mut all = list - .iter() - .map(one) - .collect::>>() - .ok_or_else(|| bad(cmd, "`artboards` names an artboard the document does not have"))?; + let all = list.iter().map(|i| i.as_u64().map(index)).collect::>>(); + Some(all.ok_or_else(|| bad(cmd, "`artboards` must contain whole numbers"))?) + } + None => None, + }; + if single.is_some_and(|i| i >= n) { + return Err(bad(cmd, "`artboard` must be the index of an artboard of the document")); + } + let listed = match entries { + Some(mut all) => { + if all.iter().any(|i| *i >= n) { + return Err(bad(cmd, "`artboards` names an artboard the document does not have")); + } all.sort_unstable(); if all.windows(2).any(|w| w[0] == w[1]) { return Err(bad(cmd, "`artboards` names an artboard twice")); diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 65672f8b6b..5ea3efd950 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -13,7 +13,10 @@ use vectorcraft_doc::{Document, Effect, Node, NodeKind, StrokeLayer}; use vectorcraft_geom::{FillRule, PathData}; use vectorcraft_render::effects; -use super::appearance::{ItemTarget, aligned, appearance_targets, edit_targets, index_param, item_indices, item_target, item_target_at}; +use super::appearance::{ + ItemTarget, aligned, appearance_targets, design_reference, edit_targets, index_param, item_indices, item_target, item_target_at, reference_of, + with_reference, +}; use super::expand::has_seeded; use super::rasterfx; use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, check_switches, cmd, fileio, has_doc, str_param, switch_or}; @@ -49,7 +52,7 @@ fn effect_specs() -> Vec { "Apply Effect", [], None, - "{effect: id (see effect.list, e.g. \"stylize.dropShadow\", \"distort.roughen\", \"warp.arc\", or \"plugin.\" for an installed effect plug-in), params?: {…} (missing keys take the dialog defaults), item?: appearance item index|null (apply to that fill/stroke only; omitted: the Appearance panel's active item, else the whole object), ids?|id?: [..] (layers too), target?: \"object\"|\"contents\" (contents: the objects inside groups and layers)} append a live effect to each selected object's appearance (a group's or layer's apply to its members as one piece: one combined shadow; a Pathfinder effect, which combines a group's contents, groups several loose selected objects first, in the same undo step); the art of a graph design in a graph series is left out, and objects that are all such art are an error (docs/mcp.md) → {ids, index, item, grouped?}", + "{effect: id (see effect.list, e.g. \"stylize.dropShadow\", \"distort.roughen\", \"warp.arc\", or \"plugin.\" for an installed effect plug-in), params?: {…} (missing keys take the dialog defaults), item?: appearance item index|null (apply to that fill/stroke only; omitted: the Appearance panel's active item, else the whole object), ids?|id?: [..] (layers too), target?: \"object\"|\"contents\" (contents: the objects inside groups and layers), aligned?: bool (item is a row of the first target's stack: each other target gets the effect on its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, a row of the art's stack: docs/mcp.md)} append a live effect to each selected object's appearance (a group's or layer's apply to its members as one piece: one combined shadow; a Pathfinder effect, which combines a group's contents, groups several loose selected objects first, in the same undo step); the art of a graph design in a graph series is left out, and objects that are all such art are an error (docs/mcp.md) → {ids, index, item, grouped?}", has_doc, apply ), @@ -67,7 +70,7 @@ fn effect_specs() -> Vec { "Remove Effect", [], None, - "{index: int (position in the effect list), indices?: [int] (several positions in the same list instead of index, removed in one undo step; every one must exist), item?: appearance item index|null (that fill/stroke's effects; omitted: the active item, else the object's), 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)} → {ids}", + "{index: int (position in the effect list), indices?: [int] (several positions in the same list instead of index, removed in one undo step; every one must exist), item?: appearance item index|null (that fill/stroke's effects; omitted: the active item, else the object's), 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)} → {ids}", has_doc, remove ), @@ -76,7 +79,7 @@ fn effect_specs() -> Vec { "Effect Options", [], None, - "{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place; params are checked against the new style), threeDType?: plane|extrude|revolve|inflate (the 3D and Materials panel's object type: changes only an applied 3D effect in place into Rotate, Extrude & Bevel, Revolve or Inflate; the settings the new effect also takes keep their values, rotation angles wrapped into -180..180 outside Revolve, and the others start at its defaults; params then merge into the new effect's; the type the effect already has, with nothing else given, changes nothing and records no undo step), visible?: bool (any other value but null is refused, when a step plays too), item?: appearance item index|null (as effect.remove), 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)} → {ids}", + "{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place; params are checked against the new style), threeDType?: plane|extrude|revolve|inflate (the 3D and Materials panel's object type: changes only an applied 3D effect in place into Rotate, Extrude & Bevel, Revolve or Inflate; the settings the new effect also takes keep their values, rotation angles wrapped into -180..180 outside Revolve, and the others start at its defaults; params then merge into the new effect's; the type the effect already has, with nothing else given, changes nothing and records no undo step), visible?: bool (any other value but null is refused, when a step plays too), item?: appearance item index|null (as effect.remove), 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)} → {ids}", has_doc, set_params ), @@ -85,7 +88,7 @@ fn effect_specs() -> Vec { "3D Lighting Preset", [], None, - "{index: int, preset: standard|diffuse|topLeft|right, item?: appearance item index|null (omitted: the active item, else the object's), 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)} replace an applied 3D effect's light rig and ambient with an original lighting preset; preserve shading, geometry and view; all targets must have a 3D effect at index other than Extrude & Bevel (Classic), Revolve (Classic) or Rotate (Classic), which have no lighting presets; one undo step → {ids}", + "{index: int, preset: standard|diffuse|topLeft|right, item?: appearance item index|null (omitted: the active item, else the object's), 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)} replace an applied 3D effect's light rig and ambient with an original lighting preset; preserve shading, geometry and view; all targets must have a 3D effect at index other than Extrude & Bevel (Classic), Revolve (Classic) or Rotate (Classic), which have no lighting presets; one undo step → {ids}", has_doc, lighting_preset ), @@ -94,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 ), @@ -103,7 +106,7 @@ fn effect_specs() -> Vec { "Duplicate Effect", [], None, - "{index: int, indices?: [int] (several positions in the same list instead of index; every one must exist), item?: appearance item index|null (as effect.remove), 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)} insert a copy of each effect right after it, in one undo step → {ids}", + "{index: int, indices?: [int] (several positions in the same list instead of index; every one must exist), item?: appearance item index|null (as effect.remove), 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)} insert a copy of each effect right after it, in one undo step → {ids}", has_doc, duplicate ), @@ -112,7 +115,7 @@ fn effect_specs() -> Vec { "Move Effect", [], None, - "{from: int|[int] (position in the source list; a list moves several effects of that list, which keep their order and land together), to: int (the position of the (first) moved effect in the destination list afterwards), fromItem?: appearance item index|null (the source list: that fill/stroke's effects, null the object's; omitted: the active item, else the object's), toItem?: item index|null (the destination list; default: the source list), copy?: bool (copy instead of move, as Alt-dragging the row), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (refused when the targets' appearances differ)} reorder an effect or move it between the object and its fills/strokes, as one undo step → {ids, index, item}", + "{from: int|[int] (position in the source list; a list moves several effects of that list, which keep their order and land together), to: int (the position of the (first) moved effect in the destination list afterwards), fromItem?: appearance item index|null (the source list: that fill/stroke's effects, null the object's; omitted: the active item, else the object's), toItem?: item index|null (the destination list; default: the source list), copy?: bool (copy instead of move, as Alt-dragging the row), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (refused when the targets' appearances differ, or differ from that of a graph design's art given first)} reorder an effect or move it between the object and its fills/strokes, as one undo step → {ids, index, item}", has_doc, move_effect ), @@ -296,14 +299,20 @@ fn ids_json(ids: &[NodeId]) -> Value { /// effects it edits (`None`: the object's own) and the effect's index there. With `aligned` (see /// [`ItemTarget::per_target`]) `item` and `index` are the first target's, and each other target /// edits its equal item, or its equal object-level effect, each target matched on its own whatever -/// the other targets have; in a target without them, `item` and `index` stand for themselves. +/// the other targets have; in a target without them, `item` and `index` stand for themselves. When the first object +/// given is the art of a graph design in a series ([`design_reference`]), which is left out, they are rows of its stack, +/// and a target without them is left out. pub(crate) fn effect_targets(s: &Session, p: &Value, item: ItemTarget, index: usize, cmd: &str) -> Result, usize)>> { - let roots = edit_targets(s, p)?; + let roots = edit_targets(s, p, cmd)?; + let of = reference_of(s, p, item, cmd)?; let d = &s.doc()?.doc; - let per = item.per_target(s, &roots); - let first = roots.first().and_then(|f| d.node(*f)); + let per = item.per_target_of(s, of, &roots); + let first = of.or_else(|| roots.first().copied()).and_then(|f| d.node(f)); // Whether `item` names an item in the stack it is a row of (else the edit is object-level there). - let anchor = roots.get(item.anchor(s, &roots)).and_then(|a| d.node(*a)); + let anchor = match of { + Some(of) => d.node(of), + None => roots.get(item.anchor(s, &roots)).and_then(|a| d.node(*a)), + }; let anchor_level = anchor.map(|a| item.effects_item(&a.appearance, cmd)).transpose()?.flatten(); let aligned = aligned(p, cmd)?; let mut out = Vec::with_capacity(roots.len()); @@ -312,7 +321,11 @@ pub(crate) fn effect_targets(s: &Session, p: &Value, item: ItemTarget, index: us let at = item.effects_item(&n.appearance, cmd)?; // An object-level effect this target shares with the first is where it is in this target. let index = match (first.filter(|_| aligned), at, anchor_level) { - (Some(f), None, None) => SharedStack::of(&[&*f.appearance, &*n.appearance]).effect_in(index, 1).unwrap_or(index), + (Some(f), None, None) => match SharedStack::of(&[&*f.appearance, &*n.appearance]).effect_in(index, 1) { + Some(i) => i, + None if of.is_some() && index != APPENDED => continue, + None => index, + }, _ => index, }; out.push((*id, at, index)); @@ -320,6 +333,10 @@ pub(crate) fn effect_targets(s: &Session, p: &Value, item: ItemTarget, index: us Ok(out) } +/// The effect index `effect.apply` gives [`effect_targets`] for the effect it appends, which names no effect the targets +/// have. +const APPENDED: usize = usize::MAX; + #[allow(clippy::too_many_arguments)] fn edit_effects( s: &mut Session, @@ -350,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, @@ -362,10 +380,29 @@ fn edit_effects_at( indices: &[usize], mut f: impl FnMut(&mut Vec, &[usize]) -> bool, ) -> Result> { + // With a graph design's art given first, the indices are effects of its list: one it doesn't have names no effect, + // and the edit is refused as a whole, as it is in a list that lacks one of them. + if let Some(of) = reference_of(s, p, item, cmd)? + && let Some(n) = s.doc()?.doc.node(of) + { + let ap = &n.appearance; + let len = match item.effects_item(ap, cmd)? { + None => ap.effects.len(), + Some(i) => ap.items.get(i).map_or(0, |it| it.effects().len()), + }; + if indices.iter().any(|i| *i >= len) { + return Err(EngineError::Other(none.into())); + } + } // 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])), @@ -427,6 +464,7 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { } super::params::check_effect_color(C, id, ¶ms)?; super::params::check_effect_channel(C, id, ¶ms)?; + super::params::check_effect_center(C, id, ¶ms)?; // Crop Marks take their style from the preferences when applied. if id == effects::CROP_MARKS && params.get("style").is_none() { params["style"] = json!(s.crop_mark_style().id()); @@ -452,13 +490,18 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { return Ok(json!({ "ids": [gid.0], "index": 0, "item": null, "grouped": true })); } let item = item_target(s, p, C)?; + // The item as each target has it, read before the effect changes their rows: a row of a graph design's art, which is + // left out of the targets, is the row equal to it there, and a target without one is left out. + let targets = edit_targets(s, p, C)?; + let of = reference_of(s, p, item, C)?; + let per: Vec<(NodeId, Option)> = targets.iter().copied().zip(item.per_target_of(s, of, &targets)).collect(); if effects::is_three_d(id) { - let targets = edit_targets(s, p)?; - for (target, at) in targets.iter().copied().zip(item.per_target(s, &targets)) { + for &(target, at) in &per { + let Some(at) = at else { continue }; let d = &s.doc()?.doc; let n = d.node(target).ok_or(EngineError::NoNode(target))?; // A new effect goes after the item's (or the object's) others. - let on = at.and_then(|at| at.effects_item(&n.appearance, C).ok()).flatten(); + let on = at.effects_item(&n.appearance, C).ok().flatten(); let on = on.and_then(|i| Some((Some(i), n.appearance.items.get(i)?.effects().len()))); let on = on.unwrap_or((None, n.appearance.effects.len())); effects::validate_three_d_at_in(Some(d), n, id, &effect.params, on).map_err(|e| bad(C, e))?; @@ -473,14 +516,19 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { } } } - let ids = edit_effects(s, p, item, C, &label, "Apply Effect: select objects", 0, |fx, _| { + let ids = edit_effects(s, p, item, C, &label, "Apply Effect: select objects", APPENDED, |fx, _| { fx.push(effect.clone()); true })?; // The item the effect landed on in the object whose row the item is (the first selected object // for the active item, which applies where it fits), and the effect's index in that object. - let first = ids.get(item.anchor(s, &ids)).and_then(|id| s.doc().ok()?.doc.node(*id)); - let landed = first.and_then(|n| item.effects_item(&n.appearance, C).ok().flatten()); + let k = item.anchor(s, &ids); + let first = ids.get(k).and_then(|id| s.doc().ok()?.doc.node(*id)); + let at = match of { + Some(_) => ids.get(k).and_then(|id| per.iter().find(|(t, _)| t == id)).and_then(|(_, at)| *at).unwrap_or(item), + None => item, + }; + let landed = first.and_then(|n| at.effects_item(&n.appearance, C).ok().flatten()); let index = first.and_then(|n| n.appearance.effects_at(landed)).map_or(0, |fx| fx.len().saturating_sub(1)); Ok(json!({ "ids": ids_json(&ids), "index": index, "item": landed })) } @@ -494,7 +542,7 @@ fn loose_for_pathfinder(s: &Session, p: &Value, id: &str) -> Result= 2 && !grouped).then_some(roots)) } @@ -607,9 +655,9 @@ fn move_effect(s: &mut Session, p: &Value) -> Result { let src = item_target_at(s, p, "fromItem", C)?; let dst = if p.get("toItem").is_some() { item_target_at(s, p, "toItem", C)? } else { src }; let copy = switch_or(p, "copy", false, C)?; - let roots = edit_targets(s, p)?; + let roots = edit_targets(s, p, C)?; // Where an aligned effect would go in each of several different stacks isn't one place. - if aligned(p, C)? && super::appearance::appearances_differ(&s.doc()?.doc, &roots) { + if aligned(p, C)? && super::appearance::appearances_differ(&s.doc()?.doc, &with_reference(design_reference(s, p, C)?, &roots)) { return Err(bad(C, "effects of objects whose appearances differ can't be moved together")); } // Where the effect landed in each object it moved in, in the order of `ids`. @@ -718,7 +766,7 @@ fn lighting_preset(s: &mut Session, p: &Value) -> Result { /// sets its Warp style (`warpStyle`), its 3D type (`threeDType`) or visibility (`visible`), as one /// undo step. They are checked as `effect.apply` checks them, and a visible 3D effect must still /// fit; a hidden one has its given values checked. → `{ids}`. -fn set_params(s: &mut Session, p: &Value) -> Result { +pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { const C: &str = "effect.setParams"; let index = index_param(p, "index", C)?; let mut params = p.get("params").cloned().unwrap_or(Value::Null); @@ -740,6 +788,7 @@ fn set_params(s: &mut Session, p: &Value) -> Result { for effect in &edited { super::params::check_effect_color(C, effect, ¶ms)?; super::params::check_effect_channel(C, effect, ¶ms)?; + super::params::check_effect_center(C, effect, ¶ms)?; } if edited.iter().any(|e| texture_load_effect(e)) { load_texture(&mut params, C)?; @@ -833,11 +882,13 @@ fn set_params(s: &mut Session, p: &Value) -> Result { const GLASS: &str = "distort.glass"; /// Effect › Texture › Texturizer. const TEXTURIZER: &str = "texture.texturizer"; +/// Effect › Artistic › Rough Pastels. +const ROUGH_PASTELS: &str = "artistic.roughPastels"; /// Does effect `id` have Load Texture: a `textureImage` that `effect.apply` reads from an image -/// file (Glass, Texturizer)? +/// file (Glass, Texturizer, Rough Pastels)? pub(crate) fn texture_load_effect(id: &str) -> bool { - id == GLASS || id == TEXTURIZER + id == GLASS || id == TEXTURIZER || id == ROUGH_PASTELS } /// Glass's `textureImage` in `params` as Glass stores it: an image file (`{path}`, or `{name?, @@ -894,8 +945,11 @@ fn can_expand(s: &Session) -> std::result::Result<(), String> { has_doc(s)?; let ids = appearance_targets(s, &Value::Null).map_err(|e| e.to_string())?; let d = &s.doc().map_err(|e| e.to_string())?.doc; + // The art of a graph design in a series, selected or inside a selected graph, is drawn again from the design. + let ids = super::appearance::drop_design_art(d, ids); // A dimension selected with the art it measures is left as it is. - let kept = super::dimension::with_their_art(d, &ids); + let mut kept = super::dimension::with_their_art(d, &ids); + kept.extend(super::appearance::design_art_in(d, &ids)); if ids.iter().filter_map(|id| d.node(*id)).any(|n| expandable_except(n, &kept)) { Ok(()) } else { @@ -909,32 +963,96 @@ 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. `Err` when such a member still holds a random Transform effect after the +/// raster budget left part of it as it is: its new ids would give that effect another seed. +#[allow(clippy::too_many_arguments)] fn expand_pieces( d: &mut Document, m: &mut Node, all: bool, brushes: &[vectorcraft_brush::Brush], + skip: &[NodeId], + kept: &mut Vec, stroke_art: effects::StrokeArt, -) -> std::collections::HashMap> { + raster: &mut RasterBudget, +) -> std::result::Result>, OverBudget> { let id = m.id; let mut seen = std::collections::HashSet::from([id]); let mut expanded = std::collections::HashMap::new(); @@ -948,48 +1066,116 @@ 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)); + let left = raster.left; + let expanded = expand_in_place(d, c, brushes, skip, raster); + if raster.left > left && has_seeded(c) { + return Err(OverBudget); + } + listed = Some(expanded); + } + let mut was = vec![]; + if !skip.is_empty() { + 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); } } - expanded + Ok(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(); @@ -1004,9 +1190,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 @@ -1028,11 +1214,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. @@ -1043,14 +1244,99 @@ pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_b } } +/// Replace `n`, a group or layer whose Transform effect's copies each carry the raster effects +/// listed before it ([`effects::outer_effects`]), with its art ([`effects::evaluate_container`]): +/// the copies become groups of their own with those effects, and they and what they hold get ids +/// of their own, so they expand as its members do; the raster effects after the Transform effect +/// stay on `n`. A copy that repeats an id ([`repeats_an_id`]) and holds a random Transform effect +/// ([`has_seeded`]) expands before its ids change ([`expand_in_place`]), as [`expand_pieces`] does, +/// and `members` gets what that expansion lists, by the copy's new id. `kept` gets the new id of +/// each copy of an object `skip` lists, and `out` gets `n` unless `listed` says it is there. +/// Returns whether `n` changed; any other object stays as it is. `Err`, with `n` as it is, when +/// such a copy still holds a random Transform effect after the raster budget left part of it as +/// it is: its new ids would give that effect another seed. +fn copies_carrying_raster( + d: &mut Document, + n: &mut Node, + (brushes, skip): (&[vectorcraft_brush::Brush], &[NodeId]), + kept: &mut Vec, + members: &mut std::collections::HashMap>, + (out, listed): (&mut Vec, &mut bool), + raster: &mut RasterBudget, +) -> std::result::Result { + if !carries_copies(n) { + return Ok(false); + } + let Some(mut m) = effects::evaluate_container(Some(&*d), n) else { return Ok(false) }; + let mut seen = std::collections::HashSet::from([n.id]); + for c in m.children_mut().into_iter().flatten().filter(|c| !c.is_ruler_guide()) { + let c = Arc::make_mut(c); + let left = raster.left; + let mut expanded = (has_seeded(c) && repeats_an_id(c, &seen)).then(|| expand_in_place(d, c, brushes, skip, raster)); + if expanded.is_some() && raster.left > left && has_seeded(c) { + return Err(OverBudget); + } + let mut was = vec![]; + if !skip.is_empty() { + c.walk(&mut |n| was.push(n.id)); + } + fresh_ids_listed(d, c, &mut seen, expanded.as_deref_mut().unwrap_or_default()); + // A copy of an object `skip` lists is left as it is too. + let mut at = 0; + c.walk(&mut |n| { + if was.get(at).is_some_and(|old| *old != n.id && skip.contains(old)) { + kept.push(n.id); + } + at += 1; + }); + if let Some(expanded) = expanded { + members.insert(c.id, expanded); + } + } + if !*listed { + out.push((n.id, 0)); + *listed = true; + } + *n = m; + Ok(true) +} + +/// Is `n` a group or layer whose Transform effect's copies each carry the raster effects listed +/// before it ([`copies_carrying_raster`])? +fn carries_copies(n: &Node) -> bool { + is_container(n) && effects::outer_effects(n).len() != n.appearance.effects.len() +} + +/// Does `n`, something in it, or the art of the symbol it places when a color adjustment makes it +/// that art, hold a random Transform effect ([`has_seeded`])? The raster budget can then leave `n` +/// as it is after part of it expanded ([`expand_pieces`], Crop Marks). +fn holds_seeded(d: &Document, n: &Node) -> bool { + has_seeded(n) + || match &n.kind { + NodeKind::SymbolInstance { symbol, .. } if effects::has_adjustment(n) => { + d.symbols.iter().find(|s| s.name == *symbol).is_some_and(|s| has_seeded(&s.art)) + } + _ => false, + } +} + /// [`expand_node`] of `n`, which need not be in `d`: `n` with its appearance expanded, `None` when /// it has nothing to expand. `out` gets the objects whose appearance expands, by places in the walk -/// of the expanded `n`, `n`'s first when its own does. -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; @@ -1063,6 +1349,23 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br } _ => None, }; + // The embedded images before the adjustment and the expansions of the copies + // ([`copies_carrying_raster`]) and of the members that hold a random Transform effect, when the + // raster budget may yet leave `n` as it is: the recolored copies and the images those add then + // go again. + let images_before = ((effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty()) || carries_copies(&n) || holds_seeded(d, &n)) + .then(|| d.images.keys().cloned().collect::>()); + // What the raster budget had left before those expansions: it gets back what they took. + let budget_before = (raster.images, raster.pixels); + // `n` stays as it is: `out` lists nothing of it, and the document and the raster budget lose + // what expanding it added and took. + let leave = |d: &mut Document, out: &mut Vec, raster: &mut RasterBudget| { + out.truncate(listed_before); + if let Some(keys) = &images_before { + d.images.retain(|k, _| keys.contains(k)); + } + (raster.images, raster.pixels) = budget_before; + }; if effects::has_adjustment(&n) && let Some(m) = effects::adjust_in_document(d, &n, symbol_art) { @@ -1078,14 +1381,21 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br let container = is_container(&n); // Crop Marks: the object and its marks become a group. The object expands on its own first, // with `id`: the canvas draws it with that id, which Random in a Transform effect takes its - // seed from. Then the object and the marks get ids of their own. + // seed from. Then the object and the marks get ids of their own. When the raster budget leaves + // a random Transform effect in the object, `n` stays as it is: new ids would give that effect + // another seed. if let Some(mut m) = effects::crop_marks_art(&n) { let mut seen = std::collections::HashSet::from([id]); let mut expanded = vec![]; for (i, c) in m.children_mut().into_iter().flatten().enumerate() { let c = Arc::make_mut(c); if i == 0 { - expanded = expand_in_place(d, c, brushes); + let left = raster.left; + expanded = expand_in_place(d, c, brushes, skip, raster); + if raster.left > left && has_seeded(c) { + leave(d, out, raster); + return None; + } fresh_ids_listed(d, c, &mut seen, &mut expanded); } else { effects::fresh_ids(d, c, &mut seen); @@ -1108,13 +1418,27 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br } return Some(m); } - let image = raster_image(d, &n); + // New ids of the copies of objects `skip` lists among the members. + let mut kept = vec![]; + // Members of a group or layer that `expand_pieces` or `copies_carrying_raster` expanded, by id, + // with what their expansion lists. + let mut members = std::collections::HashMap::new(); + let copies = copies_carrying_raster(d, &mut n, (brushes, skip), &mut kept, &mut members, (out, &mut listed_n), raster); + // Raster effects whose image would go past the budget stay: so does the object, with what is + // inside it and its color adjustments (a symbol instance stays an instance of its symbol), and + // so does a group or layer whose copies or members keep a random Transform effect the budget + // left. + let Ok(image) = copies.and_then(|copied| { + changed |= copied; + raster_image(d, &n, raster) + }) else { + leave(d, out, raster); + return None; + }; let mut v = n.clone(); rasterfx::strip_raster(&mut v, false); let mut stroke_art = |d: &mut Document, path: &PathData, rule: FillRule, st: &StrokeLayer| super::pathops::outlined_stroke(d, brushes, path, rule, st); - // Members of a group or layer that `expand_pieces` expanded, by id, with what their expansion lists. - let mut members = std::collections::HashMap::new(); 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). @@ -1122,18 +1446,20 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br image => { let m = if (container || matches!(n.kind, NodeKind::Text(_))) && (effects::has_solid(&v) || effects::has_revolve(&v)) { // A 3D effect on a group or layer, or on type: the shaded faces of its solids. - effects::expand_leaf(d, &v, &mut stroke_art) + Ok::<_, OverBudget>(effects::expand_leaf(d, &v, &mut stroke_art)) } else if container { // A group's or layer's own fills and strokes become art among its members. - effects::evaluate_container(Some(&*d), &v).map(|mut m| { - members = expand_pieces(d, &mut m, false, brushes, &mut stroke_art); - m - }) + effects::evaluate_container(Some(&*d), &v) + .map(|mut m| { + members.extend(expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster)?); + Ok(m) + }) + .transpose() } else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && !effects::has_transform_art(&v) && !effects::has_transform_copies(&v) { - effects::expand_leaf(d, &v, &mut stroke_art) + Ok(effects::expand_leaf(d, &v, &mut stroke_art)) } else { // Type, images, symbol instances, live objects (and paths whose Transform effect copies // them, each copy an object of its own, or changes their fills and strokes): through @@ -1144,13 +1470,27 @@ 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| { - 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); - 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, raster); + expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art, raster)?; + Ok(m) + }) + .transpose() }; + let Ok(m) = m else { + leave(d, out, raster); + return None; + }; + // A 3D effect's shadow blurred by the light's Softness keeps its blur in the art: it + // expands in turn, to an image. + 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); @@ -1169,6 +1509,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() { @@ -1181,7 +1522,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; } @@ -1221,12 +1562,33 @@ fn holds_plugin_effect(d: &Document, n: &Node, in_art: bool, seen: &mut std::col } fn expand_appearance(s: &mut Session, p: &Value) -> Result { - let roots = appearance_targets(s, p)?; + let roots = edit_targets(s, p, "effect.expandAppearance")?; // In Safe Mode a plug-in effect draws nothing: expanding it would drop the effect and keep the // geometry it hasn't changed. if vectorcraft_plugins::safe_mode::active() { - // A dimension selected with the art it measures is left as it is. - let d = &*super::dimension::without_kept(&s.doc()?.doc, &roots); + // 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, 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 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 { + // Art already gone (inside other art removed) needs nothing more. + let _ = view.remove(id); + } + } + let d = &*d; let mut seen = std::collections::HashSet::new(); if roots.iter().filter_map(|id| d.node(*id)).any(|n| holds_plugin_effect(d, n, false, &mut seen)) { return Err(EngineError::Other("Expand Appearance: a plug-in effect in the selection can't be expanded in Safe Mode".into())); @@ -1234,8 +1596,13 @@ 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 + // own effect turns it into other art as a whole (a blur, feather or inner glow makes it an image) takes its + // art into that art, which draws it, so that art has no place to go back to. + let designs = super::appearance::design_art_in(d, &roots); // A dimension selected with the art it measures keeps its own lines and label: it is out // of the document while the art expands. let lifted = super::dimension::lift(d, &roots); @@ -1245,7 +1612,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); + 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. @@ -1254,6 +1621,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))?; @@ -1261,8 +1631,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/graphics.rs b/crates/engine/src/cmd/effectcmd/graphics.rs index 9f4b89d2f4..e80c1b2d36 100644 --- a/crates/engine/src/cmd/effectcmd/graphics.rs +++ b/crates/engine/src/cmd/effectcmd/graphics.rs @@ -95,7 +95,7 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result { effect_targets(s, p, item, index, C)? } else { let mut out = vec![]; - for id in edit_targets(s, p)? { + for id in edit_targets(s, p, C)? { let (item, index) = d.node(id).and_then(first_three_d).ok_or_else(|| bad(C, format!("object {} needs a 3D effect", id.0)))?; out.push((id, item, index)); } diff --git a/crates/engine/src/cmd/effectcmd/tests.rs b/crates/engine/src/cmd/effectcmd/tests.rs index 306aaa4797..685261d340 100644 --- a/crates/engine/src/cmd/effectcmd/tests.rs +++ b/crates/engine/src/cmd/effectcmd/tests.rs @@ -1016,3 +1016,263 @@ 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] +fn radial_blur_center_is_stored_drawn_and_checked() { + let (mut s, id) = session_with_rect(); + let draw = |s: &Session| { + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels + }; + s.execute("effect.apply", &json!({"effect": "blur.radial", "params": {"amount": 40}})).unwrap(); + assert_eq!(node(&s, id).appearance.effects[0].params["centerX"], json!(0.5), "the default center is stored"); + let middle = draw(&s); + s.execute("effect.setParams", &json!({"index": 0, "params": {"centerX": 0.5, "centerY": 0.5}})).unwrap(); + assert_eq!(draw(&s), middle, "the default center draws as before"); + s.execute("effect.setParams", &json!({"index": 0, "params": {"centerX": 0, "centerY": 1}})).unwrap(); + let params = node(&s, id).appearance.effects[0].params.clone(); + assert_eq!((params["centerX"].clone(), params["centerY"].clone()), (json!(0), json!(1))); + let corner = draw(&s); + assert_ne!(corner, middle, "the blur turns about the bottom-left corner"); + let undo = s.doc().unwrap().history.undo.len(); + for (cmd, params) in [ + ("effect.setParams", json!({"index": 0, "params": {"centerX": 1.5}})), + ("effect.setParams", json!({"index": 0, "params": {"centerY": -0.01}})), + ("effect.setParams", json!({"index": 0, "params": {"centerX": "0.5"}})), + ("effect.apply", json!({"effect": "blur.radial", "params": {"centerY": 2}})), + ] { + let e = s.execute(cmd, ¶ms).unwrap_err().to_string(); + assert!(e.contains("must be a number"), "{cmd} {params}: {e}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{cmd} {params}"); + assert_eq!(node(&s, id).appearance.effects.len(), 1, "{cmd} {params}"); + assert_eq!(draw(&s), corner, "{cmd} {params}"); + } + // A replayed journal is checked too: the refusal is the command's own. + let e = s.replay("effect.setParams", &json!({"index": 0, "params": {"centerX": 7}})).unwrap_err().to_string(); + assert!(e.contains("`centerX` must be a number from 0 to 1"), "{e}"); + // Moving the object moves the blur with it. + s.execute("object.move", &json!({"ids": [id.0], "dx": 40, "dy": 20})).unwrap(); + let moved = draw(&s); + let at = |px: &[u8], x: usize, y: usize| px[(y * 300 + x) * 4..][..4].to_vec(); + for (x, y) in [(95, 150), (150, 205), (205, 95), (120, 120)] { + assert_eq!(at(&moved, x + 40, y + 20), at(&corner, x, y), "({x}, {y})"); + } +} + +/// A Rasterize with transparent room around the art, before another Rasterize, splits the stack, +/// and the part after the split paints around content the room spreads. The Blur Center still +/// lies in the object's own bounds, so the blur draws as it does without the room. +#[test] +fn radial_blur_center_stays_in_the_object_when_the_stack_splits() { + let draw = |room: bool| { + let (mut s, _) = session_with_rect(); + let mut stack = vec![("rasterize", json!({})), ("blur.radial", json!({"amount": 60, "centerX": 0, "centerY": 0}))]; + if room { + stack.insert(0, ("rasterize", json!({"addAround": 40}))); + } + for (effect, params) in stack { + s.execute("effect.apply", &json!({"effect": effect, "params": params})).unwrap(); + } + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels + }; + let (plain, split) = (draw(false), draw(true)); + let alpha = |px: &[u8]| px.iter().skip(3).step_by(4).map(|a| u64::from(*a)).sum::(); + assert!(alpha(&plain) > 0, "the blurred art draws"); + 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"); +} + +/// A group whose Transform effect's copies each carry the drop shadow listed before it, with a +/// symbol instance whose random Transform effect takes its seed from the instance's id, stays as it +/// is when the raster budget has no image left for a copy's shadow, with none left or with one for +/// the first copy's: the copies keep the ids their random moves are drawn with, the group draws as +/// before, and the document holds no image the first copy's expansion made, nor the budget its +/// charge. +#[test] +fn copies_the_raster_budget_leaves_keep_their_random_moves() { + let (mut s, id) = session_with_rect(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let id = NodeId(s.execute("symbol.new", &json!({"name": "Box"})).unwrap()["id"].as_u64().unwrap()); + let random = json!({"moveH": 40, "moveV": 40, "random": true}); + s.execute("effect.apply", &json!({"ids": [id.0], "effect": "distort.transform", "params": random})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let shadow = json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"}); + s.execute("effect.apply", &json!({"ids": [g.0], "effect": "stylize.dropShadow", "params": shadow})).unwrap(); + s.execute("effect.apply", &json!({"ids": [g.0], "effect": "distort.transform", "params": {"moveV": 150, "copies": 1}})).unwrap(); + let draw = |d: &vectorcraft_doc::Document| { + vectorcraft_render::Renderer::new().render(d, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels + }; + for images in [0, 1] { + let mut d = s.doc().unwrap().doc.as_ref().clone(); + let before = d.node(g).cloned().unwrap(); + assert!(effects::outer_effects(&before).len() < before.appearance.effects.len(), "each copy carries the shadow"); + let (drawn, keys) = (draw(&d), d.images.keys().cloned().collect::>()); + + let mut budget = super::RasterBudget { images, pixels: u64::MAX, left: 0 }; + let mut out = vec![]; + super::expand_node(&mut d, g, &[], &mut out, &mut budget); + assert!(budget.left > 0, "{images}: a copy's shadow is left"); + assert!(out.is_empty(), "{images}: nothing expands: {out:?}"); + assert_eq!(d.node(g), Some(&before), "{images}: the group stays as it is"); + assert!(draw(&d) == drawn, "{images}: the group draws as before"); + assert_eq!(d.images.keys().cloned().collect::>(), keys, "{images}: no image is added"); + assert_eq!((budget.images, budget.pixels), (images, u64::MAX), "{images}: the budget gets back what the copies took"); + } +} + +/// A group whose Transform effect copies its symbol instance, which has a drop shadow and a random +/// Transform effect that takes its seed from the instance's id: each copy's instance has that id. +/// When the raster budget has no image left for a copy's shadow, with none left or with one for the +/// first copy's, the group stays as it is: the copies keep the ids their random moves are drawn +/// with, the group draws as before, and the document holds no image the first copy's expansion +/// made, nor the budget its charge. With the whole budget, the group expands and each object gets +/// an id of its own. +#[test] +fn a_member_the_raster_budget_leaves_keeps_its_random_move() { + let (mut s, id) = session_with_rect(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let id = NodeId(s.execute("symbol.new", &json!({"name": "Box"})).unwrap()["id"].as_u64().unwrap()); + let shadow = json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"}); + s.execute("effect.apply", &json!({"ids": [id.0], "effect": "stylize.dropShadow", "params": shadow})).unwrap(); + let random = json!({"moveH": 40, "moveV": 40, "random": true}); + s.execute("effect.apply", &json!({"ids": [id.0], "effect": "distort.transform", "params": random})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("effect.apply", &json!({"ids": [g.0], "effect": "distort.transform", "params": {"moveV": 150, "copies": 1}})).unwrap(); + let draw = |d: &vectorcraft_doc::Document| { + vectorcraft_render::Renderer::new().render(d, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels + }; + for images in [0, 1, 1_024] { + let mut d = s.doc().unwrap().doc.as_ref().clone(); + let before = d.node(g).cloned().unwrap(); + assert!(effects::outer_effects(&before).len() == before.appearance.effects.len(), "the copies carry no shadow of the group's"); + let art = effects::evaluate_container(Some(&d), &before).unwrap(); + let mut instances = 0; + art.walk(&mut |n| instances += usize::from(n.id == id && super::has_seeded(n))); + assert!(instances >= 2, "{images}: each copy's instance has the id and its random effect: {instances}"); + let (drawn, keys) = (draw(&d), d.images.keys().cloned().collect::>()); + + let mut budget = super::RasterBudget { images, pixels: u64::MAX, left: 0 }; + let mut out = vec![]; + super::expand_node(&mut d, g, &[], &mut out, &mut budget); + if images < 2 { + assert!(budget.left > 0, "{images}: a shadow is left"); + assert!(out.is_empty(), "{images}: nothing expands: {out:?}"); + assert_eq!(d.node(g), Some(&before), "{images}: the group stays as it is"); + assert!(draw(&d) == drawn, "{images}: the group draws as before"); + assert_eq!(d.images.keys().cloned().collect::>(), keys, "{images}: no image is added"); + assert_eq!((budget.images, budget.pixels), (images, u64::MAX), "{images}: the budget gets back what the copies took"); + } else { + assert_eq!(budget.left, 0, "no shadow is left"); + assert!(!out.is_empty(), "the group expands"); + let (mut ids, mut count, mut seeded) = (std::collections::HashSet::new(), 0, false); + d.node(g).unwrap().walk(&mut |n| { + ids.insert(n.id); + count += 1; + seeded |= super::has_seeded(n); + }); + assert_eq!(ids.len(), count, "each object has an id of its own"); + assert!(!seeded, "no random Transform effect is left"); + } + } +} + +/// An object with Crop Marks, a drop shadow and a random Transform effect that takes its seed from +/// the object's id stays as it is when the raster budget has no image left for its shadow: the +/// object keeps its id and its random move, and draws as before. +#[test] +fn crop_marks_the_raster_budget_leaves_keep_their_random_move() { + let (mut s, id) = session_with_rect(); + let shadow = json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"}); + s.execute("effect.apply", &json!({"ids": [id.0], "effect": "stylize.dropShadow", "params": shadow})).unwrap(); + let random = json!({"moveH": 40, "moveV": 40, "random": true}); + s.execute("effect.apply", &json!({"ids": [id.0], "effect": "distort.transform", "params": random})).unwrap(); + s.execute("effect.apply", &json!({"ids": [id.0], "effect": "cropMarks", "params": {}})).unwrap(); + let draw = |d: &vectorcraft_doc::Document| { + vectorcraft_render::Renderer::new().render(d, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels + }; + let mut d = s.doc().unwrap().doc.as_ref().clone(); + let before = d.node(id).cloned().unwrap(); + assert!(effects::crop_marks_art(&before).is_some(), "the object has crop marks"); + let (drawn, keys) = (draw(&d), d.images.keys().cloned().collect::>()); + + let mut budget = super::RasterBudget { images: 0, pixels: u64::MAX, left: 0 }; + let mut out = vec![]; + super::expand_node(&mut d, id, &[], &mut out, &mut budget); + assert!(budget.left > 0, "the shadow is left"); + assert!(out.is_empty(), "nothing expands: {out:?}"); + assert_eq!(d.node(id), Some(&before), "the object stays as it is"); + assert!(draw(&d) == drawn, "the object draws as before"); + assert_eq!(d.images.keys().cloned().collect::>(), keys, "no image is added"); + assert_eq!((budget.images, budget.pixels), (0, u64::MAX), "the budget is as it was"); +} diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index 02dbad5d23..a17a02ed15 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -265,25 +265,30 @@ 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, has one ([`gradient_expands`] on that path's own box). Inline -/// graphics and color glyphs become other art. Leaves the document as it is and stops at the -/// first such path. +/// 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(|r| &r.style); - if !matches!(style.map_or_else(|| t.first_style().fill, |s| s.fill.clone()), Paint::Gradient(_)) { + let style = t.runs.get(run).map_or(&first, |r| &r.style); + if !gradient(style) { return false; } - let path = PathData::from_bezpath(outline).transformed(t.xf); + let path = PathData::from_bezpath(outline); if path.is_empty() { return false; } - let appearance = style.map_or_else(|| t.first_style().appearance(), |s| s.appearance()); - gradient_expands(d, &Node::path(NodeId(u64::MAX), path, appearance)) + let mut piece = Node::path(NodeId(u64::MAX), path, Appearance::default()); + 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 9a59d0f2f8..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)), @@ -146,7 +454,11 @@ fn text(k: &str, v: &Value, multiline: bool) -> Result { return Err(bad(C, format!("{k} is too long (at most {MAX_TEXT} characters)"))); } if s.chars().any(|c| c.is_control() && !(multiline && matches!(c, '\n' | '\r' | '\t'))) { - return Err(bad(C, format!("{k} has control characters{}", if multiline { "" } else { " or line breaks" }))); + return Err(if multiline { + bad(C, format!("{k} has control characters")) + } else { + bad(C, format!("{k} has control characters or line breaks")) + }); } Ok(s.to_string()) } diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 1ff1897c85..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, size_note}; +pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, png_clip, size_note}; mod heifread; mod hpgl; mod jp2read; @@ -54,6 +54,7 @@ pub mod ppi; pub mod progress; mod psdlayers; pub mod psdread; +mod psdslices; mod pxrread; mod save; mod screens; @@ -66,11 +67,14 @@ use serde_json::{Value, json}; pub use action_batch::batch_overwrites_one_file; pub use dxf::{UNSUPPORTED, Unsupported, unsupported}; -pub use encode::{ARTBOARD_PARAMS, ArtboardPick, Encoded, Note, NoteKind, encode, encode_all, encode_with_notes, encode_with_warnings, note_texts}; +pub use encode::{ + ARTBOARD_PARAMS, ArtboardPick, Encoded, Note, NoteKind, encode, encode_all, encode_with_notes, encode_with_warnings, export_art_bounds, + note_texts, +}; pub(crate) use encode::{anti_alias, background, with_single_artboard}; pub(crate) use export::with_artboard_fills; pub(crate) use export::{EXPORT_PARAMS, export_crop, isolated}; -pub use export::{export_doc, export_source, unused_option_notes}; +pub use export::{export_doc, export_source, selection_doc, unused_option_notes}; use load::err; pub(crate) use load::import_svg; pub(crate) use load::is_placeholder; @@ -88,7 +92,11 @@ pub(crate) use mesh3d::{mesh_file_names, mesh_files}; pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, render as render_file_name}; pub(crate) use native::preview_png; pub use native::with_compression_pref; +pub(crate) use pdfimport::opened_page_document; pub use pdfimport::{LoadOptions, page_document}; +pub(crate) use psdlayers::import_active as psd_layers; +pub use psdlayers::{PsdInfo, info as psd_info}; +pub(crate) use psdslices::over as psd_slices; pub(crate) use save::job_for; pub(crate) use save::save as save_document; pub use save::{ @@ -123,7 +131,8 @@ mod formats; #[cfg(not(target_arch = "wasm32"))] pub(crate) use access::list_dir; -pub use access::{check_linked_scripts, write_file_with, write_save_file, write_save_file_with}; +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")))] mod tests_readonly; @@ -235,6 +244,8 @@ mod tests_psd; mod tests_psdlayers; #[cfg(test)] mod tests_psdread; +#[cfg(test)] +mod tests_psdslices; #[cfg(test)] mod tests_heifread; diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 203a2262b0..9d2d9a4a33 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -121,20 +121,103 @@ 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 `