diff --git a/Cargo.lock b/Cargo.lock index 7492a7ccb5..520647b95d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1239,7 +1239,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-automation", "craft-behavior", @@ -1280,7 +1280,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "crc32fast", "flate2", @@ -1291,7 +1291,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -1302,7 +1302,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "rustix 1.1.6", ] @@ -1310,7 +1310,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1335,7 +1335,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1353,7 +1353,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-docpath", @@ -1371,7 +1371,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "crc32fast", "flate2", @@ -1380,7 +1380,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "egui", ] @@ -1388,7 +1388,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "md-5", "rayon", @@ -1397,12 +1397,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-cms", @@ -1422,11 +1422,10 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-control-protocol", "craft-platform", - "getrandom 0.3.4", "serde", "serde_json", ] @@ -1434,8 +1433,9 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ + "getrandom 0.3.4", "serde_json", "subtle", ] @@ -1443,7 +1443,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "rayon", ] @@ -1451,7 +1451,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1477,7 +1477,7 @@ dependencies = [ [[package]] name = "craft-doc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "blake3", "craft-ecproj-format", @@ -1493,7 +1493,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "serde", ] @@ -1501,7 +1501,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1520,7 +1520,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-codepage", "encoding_rs", @@ -1532,7 +1532,7 @@ dependencies = [ [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "serde", "serde_json", @@ -1542,12 +1542,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1562,7 +1562,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1581,7 +1581,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1590,7 +1590,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "cap-primitives", "craft-atomic", @@ -1613,12 +1613,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "gif", ] @@ -1626,7 +1626,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "flate2", ] @@ -1634,7 +1634,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1647,7 +1647,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "chrono", "fixed_decimal", @@ -1675,7 +1675,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-dds", "craft-jpeg", @@ -1702,7 +1702,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1720,7 +1720,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "thiserror 2.0.21", ] @@ -1728,7 +1728,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1739,7 +1739,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-host", "craft-i18n", @@ -1754,7 +1754,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-i18n", @@ -1768,7 +1768,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-host", @@ -1786,7 +1786,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1798,7 +1798,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "encoding_rs", "image", @@ -1809,7 +1809,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "chrono", "craft-codepage", @@ -1819,7 +1819,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-keymap", @@ -1835,7 +1835,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "flate2", "serde", @@ -1846,7 +1846,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1858,7 +1858,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "async-channel", "async-io", @@ -1889,7 +1889,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1898,7 +1898,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-host", @@ -1922,7 +1922,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1933,7 +1933,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-eps", "flate2", @@ -1947,7 +1947,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "encoding_rs", "flate2", @@ -1958,7 +1958,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "dispatch2", "egui", @@ -1971,7 +1971,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1990,7 +1990,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-atomic", "craft-host", @@ -2007,7 +2007,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "fax", "hayro-ccitt", @@ -2018,7 +2018,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2039,7 +2039,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-keymap", @@ -2051,7 +2051,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2076,7 +2076,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2091,7 +2091,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-atomic", "craft-behavior", @@ -2106,7 +2106,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "serde", "thiserror 2.0.21", @@ -2116,7 +2116,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "serde", "thiserror 2.0.21", @@ -2125,7 +2125,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-keymap", @@ -2140,12 +2140,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2159,7 +2159,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-i18n", @@ -2175,7 +2175,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "accesskit", "craft-behavior", @@ -2213,7 +2213,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2224,7 +2224,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-host", @@ -2242,7 +2242,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-host", @@ -2263,7 +2263,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-host", @@ -2284,7 +2284,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-behavior", "craft-host", @@ -2303,7 +2303,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "base64 0.22.1", "chrono", @@ -2335,7 +2335,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "flate2", "serde", @@ -2346,7 +2346,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2356,7 +2356,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "js-sys", "serde_json", @@ -2367,7 +2367,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "winsafe", ] @@ -2375,7 +2375,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "craft-appkit", "craft-atomic", @@ -2407,7 +2407,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "quick-xml 0.41.0", "serde", @@ -3762,7 +3762,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "brotli", "hayro-postscript", @@ -3771,7 +3771,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3789,7 +3789,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3807,12 +3807,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "flate2", "hayro-ccitt", @@ -4795,7 +4795,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4952,7 +4952,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" dependencies = [ "arrayvec", "kurbo 0.13.1", diff --git a/Cargo.toml b/Cargo.toml index 242abcfe87..a0fb986dcc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,46 +11,46 @@ rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } # 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 = "51fcc3b0413af193db952df28dffae2321745703" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } # The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names # the members it imports. -craft = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } # Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui # without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes. -craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -193,13 +193,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index a9a1013520..e8b56c29a9 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -27,7 +27,7 @@ log = { workspace = true } # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/crates/effects/src/group/tests.rs b/crates/effects/src/group/tests.rs index b3fa27aee1..0efaffafeb 100644 --- a/crates/effects/src/group/tests.rs +++ b/crates/effects/src/group/tests.rs @@ -1780,6 +1780,44 @@ fn perspective_projects_the_masks_in_a_symbols_art() { assert_eq!(mask, path, "and so is its mask"); } +/// The images in the art of a symbol instance drawn through a projection have their corners where +/// the projection takes them, beside a path, in a group and in the art of a linked mask, and an +/// image's own linked mask is projected with it. +#[test] +fn a_projection_puts_the_corners_of_the_images_in_a_symbols_art_where_it_takes_them() { + let masked = masked_by(white_square(22), image_node(23), true); + let art = Node::group(NodeId(20), vec![Arc::new(image_node(21)), Arc::new(Node::group(NodeId(24), vec![Arc::new(masked)]))]); + // An image with a linked mask of its own, whose path has a linked mask too. + let inner = masked_by(white_square(32), white_square(33), true); + let own = Node::group(NodeId(30), vec![Arc::new(masked_by(image_node(31), inner, true))]); + let at = vectorcraft_doc::PerspectiveAttachment { projection: Some([1.0, 0.2, 3.0, 0.1, 1.0, 2.0, 0.01, 0.02, 1.0]), ..Default::default() }; + let h = at.homography().unwrap(); + let mut instance = Node::new(NodeId(2), NodeKind::SymbolInstance { symbol: "t".into(), xf: vectorcraft_geom::Affine::IDENTITY }); + instance.extras_mut().perspective = Some(Box::new(at.clone())); + let out = crate::reshape::reshape(None, &instance, Some(&own)).unwrap(); + let mut masks = vec![]; + out.walk(&mut |c| masks.extend(c.image_corners().and(c.extras().mask.as_deref()).map(|m| m.art.clone()))); + let [mask] = masks.as_slice() else { panic!("one masked image: {out:?}") }; + assert!(mask.path_data() != white_square(32).path_data(), "the image's mask is projected"); + let inner = mask.extras().mask.as_deref().map(|m| m.art.path_data().cloned()); + assert_eq!(inner, Some(mask.path_data().cloned()), "and so is the mask on that mask's path"); + let mut instance = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "s".into(), xf: vectorcraft_geom::Affine::IDENTITY }); + instance.extras_mut().perspective = Some(Box::new(at)); + let out = crate::reshape::reshape(None, &instance, Some(&art)).unwrap(); + let want = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].map(|(x, y)| h.apply(vectorcraft_geom::Point::new(x, y)).unwrap()); + let mut images = vec![]; + out.walk(&mut |c| { + images.extend(c.image_corners()); + images.extend(c.extras().mask.as_deref().and_then(|m| m.art.image_corners())); + }); + assert_eq!(images.len(), 2, "{out:?}"); + for q in images { + for (got, want) in q.iter().zip(want) { + assert!(got.distance(want) < 1e-9, "{q:?} against {want:?}"); + } + } +} + /// A group with `effect` holding `n` vertical then `n` horizontal bars, 2 wide on a 4-unit /// pitch, each crossing every bar of the other direction: n² crossings. fn crossing_bars(n: usize, effect: &str) -> Node { diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 4d1c7b420f..82fcc1fd9d 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -1544,11 +1544,40 @@ pub(crate) fn own_effects_art(doc: Option<&Document>, n: &Node) -> Option /// follow it. The type and live objects in the art of those masks are outlined and evaluated /// first ([`outlined_members`], with the symbols of `doc`). fn project_leaves(art: &mut Node, h: &vectorcraft_geom::Homography, doc: Option<&Document>) { + project_art(art, h, doc, false); +} + +/// [`project_leaves`], the linked opacity mask of `art` itself included when `own`. +fn project_art(art: &mut Node, h: &vectorcraft_geom::Homography, doc: Option<&Document>, own: bool) { project_paths(art, h); - each_linked_mask_mut(art, false, 0, &mut |m| { + each_linked_mask_mut(art, own, 0, &mut |m| { *m = outlined_mask_art(doc, m); project_paths(m, h); + project_image_masks(m, h, doc); }); + project_image_masks(art, h, doc); +} + +/// The art of the linked opacity masks of the images under `art` (`art` itself, and in groups and +/// layers, as [`project_images`] reaches them) projected through `h` as [`project_leaves`] +/// projects art, the linked mask of that art's own root included, so that each mask stays on the +/// object it masks. Unlinked masks stay where they are. +fn project_image_masks(art: &mut Node, h: &vectorcraft_geom::Homography, doc: Option<&Document>) { + match &mut art.kind { + NodeKind::Image(_) => { + if let Some(m) = art.extras_if_any().and_then(|e| e.mask.as_mut()).filter(|m| m.linked) { + let a = Arc::make_mut(&mut m.art); + *a = outlined_mask_art(doc, a); + project_art(a, h, doc, true); + } + } + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => { + for c in children.iter_mut() { + project_image_masks(Arc::make_mut(c), h, doc); + } + } + _ => {} + } } /// `art`, the art of an opacity mask, with type and live objects in it outlined and evaluated @@ -1584,6 +1613,27 @@ fn project_paths(art: &mut Node, h: &vectorcraft_geom::Homography) { _ => {} } }); + project_images(art, h); +} + +/// Place the corners of every image under `art` (in groups and layers, as [`for_each_leaf`] reaches +/// paths) where the projective map `h` takes them, so that its pixels are drawn in perspective +/// between them ([`Node::set_image_corners`]). An image with a corner that `h` sends past its +/// horizon keeps its place, as the points of a path there do. +fn project_images(n: &mut Node, h: &vectorcraft_geom::Homography) { + match &mut n.kind { + NodeKind::Image(_) => { + if let Some([Some(a), Some(b), Some(c), Some(d)]) = n.image_corners().map(|q| q.map(|p| h.apply(p))) { + let _ = n.set_image_corners([a, b, c, d]); + } + } + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => { + for c in children.iter_mut() { + project_images(Arc::make_mut(c), h); + } + } + _ => {} + } } /// The visible geometry effects of `n`'s own effect list, in order. diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index ea5d72f7ef..ef1608a5d9 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -1180,8 +1180,11 @@ impl Placed { } } -/// The most pairs of faces [`local_order`] compares, and the most [`cut_stroke_faces`] compares; -/// the pairs they have not reached by then keep the order of their depths. +/// The most pairs of faces [`local_order`] compares, together with the steps it takes to break +/// rings of them ([`drawn_in_pairs_order`]), and the most pairs [`cut_stroke_faces`] compares. A +/// pair not compared by then adds no constraint on the order (the pairs that were compared can +/// still move its faces), and once the steps run out the first face left by depth goes next only +/// when no face can. const MAX_LOCAL_CHECKS: usize = 4_000_000; /// The polygon of `f` and the sign of its turns, when `f` is a face turned toward the viewer other @@ -1412,11 +1415,11 @@ fn half(p: &[Point], values: &[f64], sign: f64) -> Vec { /// their depths where they overlap: the face nearer the viewer there goes after the other. A fill /// wall and a face of the same shape's covering stroke ([`Paints::Stroke`]) keep their order. Each /// face otherwise keeps its place in `order`, so a fill wall in the gap between two dashes stays -/// where its depth puts it. A cycle of such pairs is broken at the face that comes first in `order`. +/// where its depth puts it. A cycle of such pairs is broken at one of its own faces +/// ([`drawn_in_pairs_order`]). /// A face drawn last (a planar end turned toward the viewer, at depth `f64::MAX`) keeps its place: /// no face moves across it. Otherwise `order` as it is. fn local_order(faces: &[Placed], order: Vec) -> Vec { - use std::cmp::Reverse; // The faces of each shape that take part, from left to right for a sweep along x. let mut shapes: Vec> = vec![]; for (k, f) in faces.iter().enumerate() { @@ -1428,7 +1431,7 @@ fn local_order(faces: &[Placed], order: Vec) -> Vec { } shapes[f.member].push(k); } - if !shapes.iter().any(|list| list.iter().any(|&k| faces[k].paints != Paints::Fill)) { + if !shapes.iter().any(|list| list.iter().any(|&k| faces[k].paints != Paints::Fill)) || u32::try_from(faces.len()).is_err() { return order; } for list in &mut shapes { @@ -1471,9 +1474,9 @@ fn local_order(faces: &[Placed], order: Vec) -> Vec { // faces with a polygon and a plane that overlap goes in the order of their depths there. let mut sweep: Vec = (0..faces.len()).filter(|&k| faces[k].outline.len() >= 3 && faces[k].plane.is_some()).collect(); sweep.sort_by(|&a, &b| faces[a].bounds.x0.total_cmp(&faces[b].bounds.x0)); - // For each face, the faces drawn after it, and for each, how many go before it. - let mut after: Vec> = vec![vec![]; faces.len()]; - let mut waits = vec![0usize; faces.len()]; + // Each pair in its order: a face, and a face drawn after it (as `u32`: there are fewer faces + // than that, which is checked above). + let mut pairs: Vec<(u32, u32)> = vec![]; 'pairs: for (i, &k) in sweep.iter().enumerate() { let a = &faces[k]; for &j in sweep.iter().skip(i + 1).take_while(|&&j| faces[j].bounds.x0 < a.bounds.x1) { @@ -1491,38 +1494,117 @@ fn local_order(faces: &[Placed], order: Vec) -> Vec { let Some(a_nearer) = nearer_where_overlapping(a, b) else { continue }; a_nearer }; - let (back, front) = if a_later { (j, k) } else { (k, j) }; - after[back].push(front); - waits[front] += 1; + pairs.push(if a_later { (j as u32, k as u32) } else { (k as u32, j as u32) }); } } - // Each step draws the face that comes first in `order` of those whose faces before are drawn. + // Breaking rings has what is left of the limit. + let last: Vec = faces.iter().map(|f| f.depth >= f64::MAX).collect(); + let mut room = MAX_LOCAL_CHECKS.saturating_sub(checks); + drawn_in_pairs_order(order, &position, &last, pairs, &mut room) +} + +/// `order` with each face after the faces that go before it: each of `pairs` is a face and a face +/// drawn after it, `position` is each face's place in `order`, and `last` says of each face +/// whether it is drawn last. Each step draws the face that comes first in `order` of those whose +/// faces before are drawn. A face drawn last goes only after every face before it in `order`, so +/// a face before it never waits for it or for a face after it: those pairs, with the face drawn +/// last itself or with a face that follows it, are drawn the wrong way round. +/// +/// When no face can go next, some of the faces left go before each other in a ring, or wait for a +/// face drawn last or one that follows it. The faces that go before the first face left in `order` +/// are followed back, among the faces that come before the next face drawn last, to the first +/// group found that waits for no other of them ([`RingFinder::behind`]): a ring, or one face. That +/// group gives up its face that comes first in `order`. So when the first face left is in the +/// group, it goes next, as it would with no ring looked for; when it only waits for the group, a +/// face of the group goes instead, and the only other pairs drawn the wrong way round are pairs of +/// a ring. +/// +/// Every face and pair looked at takes one from `room`. The search is kept from one stop to the +/// next and goes on from where it stopped, and a face that is drawn is dropped from a list the +/// next time the list is looked at, so rings of a few faces take a few steps a face whether they +/// stand apart, all lie behind one face or lie one behind the other. Two costs are not in +/// proportion to the faces. A ring that is still a ring after it gives up a face is walked again +/// from the face the search reached it by, so a large ring can cost about its pairs for each face +/// it gives up: the square of its faces, even when each waits for few others (3,200 faces with +/// four pairs each at random take about 3,000,000 steps). And a face at or +/// after the next face drawn last is passed over again each time a face that waits for it is +/// looked at. Once `room` runs out the first face left in `order` goes next, ring or not. +/// A first face left that waits only for the next face drawn last or faces after it goes next +/// with no search, at no cost. +/// +/// An `order` and `position` that do not agree, or a pair of a face that is not in them, give +/// `order` back. +/// +/// The pairs come at 8 bytes each and are dropped once the lists of the faces after each face +/// are made, 4 bytes a pair; the lists of the faces before each face, as many again, are made +/// when a ring is first looked for, a step a pair not taken from `room`, and only when the room +/// left is at least a quarter of the pairs: with less, no ring is looked for and the first face +/// left goes next. So a solid whose comparing of pairs leaves less than a quarter of its pairs +/// of the limit breaks its rings as before rings were looked for. +fn drawn_in_pairs_order(order: Vec, position: &[usize], last: &[bool], pairs: Vec<(u32, u32)>, room: &mut usize) -> Vec { + use std::cmp::Reverse; + let n = order.len(); + // `order` holds each face once when each face's place in it is the place `position` gives. + let agree = position.len() == n && last.len() == n && order.iter().enumerate().all(|(at, &k)| position.get(k) == Some(&at)); + if !agree || u32::try_from(pairs.len()).is_err() || pairs.iter().any(|&(back, front)| back as usize >= n || front as usize >= n) { + return order; + } + // For each face, how many faces not drawn yet go before it, and the faces drawn after it. + let mut waits = vec![0usize; n]; + for &(_, front) in &pairs { + waits[front as usize] += 1; + } + let after = Lists::from_pairs(n, pairs.iter().map(|&(back, front)| (back as usize, front as usize))); + drop(pairs); let mut ready: std::collections::BinaryHeap> = - (0..faces.len()).filter(|&k| waits[k] == 0).map(|k| Reverse((position[k], k))).collect(); + (0..n).filter(|&k| waits[k] == 0).map(|k| Reverse((position[k], k))).collect(); // The faces drawn last, in `order`: each goes only after every face before it in `order`. - let last: Vec = order.iter().copied().filter(|&k| faces[k].depth >= f64::MAX).collect(); + let lasts: Vec = order.iter().copied().filter(|&k| last[k]).collect(); let mut next_last = 0usize; - let mut drawn = vec![false; faces.len()]; - let mut out = Vec::with_capacity(order.len()); + let mut drawn = vec![false; n]; + let mut out = Vec::with_capacity(n); let mut first = 0usize; - while out.len() < order.len() { - while last.get(next_last).is_some_and(|&k| drawn[k]) { + let mut rings: Option = None; + // For each face, how many faces not drawn yet go before it among the first `counted` of + // `order`, which keeps up with the next face drawn last. + let mut early = vec![0u32; n]; + let mut counted = 0usize; + while out.len() < n { + while lasts.get(next_last).is_some_and(|&k| drawn[k]) { next_last += 1; } - let limit = last.get(next_last).map_or(usize::MAX, |&k| position[k]); + let limit = lasts.get(next_last).map_or(usize::MAX, |&k| position[k]); + while counted < limit.min(n) { + if let Some(&back) = order.get(counted).filter(|&&back| !drawn[back]) { + for &j in after.list(back) { + early[j as usize] += 1; + } + } + counted += 1; + } let k = match ready.peek() { Some(&Reverse((at, k))) if at < limit => { ready.pop(); k } _ => { - // A cycle, or the faces left to draw before a face drawn last wait for faces after - // it: the first face in `order` not drawn yet goes next. while order.get(first).is_some_and(|&k| drawn[k]) { first += 1; } - let Some(&k) = order.get(first) else { break }; - k + let Some(&next) = order.get(first) else { break }; + // The face drawn last goes in its turn, and so does a face that waits only for it or + // faces after it: no face it waits for can go first. Any other face waits for a + // face before the face drawn last: the group behind it gives up a face, while there + // is room to look for one. The lists of the faces before each face take a step a + // pair to make, which is not taken from `room`: they are made only when the room + // left is at least a quarter of the pairs, so making them costs no more than four + // times the room left. + let mut released = None; + let room_for_lists = rings.is_some() || room.saturating_mul(4) >= after.faces.len(); + if *room > 0 && position[next] < limit && early[next] > 0 && room_for_lists { + released = rings.get_or_insert_with(|| RingFinder::new(&after)).behind(next, &drawn, position, limit, room); + } + released.unwrap_or(next) } }; if drawn[k] { @@ -1530,8 +1612,13 @@ fn local_order(faces: &[Placed], order: Vec) -> Vec { } drawn[k] = true; out.push(k); - for &j in &after[k] { + let was_counted = position[k] < counted; + for &j in after.list(k) { + let j = j as usize; waits[j] = waits[j].saturating_sub(1); + if was_counted { + early[j] = early[j].saturating_sub(1); + } if waits[j] == 0 && !drawn[j] { ready.push(Reverse((position[j], j))); } @@ -1540,6 +1627,217 @@ fn local_order(faces: &[Placed], order: Vec) -> Vec { out } +/// A list of faces for each of some faces, all in one array: the faces after each face, or the +/// faces before it. +struct Lists { + /// The list of face `k` is `faces[starts[k]..starts[k + 1]]`. + starts: Vec, + faces: Vec, +} + +impl Lists { + /// For each of `n` faces, the second faces of the `pairs` it is first in, in the order of + /// `pairs`. There are fewer than 2^32 faces and pairs ([`drawn_in_pairs_order`] checks this); + /// a pair with a face that is not one of the `n` is left out. + fn from_pairs(n: usize, pairs: impl Iterator + Clone) -> Self { + let pairs = pairs.filter(move |&(first, second)| first < n && second < n); + let mut starts = vec![0u32; n + 1]; + for (first, _) in pairs.clone() { + if let Some(count) = starts.get_mut(first + 1) { + *count += 1; + } + } + for k in 1..starts.len() { + starts[k] += starts[k - 1]; + } + let mut filled = starts.clone(); + let mut faces = vec![0u32; starts.last().map_or(0, |&end| end as usize)]; + for (first, second) in pairs { + if let Some(at) = filled.get_mut(first) { + if let Some(slot) = faces.get_mut(*at as usize) { + *slot = second as u32; + } + *at += 1; + } + } + Lists { starts, faces } + } + + /// The list of face `k`; none for a face that is not one of them. + fn list(&self, k: usize) -> &[u32] { + let (Some(&start), Some(&end)) = (self.starts.get(k), self.starts.get(k + 1)) else { return &[] }; + self.faces.get(start as usize..end as usize).unwrap_or_default() + } + + /// Each list's faces and the face it is the list of, as pairs. + fn pairs(&self) -> impl Iterator + Clone + '_ { + (0..self.starts.len().saturating_sub(1)).flat_map(move |k| self.list(k).iter().map(move |&j| (k, j as usize))) + } +} + +#[cfg(test)] +thread_local! { + /// The entries of the lists of faces before each face that [`RingFinder`] has read, counted + /// where they are read, for tests to hold the reading to the room. + pub(super) static LIST_ENTRIES_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// No place among the faces reached, in [`RingFinder`]. +const NONE: usize = usize::MAX; + +/// Finds the ring behind a face for [`drawn_in_pairs_order`], and keeps its search from one stop to +/// the next. +/// +/// Every index it holds is in range: the faces of its lists are faces of the pairs +/// [`drawn_in_pairs_order`] checked against the number of faces, which is the length of the +/// `drawn` and `position` it is given, and the places it keeps are places in its own lists. +struct RingFinder { + /// For each face, the faces that go before it, lowest first. + before: Lists, + /// For each face, where its list in `before` now ends: the faces found drawn are dropped + /// from it, and those left moved up. + ends: Vec, + /// For each face, its place in `reached`; [`NONE`] for a face not reached. + marks: Vec, + /// The faces reached, in the order reached. Every one is in a group not completed yet. + reached: Vec, + /// For each face reached, the earliest place in `reached` it leads back to. + low: Vec, + /// The path from the first face reached to the one being looked at. + path: Vec, + /// The `limit` the faces reached were reached under; `None` with none reached yet. + limit: Option, +} + +/// A face on the path of [`RingFinder`]: its place in `reached`, and the entry of its list being +/// looked at. +struct Step { + place: usize, + entry: usize, +} + +impl RingFinder { + /// A finder for the faces of `after`, the faces drawn after each face. + fn new(after: &Lists) -> Self { + let n = after.starts.len() - 1; + let before = Lists::from_pairs(n, after.pairs().map(|(back, front)| (front, back))); + let ends = before.starts.get(1..).unwrap_or_default().to_vec(); + RingFinder { before, ends, marks: vec![NONE; n], reached: vec![], low: vec![], path: vec![], limit: None } + } + + /// The face to draw next when `start`, the first face not `drawn`, whose `position` is before + /// `limit`, waits for a face. Of the faces that are not drawn and come before `limit`, those + /// that go before `start` are followed back to the first group found whose faces wait for no + /// other such face: a ring of faces that go before each other, or one face. The answer is the + /// face of that group with the lowest `position`. Every face and every pair looked at takes + /// one from `room`; `None` when it runs out. + /// + /// The faces are followed depth first, each face's faces before it lowest first, and the first + /// strongly connected component completed is the group (Tarjan's algorithm, stopped there): + /// it leads to no other component. The search is kept, less that group, and the next call + /// goes on with it: the faces drawn since are the group's own and faces that waited for + /// nothing else, and none of those is in a group with a face still on the path, so what the + /// search knows of the faces left still holds. It starts afresh when `limit` moves, which + /// brings in faces it passed over. + fn behind(&mut self, start: usize, drawn: &[bool], position: &[usize], limit: usize, room: &mut usize) -> Option { + if self.limit != Some(limit) { + self.forget(0); + self.limit = Some(limit); + } + // The end of the path may be drawn: faces that only waited for the last group. + while let Some(place) = self.path.last().map(|step| step.place).filter(|&place| drawn[self.reached[place]]) { + self.forget(place); + } + if self.reached.first() != Some(&start) { + self.forget(0); + if !self.reach(start, drawn, room) { + return None; + } + } + while let Some(step) = self.path.last_mut() { + if *room == 0 { + return None; + } + *room -= 1; + let place = step.place; + let face = self.reached[place]; + if step.entry < self.ends[face] as usize { + let earlier = self.before.faces[step.entry] as usize; + if drawn[earlier] || position[earlier] >= limit { + step.entry += 1; + } else if self.marks[earlier] != NONE { + self.low[place] = self.low[place].min(self.marks[earlier]); + step.entry += 1; + } else { + // The entry is passed once the faces behind it are looked at. + if !self.reach(earlier, drawn, room) { + return None; + } + } + continue; + } + // Every face before this one is looked at: it ends a group when it leads no further + // back than itself. + let leads = self.low[place]; + if leads == place { + let found = self.reached[place..].iter().copied().min_by_key(|&face| position[face]); + // The face before it on the path keeps its entry for this one, to look at what is + // left of the group next time. + self.forget(place); + return found; + } + self.path.pop(); + if let Some(parent) = self.path.last_mut() { + self.low[parent.place] = self.low[parent.place].min(leads); + parent.entry += 1; + } + } + None + } + + /// Adds `face` to the faces reached and to the end of the path, at the start of its list, with + /// the faces now `drawn` dropped from the list: a step from `room` for each face the list held, + /// taken before the list is read. `false`, with `room` emptied and nothing read, when the list + /// is longer than the room left. + fn reach(&mut self, face: usize, drawn: &[bool], room: &mut usize) -> bool { + let (start, end) = (self.before.starts[face] as usize, self.ends[face] as usize); + let Some(left) = room.checked_sub(end - start) else { + *room = 0; + return false; + }; + *room = left; + let mut kept = start; + for entry in start..end { + let earlier = self.before.faces[entry]; + #[cfg(test)] + LIST_ENTRIES_READ.with(|read| read.set(read.get() + 1)); + if !drawn[earlier as usize] { + self.before.faces[kept] = earlier; + kept += 1; + } + } + // `kept` is no more than the end it replaces. + self.ends[face] = kept as u32; + let place = self.reached.len(); + self.marks[face] = place; + self.path.push(Step { place, entry: start }); + self.low.push(place); + self.reached.push(face); + true + } + + /// Takes out the faces reached from `place` on, and their part of the path. + fn forget(&mut self, place: usize) { + for face in self.reached.drain(place.min(self.reached.len())..) { + self.marks[face] = NONE; + } + self.low.truncate(place); + while self.path.last().is_some_and(|step| step.place >= place) { + self.path.pop(); + } + } +} + /// Whether face `a` is nearer the viewer than face `b` where their polygons overlap on the drawing, /// measured at the middle of the overlap. `None` when they do not overlap, when either polygon is /// not convex, or when they are at the same depth there. @@ -1673,7 +1971,8 @@ fn draw_order(faces: &[Placed], sealed: bool) -> Vec { /// 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. +/// or a convex polygon can also move. Faces that lie in front of one another in a ring give up one +/// of the ring's own faces ([`drawn_in_pairs_order`]). Otherwise the order given. pub(crate) fn surface_order<'a>(faces: impl IntoIterator, f64)>) -> Vec { let placed: Vec = faces .into_iter() diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index f3054d85cf..49c301dd75 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -933,10 +933,10 @@ fn local_order_puts_overlapping_fill_walls_and_stroke_faces_in_depth_order() { } } -/// A cycle of overlapping stroke faces is broken at the face that comes first by depth, and a cap -/// drawn last stays after every wall: 0 at x 0 to 10, flat at z 0; 1 at x 4 to 14, z = x - 8; 2 at -/// x 8 to 18, flat at z 1. Where they overlap, 0 is nearer than 1, 1 nearer than 2 and 2 nearer -/// than 0. 3 is the cap. +/// A cycle of overlapping stroke faces is broken at its own face that comes first by depth, and a +/// cap drawn last stays after every wall: 0 at x 0 to 10, flat at z 0; 1 at x 4 to 14, z = x - 8; +/// 2 at x 8 to 18, flat at z 1. Where they overlap, 0 is nearer than 1, 1 nearer than 2 and 2 +/// nearer than 0. 3 is the cap. #[test] fn a_depth_cycle_keeps_the_cap_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)]; @@ -964,6 +964,450 @@ fn a_depth_cycle_keeps_the_cap_last() { assert_eq!(draw_order(&faces, true), [0, 2, 1, 3]); } +/// A face that lies in front of a face of a cycle, without being part of the cycle, waits for that +/// face. 0, 1 and 2 overlap in a cycle (as in `a_depth_cycle_keeps_the_cap_last`); 3, at x 16 to +/// 26 and flat at z 2, is nearer than 2 where they overlap, but its center is the farthest of all, +/// so it comes first by depth. The cycle is broken at 0, its first face by depth, and 3 follows 2. +/// Breaking it at the first face by depth of all the faces left drew 3 first, under 2. +#[test] +fn a_face_in_front_of_a_cycle_waits_for_it() { + 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)]; + let at = |depth: f64, x: f64, normal: [f64; 3], offset: f64| Placed { + depth, + side: true, + away: false, + bounds: Rect::new(x, 0.0, x + 10.0, 10.0), + member: 0, + paints: Paints::Other, + outline: square(x), + plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }), + }; + let flat = [0.0, 0.0, 1.0]; + let walls = || [at(1.0, 0.0, flat, 0.0), at(2.0, 4.0, [-1.0, 0.0, 1.0], -8.0), at(3.0, 8.0, flat, 1.0), at(-5.0, 16.0, flat, 2.0)]; + assert_eq!(draw_order(&walls(), true), [0, 2, 3, 1]); + // With the cap of `a_depth_cycle_keeps_the_cap_last` as well, it still goes last. + let cap = + Placed { depth: f64::MAX, side: false, bounds: Rect::new(0.0, 0.0, 26.0, 10.0), outline: vec![], plane: None, ..at(0.0, 0.0, flat, 0.0) }; + let capped: Vec = walls().into_iter().chain([cap]).collect(); + assert_eq!(draw_order(&capped, true), [0, 2, 3, 1, 4]); +} + +/// `order` with the pairs `before` (each first face drawn before the second) in their own order +/// ([`drawn_in_pairs_order`]), within `room` steps of looking for rings, and the steps taken; the +/// faces of `last` are drawn last. +fn in_pairs_order(order: &[usize], before: &[(usize, usize)], last: &[usize], room: usize) -> (Vec, usize) { + let n = order.len(); + let mut position = vec![0; n]; + for (at, &k) in order.iter().enumerate() { + position[k] = at; + } + let last: Vec = (0..n).map(|k| last.contains(&k)).collect(); + let mut left = room; + let drawn = drawn_in_pairs_order(order.to_vec(), &position, &last, narrow(before), &mut left); + (drawn, room - left) +} + +/// What [`drawn_in_pairs_order`] is to give with room enough, worked out plainly: at every stop +/// the faces behind the first face left are followed afresh, with nothing kept and no face taken +/// out of a list. +fn in_pairs_order_plainly(order: &[usize], before: &[(usize, usize)], last: &[usize]) -> Vec { + /// The first group completed behind `face`, among the faces `open`: its faces, or `None` while + /// its group goes on. `earlier` lists the faces before each face, lowest first. + fn group(face: usize, open: &[bool], earlier: &[Vec], reached: &mut Vec, low: &mut Vec) -> Option> { + let place = reached.len(); + reached.push(face); + low.push(place); + for &e in earlier[face].iter().filter(|&&e| open[e]) { + match reached.iter().position(|&f| f == e) { + Some(at) => low[place] = low[place].min(at), + None => { + let found = group(e, open, earlier, reached, low); + if found.is_some() { + return found; + } + low[place] = low[place].min(low[reached.iter().position(|&f| f == e).unwrap()]); + } + } + } + (low[place] == place).then(|| reached[place..].to_vec()) + } + let n = order.len(); + let mut at = vec![0; n]; + for (place, &k) in order.iter().enumerate() { + at[k] = place; + } + let mut earlier = vec![vec![]; n]; + for &(first, then) in before { + earlier[then].push(first); + } + earlier.iter_mut().for_each(|list| list.sort_unstable()); + let mut drawn = vec![false; n]; + let mut out: Vec = vec![]; + while out.len() < n { + let left: Vec = order.iter().copied().filter(|&k| !drawn[k]).collect(); + let limit = left.iter().find(|k| last.contains(k)).map_or(usize::MAX, |&k| at[k]); + let waits = |k: usize| earlier[k].iter().any(|&e| !drawn[e]); + let next = match left.iter().copied().find(|&k| at[k] < limit && !waits(k)) { + Some(ready) => ready, + None if at[left[0]] >= limit => left[0], + None => { + let open: Vec = (0..n).map(|k| !drawn[k] && at[k] < limit).collect(); + let found = group(left[0], &open, &earlier, &mut vec![], &mut vec![]).unwrap(); + found.into_iter().min_by_key(|&k| at[k]).unwrap() + } + }; + drawn[next] = true; + out.push(next); + } + out +} + +/// `pairs` as [`drawn_in_pairs_order`] takes them. +fn narrow(pairs: &[(usize, usize)]) -> Vec<(u32, u32)> { + pairs.iter().map(|&(first, then)| (first as u32, then as u32)).collect() +} + +/// The pairs of `before` that `drawn` draws the wrong way round. +fn broken(drawn: &[usize], before: &[(usize, usize)]) -> Vec<(usize, usize)> { + let mut at = vec![0; drawn.len()]; + for (place, &k) in drawn.iter().enumerate() { + at[k] = place; + } + before.iter().copied().filter(|&(first, then)| at[first] > at[then]).collect() +} + +/// After a ring's face is released, the faces left are looked at afresh: they may be a smaller +/// ring and faces in none. Two rings share face 1: 0 before 1 before 4 before 0, and 1 before 2 +/// before 3 before 1. By depth the order is 3, 2, 0, 4, 1. The five wait for no other face, so the +/// first stop releases 3, the first of them by depth. That leaves the one ring 0, 1, 4 and face +/// 2, which only waits for 1: 0 is released, and 2 follows 1. Only pairs of a ring are drawn the +/// wrong way round. Taking the first face left by depth at each stop drew 2 before 1 as well. +#[test] +fn the_faces_left_are_looked_at_afresh_after_each_face_released() { + let before = [(0, 1), (1, 4), (4, 0), (1, 2), (2, 3), (3, 1)]; + let (drawn, _) = in_pairs_order(&[3, 2, 0, 4, 1], &before, &[], usize::MAX); + assert_eq!(drawn, [3, 0, 1, 2, 4]); + assert_eq!(broken(&drawn, &before), [(4, 0), (2, 3)]); + assert_eq!(broken(&in_pairs_order(&[3, 2, 0, 4, 1], &before, &[], 0).0, &before), [(4, 0), (1, 2), (2, 3)]); +} + +/// A ring is the one behind the first face left by depth that waits for no face outside it: 0 +/// comes first by depth and waits for the ring 1, 2, 3, which waits for the ring 4, 5, 6. The far +/// ring is broken first (at 4) and drawn, then the near one (at 1), and 0 follows 1; one pair of +/// each ring is drawn the wrong way round, and no pair between them. Taking the first face left by +/// depth drew 0 first, under 1. +#[test] +fn the_ring_released_waits_for_no_face_outside_it() { + let before = [(1, 0), (1, 2), (2, 3), (3, 1), (4, 1), (4, 5), (5, 6), (6, 4)]; + let (drawn, _) = in_pairs_order(&[0, 1, 2, 3, 4, 5, 6], &before, &[], usize::MAX); + assert_eq!(drawn, [4, 5, 6, 1, 0, 2, 3]); + assert_eq!(broken(&drawn, &before), [(3, 1), (6, 4)]); + assert_eq!(broken(&in_pairs_order(&[0, 1, 2, 3, 4, 5, 6], &before, &[], 0).0, &before), [(1, 0), (3, 1), (4, 1), (6, 4)]); +} + +/// A ring is looked for among the faces that come before the next face drawn last: 1 comes first +/// by depth and waits for 4, a face of the ring 2, 3, 4, and for 0, which is drawn last. 0 waits +/// for no face, so it is a group of its own behind 1, but no face before it by depth can wait for +/// it. The ring gives up 2, and 1 follows 4; the pair of 1 and 0 cannot be kept. Stopping at 0 +/// drew 1 first, under 4. +#[test] +fn a_ring_is_looked_for_before_the_next_face_drawn_last() { + let before = [(2, 3), (3, 4), (4, 2), (4, 1), (0, 1)]; + let (drawn, _) = in_pairs_order(&[1, 2, 3, 4, 0], &before, &[0], usize::MAX); + assert_eq!(drawn, [2, 3, 4, 1, 0]); + assert_eq!(broken(&drawn, &before), [(4, 2), (0, 1)]); + assert_eq!(broken(&in_pairs_order(&[1, 2, 3, 4, 0], &before, &[0], 0).0, &before), [(4, 2), (4, 1), (0, 1)]); + // A face that waits only for a face after the one drawn last goes before the faces that wait + // for it: 0 waits for 1, 1 for 3, and 2 is drawn last. + let before = [(1, 0), (3, 1)]; + assert_eq!(in_pairs_order(&[0, 1, 2, 3], &before, &[2], usize::MAX).0, [1, 0, 2, 3]); + assert_eq!(in_pairs_order(&[0, 1, 2, 3], &before, &[2], 0).0, [0, 1, 2, 3]); +} + +/// Looking for rings is counted, and past the room given the first face not drawn yet goes next, +/// as before rings were looked for: the pairs of `a_face_in_front_of_a_cycle_waits_for_it`. A +/// face drawn last keeps every face before it by depth before it, ring or not. An order and +/// places in it that do not agree (an order that is not each face once), or a pair of a face that +/// is not in them, give the order back. +#[test] +fn breaking_rings_stops_at_its_room() { + let before = [(1, 0), (0, 2), (2, 1), (2, 3)]; + let order = [3, 0, 1, 2]; + let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX); + assert_eq!(drawn, [0, 2, 3, 1]); + // The faces and pairs behind 3. + assert!((4..=16).contains(&steps), "{steps} steps"); + assert_eq!(in_pairs_order(&order, &before, &[], steps), (vec![0, 2, 3, 1], steps)); + for room in [0, 1, steps - 1] { + let (drawn, taken) = in_pairs_order(&order, &before, &[], room); + assert_eq!(drawn, [3, 0, 2, 1], "{room}"); + assert!(taken <= room, "{room}"); + } + // 0 is drawn last: 3, before it by depth, goes before it, and the ring's other faces after. + assert_eq!(in_pairs_order(&order, &before, &[0], usize::MAX).0, [3, 0, 2, 1]); + // 2 is drawn last: every other face is before it by depth, so 3 and 1, which wait only for + // it, go when they come first of the faces behind the first face left, and 0 follows 1. + assert_eq!(in_pairs_order(&order, &before, &[2], usize::MAX).0, [3, 1, 0, 2]); + assert_eq!(in_pairs_order(&order, &before, &[2], 0).0, [3, 0, 1, 2]); + let mut room = usize::MAX; + let position = [1, 2, 3, 0]; + assert_eq!(drawn_in_pairs_order(order.to_vec(), &position, &[false; 3], narrow(&before), &mut room), order); + assert_eq!(drawn_in_pairs_order(order.to_vec(), &position, &[false; 4], vec![(9, 0)], &mut room), order); + assert_eq!(drawn_in_pairs_order(order.to_vec(), &position, &[false; 4], vec![(0, 4)], &mut room), order); + assert_eq!(drawn_in_pairs_order(order[..3].to_vec(), &position, &[false; 4], narrow(&before), &mut room), order[..3]); + assert_eq!(drawn_in_pairs_order(order.to_vec(), &position[..3], &[false; 4], narrow(&before), &mut room), order); + assert_eq!(drawn_in_pairs_order(order.to_vec(), &[1, 2, 0, 3], &[false; 4], narrow(&before), &mut room), order); + assert_eq!(drawn_in_pairs_order(vec![0, 0, 1, 2], &[0, 2, 3, 0], &[false; 4], narrow(&before), &mut room), [0, 0, 1, 2]); + assert_eq!(drawn_in_pairs_order(vec![0, 1, 2, 4], &[0, 1, 2, 3], &[false; 4], narrow(&before), &mut room), [0, 1, 2, 4]); + assert_eq!(room, usize::MAX); +} + +/// A first face left that waits only for the face drawn last goes next with no search: 1,000 +/// such faces before a ring cost nothing, and the ring behind them still has its room. Each face +/// i < 1,000 waits for 1,004, which is drawn last; 1,000 to 1,003 are the pairs of +/// `breaking_rings_stops_at_its_room`, where 1,003 comes first by depth and waits for the ring. +#[test] +fn a_face_that_waits_only_for_the_face_drawn_last_costs_no_search() { + let waiting = 1000usize; + let (r, last) = (waiting, waiting + 4); + let mut before: Vec<(usize, usize)> = (0..waiting).map(|f| (last, f)).collect(); + before.extend([(r + 1, r), (r, r + 2), (r + 2, r + 1), (r + 2, r + 3)]); + let order: Vec = (0..waiting).chain([r + 3, r, r + 1, r + 2, last]).collect(); + let (drawn, steps) = in_pairs_order(&order, &before, &[last], usize::MAX); + let expected: Vec = (0..waiting).chain([r, r + 2, r + 3, r + 1, last]).collect(); + assert_eq!(drawn, expected); + assert!(steps < 20, "{steps} steps"); + // The room the ring takes is enough, whatever waits before it. + assert_eq!(in_pairs_order(&order, &before, &[last], before.len().div_ceil(4).max(steps)).0, expected); +} + +/// The lists of the faces before each face are made only when the room left is at least a +/// quarter of the pairs: with less, no ring is looked for, however few steps the ring would take. +/// A ring of three behind 3,000 faces in a chain (each before the next). +#[test] +fn the_lists_for_rings_are_made_only_with_room_for_a_quarter_of_the_pairs() { + let chain = 3000usize; + let r = chain; + let mut before: Vec<(usize, usize)> = (0..chain - 1).map(|f| (f, f + 1)).collect(); + before.extend([(r + 1, r), (r, r + 2), (r + 2, r + 1), (r + 2, r + 3)]); + // As in `breaking_rings_stops_at_its_room`: 3 comes first by depth of the four and waits for + // the ring. + let order: Vec = (0..chain).chain([r + 3, r, r + 1, r + 2]).collect(); + let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX); + assert_eq!(drawn[chain..], [r, r + 2, r + 3, r + 1]); + assert!(steps < 20, "{steps} steps"); + let quarter = before.len().div_ceil(4); + let (drawn, steps) = in_pairs_order(&order, &before, &[], quarter - 1); + assert_eq!(drawn[chain..], [r + 3, r, r + 2, r + 1]); + assert_eq!(steps, 0); + assert_eq!(in_pairs_order(&order, &before, &[], quarter).0[chain..], [r, r + 2, r + 3, r + 1]); +} + +/// A list of the faces before a face is read only when the room left holds it: with less, no +/// entry of it is read, and the first face left goes next. Face 0 comes first by depth and waits +/// for 1, which waits for 2,000 faces after it in `order`, each waiting for 1: a ring of 1 with +/// each of them. +#[test] +fn a_list_longer_than_the_room_left_is_not_read() { + let wide = 2000usize; + let mut before = vec![(1, 0)]; + before.extend((2..2 + wide).flat_map(|f| [(f, 1), (1, f)])); + let order: Vec = (0..2 + wide).collect(); + // Room for the lists (a quarter of the pairs) but not for 1's list, and room for it. + // With too little room only 0's one-entry list is read; with room for both, 1's list as well. + for (room, want) in [(before.len().div_ceil(4), 1), (wide - 1, 1), (wide + 3, wide + 1)] { + super::LIST_ENTRIES_READ.with(|read| read.set(0)); + let (drawn, taken) = in_pairs_order(&order, &before, &[], room); + let read = super::LIST_ENTRIES_READ.with(|read| read.get()); + assert_eq!(read, want, "room {room}: {read} entries read, {taken} steps"); + assert!(read <= taken && taken <= room, "room {room}: {read} entries read, {taken} steps"); + assert_eq!(drawn.len(), order.len()); + } +} + +/// The steps of breaking rings are counted, not timed, and for rings of a few faces they are a +/// few a face however the rings lie: apart, each with a face in front of it that comes first by +/// depth; all behind one face, itself in a ring whose other faces come first in its list; and one +/// behind the other. The search goes on from where it stopped, and a face drawn is dropped from +/// a list the next time the list is looked at. A ring that is still a ring after it gives up a +/// face is walked again, so a large ring can take about its pairs for each face it gives up, the +/// square of its faces even when each waits for few others. With too little room the rings not +/// reached are broken at the first face left by depth, as before. +#[test] +fn breaking_rings_takes_a_few_steps_a_face_but_for_a_ring_of_many_pairs() { + // Ring r: faces 4r, 4r + 1 and 4r + 2 in a ring, and 4r + 3 after 4r + 2. + let rings = 2000usize; + let mut before = vec![]; + for r in 0..rings { + let f = 4 * r; + before.extend([(f + 1, f), (f, f + 2), (f + 2, f + 1), (f + 2, f + 3)]); + } + // By depth: every fourth face first, then the rings. + let order: Vec = (0..rings).map(|r| 4 * r + 3).chain((0..rings).flat_map(|r| [4 * r, 4 * r + 1, 4 * r + 2])).collect(); + let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX); + assert_eq!(broken(&drawn, &before), (0..rings).map(|r| (4 * r + 1, 4 * r)).collect::>()); + assert!(steps <= 4 * order.len(), "{steps} steps for {rings} rings apart"); + // With no room the fourth faces go first, under the faces they are in front of. + assert_eq!(broken(&in_pairs_order(&order, &before, &[], 0).0, &before).len(), 2 * rings); + + // Face 0, first by depth, is in a ring with 1 and 2, which come first in its list, and after a + // face of each ring r: faces 3r + 3, 3r + 4 and 3r + 5. + let rings = 3000usize; + let mut before = vec![(1, 0), (0, 2), (2, 1)]; + for r in 0..rings { + let f = 3 * r + 3; + before.extend([(f, f + 1), (f + 1, f + 2), (f + 2, f), (f, 0)]); + } + let order: Vec = (0..3 * rings + 3).collect(); + let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX); + // One pair of each ring, face 0's among them, and no pair of face 0 with another ring's face. + assert_eq!(broken(&drawn, &before), [(1, 0)].into_iter().chain((0..rings).map(|r| (3 * r + 5, 3 * r + 3))).collect::>()); + assert!(steps <= 4 * order.len(), "{steps} steps for {rings} rings behind one face"); + // The same with a face drawn last that every ring's first face waits for: it is passed over + // each time, and nothing after it in a list is looked at twice for that. + let cap = 3 * rings + 3; + let capped: Vec<(usize, usize)> = (0..rings).map(|r| (cap, 3 * r + 3)).chain(before.iter().copied()).collect(); + let order: Vec = (0..=cap).collect(); + let (drawn, steps) = in_pairs_order(&order, &capped, &[cap], usize::MAX); + assert_eq!(broken(&drawn, &capped).len(), 2 * rings + 1); + assert!(steps <= 5 * order.len(), "{steps} steps for {rings} rings behind one face, before a face drawn last"); + + // Ring r: faces 3r, 3r + 1 and 3r + 2, the first after the last face of ring r + 1. + let rings = 3000usize; + let mut before = vec![]; + for r in 0..rings { + let f = 3 * r; + before.extend([(f, f + 1), (f + 1, f + 2), (f + 2, f)]); + if r + 1 < rings { + before.push((f + 5, f)); + } + } + let order: Vec = (0..3 * rings).collect(); + let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX); + // One pair of each ring, and no pair between rings. + assert_eq!(broken(&drawn, &before).len(), rings); + assert!(broken(&drawn, &before).iter().all(|&(first, then)| first / 3 == then / 3)); + assert!(steps <= 4 * order.len(), "{steps} steps for {rings} rings one behind the other"); + let (short, taken) = in_pairs_order(&order, &before, &[], steps / 2); + assert!(broken(&short, &before).len() > rings && taken <= steps / 2, "{} pairs, {taken} steps", broken(&short, &before).len()); + assert_eq!(short.len(), order.len()); + + // One ring: each of 200 faces before the next 99. + let faces = 200usize; + let before: Vec<(usize, usize)> = (0..faces).flat_map(|f| (1..100).map(move |d| (f, (f + d) % faces))).collect(); + let order: Vec = (0..faces).collect(); + let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX); + assert_eq!(drawn, order); + // Each face it gives up walks the ring again, so it takes many times its pairs (the cost the + // docs name), but no more than about its pairs for each face. + assert!(steps < 2 * faces * before.len(), "{steps} steps for a ring of {} pairs", before.len()); + + // Pairs at random, about four a face: one large ring and faces around it. + let steps_of = |faces: usize| { + let mut next = numbers(faces as u64); + let before: Vec<(usize, usize)> = (0..2 * faces) + .map(|_| ((next() * faces as f64) as usize, (next() * faces as f64) as usize)) + .filter(|(first, then)| first != then) + .collect(); + let order: Vec = (0..faces).collect(); + let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX); + assert_eq!(drawn.len(), faces); + steps + }; + // No more than the square of the faces. + let (few, more) = (steps_of(800), steps_of(1600)); + assert!(few < 800 * 800 && more < 1600 * 1600, "{few} steps for 800 faces, {more} for 1,600"); +} + +/// Numbers from 0 to 1 that are the same on every run. +fn numbers(mut seed: u64) -> impl FnMut() -> f64 { + move || { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 11) as f64 / (1u64 << 53) as f64 + } +} + +/// A ring gives up its own face that comes first by depth, which draws no more pairs the wrong +/// way round than taking the first face left by depth, ring or not, as before: on 6,000 sets of +/// pairs at random (4 to 30 faces, sparse and dense, agreeing with the depths mostly or half the +/// time, the pairs in any order and some twice, with up to four faces drawn last) none has more, and they have fewer in all. Every face +/// is drawn once, a face drawn last follows every face before it by depth, and the order of every +/// set is the one that looking afresh at every stop gives. One of them is a +/// set where the ring's face that waits for the fewest faces drew 4 pairs wrong against 3. +#[test] +fn breaking_a_ring_draws_no_more_pairs_wrong_than_the_first_face_by_depth() { + let order = [3, 6, 4, 1, 0, 2, 5]; + let before = [ + (1, 0), + (2, 0), + (0, 3), + (0, 4), + (5, 0), + (6, 0), + (1, 2), + (1, 3), + (4, 1), + (5, 1), + (4, 2), + (5, 2), + (6, 2), + (3, 4), + (3, 6), + (5, 4), + (6, 4), + (5, 6), + ]; + assert_eq!(broken(&in_pairs_order(&order, &before, &[], 0).0, &before).len(), 3); + assert_eq!(broken(&in_pairs_order(&order, &before, &[], usize::MAX).0, &before).len(), 3); + + let mut next = numbers(7023); + let (mut with_rings, mut without, mut fewer) = (0usize, 0usize, 0usize); + for set in 0..6000 { + let n = 4 + (next() * 27.0) as usize; + let (dense, agrees) = (0.05 + 0.8 * next() * next(), if set % 2 == 0 { 0.5 } else { 0.85 }); + // The order by depth: the faces shuffled. + let mut order: Vec = (0..n).collect(); + for k in (1..n).rev() { + order.swap(k, (next() * (k + 1) as f64) as usize); + } + let mut before = vec![]; + for a in 0..n { + for b in a + 1..n { + if next() < dense { + before.push(if next() < agrees { (order[a], order[b]) } else { (order[b], order[a]) }); + } + } + } + // The pairs in any order, and in every fifth set some of them twice. + for k in (1..before.len()).rev() { + before.swap(k, (next() * (k + 1) as f64) as usize); + } + if set % 5 == 0 { + let again: Vec<(usize, usize)> = before.iter().copied().filter(|_| next() < 0.3).collect(); + before.extend(again); + } + // No face drawn last, or up to four. + let last: Vec = (0..set % 5).map(|_| order[(next() * n as f64) as usize]).collect(); + let (drawn, _) = in_pairs_order(&order, &before, &last, usize::MAX); + // Keeping the search from stop to stop gives what looking afresh at every stop gives. + assert_eq!(drawn, in_pairs_order_plainly(&order, &before, &last), "set {set}: {order:?} {before:?} {last:?}"); + let (plainly, _) = in_pairs_order(&order, &before, &last, 0); + let mut once = drawn.clone(); + once.sort_unstable(); + assert_eq!(once, (0..n).collect::>(), "set {set}"); + for &cap in &last { + let (at, place) = (order.iter().position(|&f| f == cap).unwrap(), drawn.iter().position(|&f| f == cap).unwrap()); + assert!(order[..at].iter().all(|f| drawn[..place].contains(f)), "set {set}"); + } + let (rings, plain) = (broken(&drawn, &before).len(), broken(&plainly, &before).len()); + assert!(rings <= plain, "set {set}: {rings} pairs wrong, {plain} with the first face by depth; {order:?} {before:?} {last:?}"); + with_rings += rings; + without += plain; + fewer += usize::from(rings < plain); + } + assert!(fewer > 500 && with_rings < without, "{with_rings} pairs wrong, {without} with the first face by depth, fewer in {fewer} sets"); +} + /// The order keeps depths except where a shape's fill wall turned toward the viewer overlaps a /// face of the same shape's stroke drawn before it: the wall then goes just before that face. A /// cap, a face turned away, another shape's stroke, a stroke face the wall does not overlap and an diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 054395d796..b9fd0b98e6 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -865,11 +865,11 @@ pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location pub use select::SIMILAR; pub(crate) use vectorcraft_doc::range::parse_range; -#[cfg(test)] -pub(crate) use paint::PAINTS_READ; /// What the fill and stroke proxies read from the selected objects, kept with the selection /// ([`crate::doc_state::SelectionRecord`]). pub(crate) use paint::SelectionPaints; +#[cfg(test)] +pub(crate) use paint::{PAINTS_READ, WEIGHTS_READ}; /// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see /// [`clock_date`]), `Some(None)` for null (no date), else `Some(Some(seconds))`. diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 43151bbebb..4fc1b83c29 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -954,9 +954,43 @@ pub(crate) fn selected_roots(s: &Session) -> Result> { Ok(selection_roots(s.doc()?)) } -/// [`selected_roots`] of one document's selection. +/// [`selected_roots`] of one document's selection, found once for each document version and set of selected +/// objects and kept on this thread: the menus' enabled checks read it many times for one selection. pub(crate) fn selection_roots(st: &crate::DocState) -> Vec { - roots_of(&st.doc, st.selection.in_paint_order(&st.doc)) + let at = Arc::as_ptr(&st.doc); + ROOTS.with_borrow_mut(|kept| { + if let Some((doc, objects, roots)) = kept.as_ref() + && doc.as_ptr() == at + && *objects == st.selection.objects + { + return roots.clone(); + } + #[cfg(test)] + ROOTS_FOUND.set(ROOTS_FOUND.get() + 1); + let roots = roots_of(&st.doc, st.selection.in_paint_order(&st.doc)); + *kept = Some((Arc::downgrade(&st.doc), st.selection.objects.clone(), roots.clone())); + roots + }) +} + +/// The selected objects and roots of the last [`selection_roots`], with the document version they belong to. It is +/// held weakly, so its address is not reused while it is kept, and an edit in place moves it. +type KeptRoots = Option<(std::sync::Weak, Vec, Vec)>; + +thread_local! { + static ROOTS: std::cell::RefCell = const { std::cell::RefCell::new(None) }; +} + +#[cfg(test)] +thread_local! { + /// How many times [`selection_roots`] found the roots on this thread. + static ROOTS_FOUND: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many times [`selection_roots`] has found the roots on this thread. +#[cfg(test)] +pub(crate) fn roots_found() -> u64 { + ROOTS_FOUND.get() } /// [`super::brushsym::part_only`] while an object of a dynamic symbol instance's art is selected: diff --git a/crates/engine/src/cmd/edit/tests.rs b/crates/engine/src/cmd/edit/tests.rs index 1e41b0c4ac..7ac2d9c162 100644 --- a/crates/engine/src/cmd/edit/tests.rs +++ b/crates/engine/src/cmd/edit/tests.rs @@ -347,3 +347,26 @@ fn direct_selection_cut_timing() { println!("median {}: cpu {:?}, wall {:?}", ["one at a time", "Cut"][k], median(cpu), median(wall)); } } + +/// The selected roots are found once for a document version and its selected objects, however many enabled checks +/// read them, and found again after the selection changes, after an edit, and for another selection. +#[test] +fn selected_roots_are_found_once_for_each_document_and_selection() { + let mut s = session(30, square); + let all = selected_roots(&s).unwrap(); + assert_eq!(all.len(), 30); + let before = roots_found(); + for _ in 0..20 { + assert_eq!(selected_roots(&s).unwrap(), all); + } + assert_eq!(roots_found() - before, 0, "reading the same selection again finds nothing"); + s.execute("select.set", &json!({"ids": [all[3].0, all[7].0]})).unwrap(); + assert_eq!(selected_roots(&s).unwrap(), vec![all[3], all[7]]); + assert_eq!(roots_found() - before, 1, "a new selection is found once"); + s.execute("object.group", &json!({})).unwrap(); + let grouped = selected_roots(&s).unwrap(); + assert_eq!(grouped.len(), 1, "the group is the one root: {grouped:?}"); + assert_ne!(grouped, vec![all[3], all[7]]); + selected_roots(&s).unwrap(); + assert_eq!(roots_found() - before, 2, "an edit finds the roots once again"); +} diff --git a/crates/engine/src/cmd/fileio/importer.rs b/crates/engine/src/cmd/fileio/importer.rs index d89cfa22b7..c578dece5d 100644 --- a/crates/engine/src/cmd/fileio/importer.rs +++ b/crates/engine/src/cmd/fileio/importer.rs @@ -13,13 +13,16 @@ //! a new document whose artboard is their bounds (or, to place, the art of one group), and nothing //! opens or is placed when the importer fails, declines, is cancelled or returns objects that don't //! pass the checks a filter's output does. +//! An importer at plug-in API level 4 may also return point type, embedded images, top-level +//! layers and artboards (its manifest's `outputKinds`): the artboards it returns replace the one +//! around the art of a new document, and File › Place leaves them out. use std::sync::Arc; use serde_json::Value; -use vectorcraft_doc::{Document, MAX_COORD, NodeId}; -use vectorcraft_geom::Rect; -use vectorcraft_plugins::import::Mode; +use vectorcraft_doc::{CharStyle, Document, ImageObject, LAYER_COLORS, LayerColor, MAX_COORD, Node, NodeId, NodeKind, TextObject}; +use vectorcraft_geom::{Point, Rect}; +use vectorcraft_plugins::import::{ImportObject, Mode}; use vectorcraft_plugins::{Manifest, Plugin, export, import, objects}; use super::super::{Result, bad, str_param}; @@ -210,17 +213,15 @@ pub(crate) fn place_source<'a>(p: &'a Value, cmd: &str) -> Result> { } } +/// What [`read`] gives: the importer's format, the new document, its objects' ids, the artboards +/// the importer returned and its warnings. +type Read = (&'static Format, Document, Vec, Vec, Vec); + /// The file `name` holding `bytes` read by importer `plugin` for `mode` with command `cmd`'s params /// `p` (`params`: the importer's own parameters) → the importer's format, a new document holding its -/// objects on its first layer, their ids, and its warnings. -fn read( - name: &str, - bytes: &[u8], - plugin: &Plugin, - p: &Value, - cmd: &str, - mode: Mode, -) -> Result<(&'static Format, Document, Vec, Vec)> { +/// objects (on its first layer, or in the layers the importer returned), their ids, the artboards +/// the importer returned, and its warnings. +fn read(name: &str, bytes: &[u8], plugin: &Plugin, p: &Value, cmd: &str, mode: Mode) -> Result { let m = plugin.manifest(); let format = format(&export::format_id(&m.id)).filter(|f| f.read).ok_or_else(|| err(vectorcraft_plugins::Error::NotFound(m.id.clone())))?; let (ext, stem) = (extension(name), file_stem(name)); @@ -234,15 +235,24 @@ fn read( let mut doc = Document::new(1.0, 1.0); let layer = doc.layers.first().map(|l| l.id); let admit = |fx: &[vectorcraft_doc::Effect], n: &vectorcraft_doc::Node| crate::cmd::plugin::admit_effects_for(cmd, fx, n); - let ids = objects::apply_output(&mut doc, &[], imported.objects, layer, &admit).map_err(|e| failed(mode, name, e))?; - Ok((format, doc, ids, imported.warnings)) + let mut warnings = Vec::new(); + let (ids, artboards) = if imported.paths_only() { + let paths = imported.objects.into_iter().filter_map(|o| if let ImportObject::Path(o) = o { Some(o) } else { None }).collect(); + (objects::apply_output(&mut doc, &[], paths, layer, &admit).map_err(|e| failed(mode, name, e))?, Vec::new()) + } else { + let ids = build(&mut doc, imported.objects, imported.layers, &admit, &mut warnings).map_err(|e| failed(mode, name, e))?; + (ids, imported.artboards) + }; + warnings.splice(0..0, imported.warnings); + Ok((format, doc, ids, artboards, warnings)) } /// The file `name` holding `bytes` read by importer `plugin` to place it, with `file.place`'s params -/// `p` (errors of command `cmd`) → the importer's format, the document holding its objects on its -/// first layer, and its warnings. Importer `plugin`'s manifest must set `place`. +/// `p` (errors of command `cmd`) → the importer's format, the document holding its objects in its +/// layers, and its warnings; artboards the importer returned are left out. Importer `plugin`'s +/// manifest must set `place`. pub(crate) fn read_for_place(name: &str, bytes: &[u8], plugin: &Plugin, p: &Value, cmd: &str) -> Result<(&'static Format, Document, Vec)> { - let (format, doc, _, warnings) = read(name, bytes, plugin, p, cmd, Mode::Place)?; + let (format, doc, _, _, warnings) = read(name, bytes, plugin, p, cmd, Mode::Place)?; Ok((format, doc, warnings)) } @@ -250,14 +260,148 @@ pub(crate) fn read_for_place(name: &str, bytes: &[u8], plugin: &Plugin, p: &Valu /// (`params`: the importer's own parameters) into a new document, its artboard the bounds of what /// the importer returned. pub(super) fn load(name: &str, bytes: &[u8], plugin: &Plugin, p: &Value) -> Result { - let (format, mut doc, ids, warnings) = read(name, bytes, plugin, p, C, Mode::Import)?; - if let (Some(bounds), Some(board)) = (doc.bounds_of(&ids, true), doc.artboards.first_mut()) { - board.rect = artboard_rect(bounds); + let (format, mut doc, ids, artboards, warnings) = read(name, bytes, plugin, p, C, Mode::Import)?; + if artboards.is_empty() { + if let (Some(bounds), Some(board)) = (doc.bounds_of(&ids, true), doc.artboards.first_mut()) { + board.rect = artboard_rect(bounds); + } + } else { + set_artboards(&mut doc, artboards); } doc.title = file_name(name); Ok(Loaded { doc, format, warnings, restored: false, converted: false, preview_only: false, editing_data: false, native_pdf_compatible: None }) } +/// Puts `objects`, what an importer at plug-in API level 4 returned, into `doc`, a new document of +/// one layer: in `layers`, bottom first, each holding the objects it lists in their order, or all in +/// that one layer when there are none. Paths are made as a filter's new ones are (their effects let +/// in by `admit`), type is laid out, and each image is stored in the document as a PNG of its +/// pixels. A warning for type whose font isn't there, or doesn't have its style, goes to `warnings`. +/// An object that reaches more than [`MAX_COORD`] from the origin is an error. Returns the objects' +/// ids in order. +fn build( + doc: &mut Document, + objects: Vec, + layers: Vec, + admit: objects::AdmitEffects, + warnings: &mut Vec, +) -> std::result::Result, String> { + let count = objects.len(); + let first = doc.layers.first().map(|l| (**l).clone()); + let first = first.unwrap_or_else(|| Node::layer(doc.alloc_id(), "Layer 1", LayerColor::Preset(0))); + let mut owner = vec![0usize; count]; + for (li, l) in layers.iter().enumerate() { + for &k in &l.objects { + if let Some(o) = owner.get_mut(k) { + *o = li; + } + } + } + let mut members: Vec>> = vec![Vec::new(); layers.len().max(1)]; + let mut ids = Vec::with_capacity(count); + let mut fonts = std::collections::BTreeSet::new(); + for (i, o) in objects.into_iter().enumerate() { + let at = format!("objects[{i}]"); + let node = match o { + ImportObject::Path(o) => objects::new_object(doc, o, &at, admit).map_err(|e| e.to_string())?, + ImportObject::Type(t) => { + let node = type_node(doc, t); + if let NodeKind::Text(t) = &node.kind { + fonts.extend(t.runs.iter().flat_map(crate::cmd::fonts::run_fonts)); + } + node + } + ImportObject::Image(im) => image_node(doc, im).map_err(|e| e.to_string())?, + }; + if node.geometric_bounds().is_some_and(|b| ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD)) { + return Err(format!("plug-in output: {at}: it reaches more than {MAX_COORD} pt from the origin")); + } + ids.push(node.id); + if let Some(list) = owner.get(i).and_then(|&li| members.get_mut(li)) { + list.push(Arc::new(node)); + } + } + let built: Vec> = if layers.is_empty() { + let mut layer = first; + if let Some(children) = layer.children_mut() { + *children = members.into_iter().next().unwrap_or_default(); + } + vec![Arc::new(layer)] + } else { + layers + .into_iter() + .zip(members) + .enumerate() + .map(|(li, (l, children))| { + let mut layer = Node::layer(doc.alloc_id(), &l.name, LayerColor::Preset((li % LAYER_COLORS.len()) as u8)); + layer.visible = l.visible; + layer.locked = l.locked; + if let Some(c) = layer.children_mut() { + *c = children; + } + Arc::new(layer) + }) + .collect() + }; + doc.layers = built; + warnings.extend(crate::cmd::fonts::set_font_warning(fonts)); + Ok(ids) +} + +/// Point type `t` as a new node of `doc`, in [Normal Character Style] with the face, size and fill +/// `t` gives, laid out. +fn type_node(doc: &mut Document, t: import::OutType) -> Node { + let mut style = crate::cmd::textstyles::normal_char_style(doc); + style.font_version = None; + style.font_axes.clear(); + style.font_family = t.font_family; + match t.font_style { + Some(s) => style.font_style = s, + None => { + style.font_style = CharStyle::default().font_style; + crate::cmd::textedit::fit_font_style(&mut style); + } + } + style.size = t.font_size; + if let Some(fill) = t.fill { + style.fill = fill; + } + let mut text = TextObject::point(Point::ZERO, &t.text, style); + text.xf = t.transform; + text.para = crate::cmd::create::new_type_para(); + text.system_layout = doc.setup.system_layout; + crate::cmd::typecmd::refresh_bounds(&mut text); + let mut n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(text))); + n.name = t.name; + n +} + +/// Image `im` as a new node of `doc`, its pixels stored in `doc` as a PNG. +fn image_node(doc: &mut Document, im: import::OutImage) -> Result { + let pixels = image::RgbaImage::from_raw(im.width, im.height, im.rgba).ok_or_else(|| err("the image's pixels don't match its size"))?; + let stored = super::load::as_png(pixels, None, None)?; + let image = ImageObject { + key: stored.key.clone(), + width: stored.width, + height: stored.height, + xf: im.transform, + link: None, + placement: Default::default(), + pixels: None, + }; + doc.images.insert(stored.key, stored.blob); + let mut n = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(image))); + n.name = im.name; + Ok(n) +} + +/// Gives `doc` the artboards `boards` an importer returned, in order, in place of its one. +fn set_artboards(doc: &mut Document, boards: Vec) { + let Some(template) = doc.artboards.first().cloned() else { return }; + doc.artboards = + boards.into_iter().zip(1u32..).map(|(b, id)| vectorcraft_doc::Artboard { id, name: b.name, rect: b.rect, ..template.clone() }).collect(); +} + /// The artboard of art with bounds `r`: `r` within ±[`MAX_COORD`], at least 1 pt wide and high /// about its center (the artboard of a single line or point). A side that would pass the edge /// moves inward, so art at the edge keeps an artboard the document's edits accept. diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index c79f795b50..3ea811392d 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -576,23 +576,36 @@ struct ObjectOpacity { knockout_shape: bool, } +/// The series `id` belongs to when it is a graph series group or a path directly in one, as [`series_members`] finds +/// it. Looked up through its parents, with no pass over the document. +fn series_group_or_mark(doc: &Document, id: NodeId) -> Option { + let node = doc.node(id)?; + let chain = doc.ancestry(id)?; + let parent = doc.node(*chain.iter().rev().nth(1)?)?; + let in_graph = |group: &Node, graph: &Node| { + let index = group.extras().series_index.and_then(|i| usize::try_from(i).ok())?; + graph.extras().graph.as_deref().filter(|spec| index < series_count(spec)).map(|_| SeriesRef { graph: graph.id, group: group.id, index }) + }; + if let Some(r) = in_graph(node, parent) { + return Some(r); + } + // Only the paths the graph draws again, not the copy of a graph design. + if !matches!(node.kind, NodeKind::Path { .. }) { + return None; + } + in_graph(parent, doc.node(*chain.iter().rev().nth(2)?)?) +} + /// The graph, series, whether it is the series group itself (`true`) or a path directly in it, and the object -/// transparency of each of `edited` that is one of those, in order. +/// transparency of each of `edited` that is one of those, in order. Each object is looked up through its parents +/// ([`series_group_or_mark`]), so an edit of a few objects does not read the rest of the document. fn object_opacity_captures(doc: &Document, edited: &[NodeId]) -> Vec<(NodeId, usize, bool, ObjectOpacity)> { - if edited.is_empty() { - return Vec::new(); - } - let members = series_members(doc); - if members.is_empty() { - return Vec::new(); - } edited .iter() .filter_map(|id| { - let r = members.get(id)?; + let r = series_group_or_mark(doc, *id)?; let group = r.group == *id; - // Only the series group and the paths the graph draws again, not the copy of a graph design. - let node = doc.node(*id).filter(|n| group || (doc.parent_of(*id) == Some(r.group) && matches!(n.kind, NodeKind::Path { .. })))?; + let node = doc.node(*id)?; let mut look = ObjectOpacity { opacity: (node.opacity < 1.0).then_some(node.opacity), blend: (node.blend != BlendMode::Normal).then_some(node.blend), @@ -675,6 +688,25 @@ fn graph_labels(doc: &Document) -> HashMap { out } +/// The graph and kind of generated label `id`, as [`graph_labels`] finds it. Only the graphs among its parent and +/// grandparent are read, with no pass over the document; `own` keeps each graph's labels read so far. +fn graph_label_of(doc: &Document, id: NodeId, own: &mut HashMap>) -> Option<(NodeId, Role)> { + if !doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_))) { + return None; + } + let chain = doc.ancestry(id)?; + // The nearer graph first: [`graph_labels`] visits it later, so its entry is the one kept. + for graph in chain.iter().rev().skip(1).take(2) { + let Some(n) = doc.node(*graph) else { continue }; + let Some(spec) = n.extras().graph.as_deref() else { continue }; + let labels = own.entry(*graph).or_insert_with(|| own_labels(n, spec).into_iter().collect()); + if let Some(role) = labels.get(&id) { + return Some((*graph, *role)); + } + } + None +} + /// The generated labels of graph `n` (with spec `g`) and what each shows, as [`graph_labels`] finds them. fn own_labels(n: &Node, g: &GraphSpec) -> Vec<(NodeId, Role)> { let mut out = vec![]; @@ -1725,9 +1757,9 @@ fn label_rows_of(doc: &Document, ids: &[NodeId]) -> Vec<(NodeId, Role, Option)> = vec![]; - for (&(g, role), n) in ids.iter().rev().filter_map(|id| Some((labels.get(id)?, doc.node(*id)?))) { + for ((g, role), n) in ids.iter().rev().filter_map(|id| Some((graph_label_of(doc, *id, &mut own)?, doc.node(*id)?))) { if !picked.iter().any(|(pg, pr, _)| *pg == g && *pr == role) { picked.push((g, role, label_rows(n))); } diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index b8136e8cf5..9bb39e1e96 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -398,21 +398,26 @@ pub(crate) fn painted<'a>(n: &'a Node, top: bool, stroke: bool, out: &mut Vec<&' thread_local! { /// Tests: how many fills [`SelectionPaints`] read or took out on this thread. pub(crate) static PAINTS_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Tests: how many stroke weights [`SelectionPaints`] read or took out on this thread. + pub(crate) static WEIGHTS_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// The objects that reading objects `ids` meets, one item each ([`SelectionPaints::reads_no_more_than`]): /// each id, and the contents of a group, a layer, a Live Paint group or a container inside a group, -/// as [`painted`] expands them. An id with no object and a ruler guide count once each. +/// as [`painted`] expands them. An id with no object and a ruler guide count once each. A type +/// object counts once for each of its runs, since the stroke weights are read run by run. struct Reads<'a> { doc: &'a Document, ids: std::slice::Iter<'a, NodeId>, /// The contents not counted yet of the objects met, innermost last. left: Vec>>, + /// The runs not counted yet of the type object met last. + runs: usize, } impl<'a> Reads<'a> { fn new(doc: &'a Document, ids: &'a [NodeId]) -> Self { - Self { doc, ids: ids.iter(), left: vec![] } + Self { doc, ids: ids.iter(), left: vec![], runs: 0 } } } @@ -420,6 +425,10 @@ impl Iterator for Reads<'_> { type Item = (); fn next(&mut self) -> Option<()> { + if self.runs > 0 { + self.runs -= 1; + return Some(()); + } loop { let (n, top) = match self.left.last_mut() { Some(contents) => match contents.next() { @@ -447,6 +456,9 @@ impl Iterator for Reads<'_> { if let Some(contents) = n.children().filter(|_| expand) { self.left.push(contents.iter()); } + if let NodeKind::Text(t) = &n.kind { + self.runs = t.runs.len().saturating_sub(1); + } return Some(()); } } @@ -618,6 +630,8 @@ impl SelectionPaints { NodeKind::Text(t) => t.runs.iter().map(|r| r.style.stroke_layer().width).collect(), _ => n.appearance.stroke().map(|s| s.width).into_iter().collect(), }; + #[cfg(test)] + WEIGHTS_READ.with(|c| c.set(c.get() + widths.len())); for w in widths { if add { self.weight.add(w, |a, b| a == b); diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 3e0a808fd5..c277af5c28 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -88,7 +88,7 @@ pub fn specs() -> Vec { "Place…", ["File"], Some("Cmd+Shift+P"), - "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its objects, guides left out, are placed as one group named after the file, in the order it returned them, embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] center (default: the first artboard's center; all retained geometry, including art outside a crop frame, must stay within ±4,000,000 pt on either axis after transformation, including template placement), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its visible layers' objects (all objects without layers), guides left out, are placed as one group named after the file, from the bottom layer upward in each layer's listed order (returned object order without layers), embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), @@ -867,6 +867,38 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { Affine::translate(c - natural.center()) } }; + let mut retained = natural; + match &loaded.art { + Art::Vector { src, nodes, .. } => { + let symbols = src.symbol_boxes(); + for node in nodes { + node.walk(&mut |node| { + if let Some(bounds) = node.geometric_bounds_with(&symbols) { + retained = retained.union(bounds); + } + }); + } + } + Art::Image(image, _) => { + let (sx, sy) = pt_per_px(image.ppi); + retained = retained.union(Rect::new(0.0, 0.0, f64::from(image.width) * sx, f64::from(image.height) * sy)); + } + Art::Dcs(art) => { + let pixels = Rect::new(0.0, 0.0, f64::from(art.img.width), f64::from(art.img.height)); + retained = retained.union(art.xf.transform_rect_bbox(pixels)); + if let Some(clip) = &art.clip { + clip.walk(&mut |node| { + if let Some(bounds) = node.geometric_bounds() { + retained = retained.union(bounds); + } + }); + } + } + Art::Text(_) | Art::Document(..) => {} + } + if !crate::sanity::rect_in_range(m.transform_rect_bbox(retained)) { + return Err(bad(PLACE, "placed art lies outside the canvas")); + } let parent = st.insertion_parent(); let below = st.current_layer().or_else(|| parent.and_then(|p| st.doc.layer_of(p))); let link = loaded.link.take().filter(|_| bool_or(p, "link", true)); diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index b9e9a959e0..e890c2b65f 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -119,6 +119,9 @@ pub fn describe(p: &Plugin) -> Value { if !m.inputs.is_empty() { v["inputs"] = json!(m.inputs); } + if !m.output_kinds.is_empty() { + v["outputKinds"] = json!(m.output_kinds); + } if !m.writes.is_empty() { v["writes"] = json!(m.writes); } @@ -2408,7 +2411,7 @@ pub fn specs() -> Vec { "List Plug-ins", [], None, - "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\"|\"generator\" (a generator draws art from its parameters, see plugin.generate), author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), appearanceOutput?: true (a live effect whose pieces, fills and strokes may also have opacity, a blending mode and effects), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema, menu?: {path?: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there), context?: [{menu: \"canvas\"|\"layers\", when?: \"selection\"|\"oneObject\"|\"typeObject\"|\"layerRow\"}] (the context menus that also list it)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), failed: [{file, error, from: \"store\"|\"folder\"}] (the plug-in files that didn't load in this process and that plugin.retry loads again: those of the plug-in store that didn't install, until they install or the store is loaded again, then those of the folder report's failed, without the disabled ones and ones skipped because another install or removal of their id came first), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\"|\"generator\" (a generator draws art from its parameters, see plugin.generate), author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), outputKinds?: [\"type\"|\"image\"|\"layer\"|\"artboard\"] (what an importer at API level 4 returns besides paths, see docs/plugins.md), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 to 4), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), appearanceOutput?: true (a live effect whose pieces, fills and strokes may also have opacity, a blending mode and effects), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema, menu?: {path?: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there), context?: [{menu: \"canvas\"|\"layers\", when?: \"selection\"|\"oneObject\"|\"typeObject\"|\"layerRow\"}] (the context menus that also list it)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), failed: [{file, error, from: \"store\"|\"folder\"}] (the plug-in files that didn't load in this process and that plugin.retry loads again: those of the plug-in store that didn't install, until they install or the store is loaded again, then those of the folder report's failed, without the disabled ones and ones skipped because another install or removal of their id came first), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", always, list ), diff --git a/crates/engine/src/cmd/xform.rs b/crates/engine/src/cmd/xform.rs index f12df3f229..7b71a20a3a 100644 --- a/crates/engine/src/cmd/xform.rs +++ b/crates/engine/src/cmd/xform.rs @@ -4,8 +4,9 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::Paint; -use vectorcraft_doc::{Node, NodeKind, OrientedBox, Scaling}; -use vectorcraft_geom::{Affine, Point, Rect, Vec2}; +use vectorcraft_doc::{Node, NodeKind, OrientedBox, Scaling, SymbolBoxes}; +use vectorcraft_geom::{Affine, Homography, Point, Rect, Vec2}; +use vectorcraft_tools::distort::project_node; use super::edit::{outermost, selected_roots}; use super::{ @@ -21,7 +22,7 @@ pub fn specs() -> Vec { "Free Distort", [], None, - "{corners: [[x,y]×4] (TL, TR, BR, BL), from?: [x0,y0,x1,y1] (default: selection bounds), angle?: degrees (counter-clockwise; `from`, or the selection bounds, is then a box in the frame turned by it, as a rotated bounding box is; default 0), ids?} projective warp of anchors and handles; an image's four corners go exactly where the warp takes them and its pixels are drawn in perspective between them (an error, and nothing changes, when an image's corners would fold over, fall on one line, cross the warp's horizon or lie too close together for a perspective map); a linked opacity mask's art is warped with its object, an unlinked one stays; each warped object's bounding box (the objects inside groups and the art of linked masks too) turns as the warp turns the art at its center (object.resetBoundingBox squares it again); corners where the box already stands change nothing and add no undo step", + "{corners: [[x,y]×4] (TL, TR, BR, BL), from?: [x0,y0,x1,y1] (default: selection bounds), angle?: degrees (counter-clockwise; `from`, or the selection bounds, is then a box in the frame turned by it, as a rotated bounding box is; default 0), ids?} projective warp of anchors and handles; an image's four corners go exactly where the warp takes them and its pixels are drawn in perspective between them (an error, and nothing changes, when an image's corners would fold over, fall on one line, cross the warp's horizon or lie too close together for a perspective map); the corners of a type object's or symbol instance's box go exactly where the warp takes them too, and it stays type or an instance, drawn through the warp after any projection it had (the same errors, naming the object); a linked opacity mask's art is warped with its object, an unlinked one stays; each warped object's bounding box (the objects inside groups and the art of linked masks too) turns as the warp turns the art at its center (object.resetBoundingBox squares it again); corners where the box already stands change nothing and add no undo step", has_doc, distort ), @@ -105,6 +106,21 @@ impl Projective { Point::new((a * u + b * v + c) / w, (d * u + e * v + f) / w) } + /// Whether the warp is a perspective map rather than an affine one. + fn is_projective(&self) -> bool { + let [.., g, h] = self.m; + g != 0.0 || h != 0.0 + } + + /// The warp as one page-to-page map, which [`Self::apply`] matches in front of the horizon. + fn homography(&self) -> Homography { + let [a, b, c, d, e, f, g, h] = self.m; + let scale = |len: f64| if len.abs() > 1e-12 { 1.0 / len } else { 0.0 }; + let (sx, sy) = (scale(self.src.width()), scale(self.src.height())); + let to_unit = Affine::new([sx, 0.0, 0.0, sy, -self.src.x0 * sx, -self.src.y0 * sy]) * self.pre; + Homography([[a, b, c], [d, e, f], [g, h, 1.0]]).then_after(&Homography::from_affine(to_unit)) + } + /// Affine approximation at a point (for objects that can't be warped: text, images, symbols). fn affine_near(&self, p: Point) -> Affine { let eps = 1.0; @@ -127,6 +143,8 @@ fn warp_node(n: &mut Node, pr: &Projective) -> Option { n.pin_gradients(); // The children before these are left out of a group's or compound path's bounds. let skip = n.children().map_or(0, Vec::len) - n.editing_children().len(); + // Type and symbol instances drawn through the warp keep their gradients in their own art. + let mut projected = false; let before = match &mut n.kind { NodeKind::Path { path, live, .. } => { let b = path.bounds(); @@ -156,6 +174,15 @@ fn warp_node(n: &mut Node, pr: &Projective) -> Option { } b } + // Type and symbol instances keep their art and are drawn through the warp, after the + // projection they had ([`project_node`]), so the corners of their box follow it exactly; + // [`distort`] has checked that the projection stays finite and their corners in front of + // the horizon. + NodeKind::Text(_) | NodeKind::SymbolInstance { .. } if pr.is_projective() => { + let b = n.geometric_bounds(); + projected = project_node(n, &pr.homography()); + b + } _ => { // No editable points: the affine approximation (which maps the gradients too). let b = n.geometric_bounds(); @@ -171,7 +198,9 @@ fn warp_node(n: &mut Node, pr: &Projective) -> Option { if let Some(m) = n.extras_if_any().and_then(|x| x.mask.as_mut()).filter(|m| m.linked) { warp_node(Arc::make_mut(&mut m.art), pr); } - n.appearance.warp_gradients(&|p| pr.affine_near(p)); + if !projected { + n.appearance.warp_gradients(&|p| pr.affine_near(p)); + } before } @@ -199,17 +228,19 @@ fn warp_children(children: &mut [Arc], pr: &Projective, counts: impl Fn(us }) } -/// The first image in `n` (its children and the art of linked opacity masks, as [`warp_node`] -/// reaches them) whose corners `pr` would fold, collapse or carry past the warp's horizon, with -/// why. -fn unwarpable_image(n: &Node, pr: &Projective) -> Option<(vectorcraft_doc::NodeId, Unwarpable)> { +/// The first image, type object or symbol instance in `n` (its children and the art of linked +/// opacity masks, as [`warp_node`] reaches them) whose corners `pr` would fold, collapse or carry +/// past the warp's horizon, or type being edited flat, with why. `symbols` measures the boxes of +/// symbol instances. +fn unwarpable(n: &Node, pr: &Projective, symbols: &SymbolBoxes) -> Option<(vectorcraft_doc::NodeId, Cornered, Unwarpable)> { if let (Some(q), NodeKind::Image(im)) = (n.image_corners(), &n.kind) { if !q.iter().all(|p| pr.in_front(*p)) { - return Some((n.id, Unwarpable::Horizon)); + return Some((n.id, Cornered::Image, Unwarpable::Horizon)); } if let Err(e) = vectorcraft_doc::image_quad::check_for(im, &q.map(|p| pr.apply(p))) { return Some(( n.id, + Cornered::Image, match e { vectorcraft_doc::image_quad::QuadError::NotFinite | vectorcraft_doc::image_quad::QuadError::NotConvex => Unwarpable::NotConvex, vectorcraft_doc::image_quad::QuadError::TooNarrow => Unwarpable::TooNarrow, @@ -217,24 +248,79 @@ fn unwarpable_image(n: &Node, pr: &Projective) -> Option<(vectorcraft_doc::NodeI )); } } - warped_parts(n).into_iter().find_map(|c| unwarpable_image(c, pr)) + // Type and symbol instances are drawn through the warp ([`warp_node`]): their box's corners + // must stay in front of its horizon, and the projection they end with must be one that draws. + if let Some(kind) = Cornered::of(n).filter(|k| *k != Cornered::Image && pr.is_projective()) { + if kind == Cornered::Type && n.extras().perspective.as_deref().is_some_and(|p| p.editing) { + return Some((n.id, kind, Unwarpable::EditingFlat)); + } + if n.drawn_corners(symbols).is_some_and(|q| !q.iter().all(|p| pr.in_front(*p))) { + return Some((n.id, kind, Unwarpable::Horizon)); + } + let had = n.extras().perspective.as_deref().and_then(|p| p.homography()).unwrap_or(Homography::IDENTITY); + let Some(after) = pr.homography().checked_then_after(&had).and_then(|h| Homography::from_array(h.to_array())) else { + return Some((n.id, kind, Unwarpable::TooNarrow)); + }; + // The map it ends with must place its flat corners by the rules it is drawn with. + let flat = match n.extras().perspective.is_some() { + true => { + let mut flat = n.clone(); + flat.extras_mut().perspective = None; + flat.drawn_corners(symbols) + } + false => n.drawn_corners(symbols), + }; + if flat.is_some_and(|q| q.iter().any(|p| after.apply(*p).is_none())) { + return Some((n.id, kind, Unwarpable::Horizon)); + } + } + warped_parts(n).into_iter().find_map(|c| unwarpable(c, pr, symbols)) } -/// The first image in `n` that [`warp_node`] reaches (its children and the art of linked opacity -/// masks). -fn first_image(n: &Node) -> Option { - if matches!(n.kind, NodeKind::Image(_)) { - return Some(n.id); +/// The first image, type object or symbol instance in `n` that [`warp_node`] reaches (its children +/// and the art of linked opacity masks), whose corners follow the warp exactly. +fn first_cornered(n: &Node) -> Option<(vectorcraft_doc::NodeId, Cornered)> { + if let Some(kind) = Cornered::of(n) { + return Some((n.id, kind)); + } + warped_parts(n).into_iter().find_map(first_cornered) +} + +/// The objects whose corners follow a distort exactly. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Cornered { + Image, + Type, + Symbol, +} + +impl Cornered { + fn of(n: &Node) -> Option { + match n.kind { + NodeKind::Image(_) => Some(Self::Image), + NodeKind::Text(_) => Some(Self::Type), + NodeKind::SymbolInstance { .. } => Some(Self::Symbol), + _ => None, + } + } + + /// The object's name in an error. + fn noun(self) -> &'static str { + match self { + Self::Image => "image", + Self::Type => "type object", + Self::Symbol => "symbol instance", + } } - warped_parts(n).into_iter().find_map(first_image) } /// The objects inside `n` that [`warp_node`] warps point by point: the children of layers, groups -/// and compound paths, and the art of a linked opacity mask on those, paths and images. Other -/// objects (blends, envelopes, repeats and the rest) take the warp's affine approximation whole. +/// and compound paths, and the art of a linked opacity mask on those, paths, images, type and +/// symbol instances. Other objects (blends, envelopes, repeats and the rest) take the warp's affine +/// approximation whole. fn warped_parts(n: &Node) -> Vec<&Node> { let inside = matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. }); - let mask_too = inside || matches!(n.kind, NodeKind::Path { .. } | NodeKind::Image(_)); + let mask_too = inside || matches!(n.kind, NodeKind::Path { .. } | NodeKind::Image(_) | NodeKind::Text(_) | NodeKind::SymbolInstance { .. }); let children = n.children().filter(|_| inside).into_iter().flatten().map(|c| &**c); let mask = n.extras().mask.as_deref().filter(|m| mask_too && m.linked).map(|m| &*m.art); children.chain(mask).collect() @@ -246,9 +332,11 @@ pub(crate) fn distorted_image_error(command: &str, id: vectorcraft_doc::NodeId) bad(command, format!("object {} is an image changed by Perspective Distort or Free Distort, which this command does not work on", id.0)) } -/// Why an image cannot follow the corners of a distort. +/// Why an image, type object or symbol instance cannot follow the corners of a distort. #[derive(Clone, Copy)] enum Unwarpable { + /// Type is being edited flat in Edit Text. + EditingFlat, /// Its corners would fold over, meet or fall on one line. NotConvex, /// A corner would cross the warp's horizon. @@ -257,14 +345,16 @@ enum Unwarpable { TooNarrow, } -/// The error of `object.distort` when image `id` cannot follow its corners. -fn unwarpable_error(id: vectorcraft_doc::NodeId, why: Unwarpable) -> EngineError { +/// The error of `object.distort` when object `id` (`kind`) cannot follow its corners. +fn unwarpable_error(id: vectorcraft_doc::NodeId, kind: Cornered, why: Unwarpable) -> EngineError { const C: &str = "object.distort"; + let noun = kind.noun(); match why { - Unwarpable::NotConvex => bad(C, format!("image {} cannot be distorted this way: its corners would not make a convex shape", id.0)), - Unwarpable::Horizon => bad(C, format!("image {} cannot be distorted this way: its corners would cross the warp's horizon", id.0)), + Unwarpable::EditingFlat => bad(C, format!("{noun} {} cannot be distorted this way: it is being edited flat in Edit Text", id.0)), + Unwarpable::NotConvex => bad(C, format!("{noun} {} cannot be distorted this way: its corners would not make a convex shape", id.0)), + Unwarpable::Horizon => bad(C, format!("{noun} {} cannot be distorted this way: its corners would cross the warp's horizon", id.0)), Unwarpable::TooNarrow => { - bad(C, format!("image {} cannot be distorted this way: its corners would be too close together for a perspective map", id.0)) + bad(C, format!("{noun} {} cannot be distorted this way: its corners would be too close together for a perspective map", id.0)) } } } @@ -311,25 +401,26 @@ fn distort(s: &mut Session, p: &Value) -> Result { return Ok(ids_json); } let pr = Projective::from_box(src, [tl, tr, br, bl]); - // An image's corners follow the handles exactly, so they must stay a convex shape: nothing - // changes when one would not. + // The corners of an image, a type object or a symbol instance follow the handles exactly, so + // they must stay a convex shape: nothing changes when one would not. let doc = &s.doc()?.doc; // Corners that do not make a convex shape give no perspective map (the warp falls back to an - // affine one), so an image cannot follow them. + // affine one), so such an object cannot follow them. if vectorcraft_doc::image_quad::check(&[tl, tr, br, bl]).is_err() - && let Some(id) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_image) + && let Some((id, kind)) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_cornered) { - return Err(unwarpable_error(id, Unwarpable::NotConvex)); + return Err(unwarpable_error(id, kind, Unwarpable::NotConvex)); } // Corners so close together that the map falls back to an affine one: the box's corners do - // not reach the handles, so an image cannot follow them either. + // not reach the handles, so such an object cannot follow them either. if !reaches_corners(src, [tl, tr, br, bl]) - && let Some(id) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_image) + && let Some((id, kind)) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_cornered) { - return Err(unwarpable_error(id, Unwarpable::TooNarrow)); + return Err(unwarpable_error(id, kind, Unwarpable::TooNarrow)); } - if let Some((id, why)) = ids.iter().filter_map(|id| doc.node(*id)).find_map(|n| unwarpable_image(n, &pr)) { - return Err(unwarpable_error(id, why)); + let symbols = doc.symbol_boxes(); + if let Some((id, kind, why)) = ids.iter().filter_map(|id| doc.node(*id)).find_map(|n| unwarpable(n, &pr, &symbols)) { + return Err(unwarpable_error(id, kind, why)); } s.edit("Free Distort", |d, _| { for id in &ids { diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index e5918d21e8..88c1b5e45e 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -59,11 +59,12 @@ //! A center outside the canvas after coordinate conversion throws a `RangeError`. //! - Members the help pages list that are not here yet throw an error that says so, and `reflect` //! leaves them out. -//! - Assigning `hidden`, `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an -//! object in a hidden or locked layer, and `zOrder()` on one, throw `Cannot edit` and change -//! nothing, even for the value the object has. The exception is `opacity` given the value the -//! object has when that changes nothing; on a graph's mark or label whose series or kind keeps -//! another opacity it would still change the graph, so it is refused too. Its `name` and `note` +//! - Assigning `hidden`, `locked`, `opacity`, `blendingMode`, `position`, `left`, `top`, `width` or +//! `height` to an object in a hidden or locked layer, and `zOrder()` on one, throw `Cannot edit` +//! and change nothing, even for the value the object has. The exception is `opacity` or +//! `blendingMode` given the value the object has when that changes nothing; on a graph's mark or +//! label whose series or kind keeps another opacity or blend mode it would still change the graph, +//! so it is refused too. Its `name` and `note` //! still change. An object that is hidden or locked itself, or is in a hidden or locked group, //! takes them. //! - `name` and `note` take a number or a Boolean as the text `String(value)` gives. @@ -81,6 +82,7 @@ use std::rc::Rc; use std::sync::Arc; use serde_json::{Value, json}; +use vectorcraft_color::BlendMode; use vectorcraft_geom::{Point, Rect}; use vectorcraft_js::{ ArgInfo, Data, HostClass, HostError, HostFunction, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref, host_ref_parts, @@ -305,8 +307,8 @@ fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo { } /// A member the help pages list that is not available yet: reading or assigning it throws, after -/// the check that a document, page item or text range `this` is still there. `hasOwnProperty` is false for it, -/// so a script that checks for the member first skips it, and `reflect` leaves it out. +/// the check that a document, page item or text range `this` is still there. `hasOwnProperty` is +/// false for it, so a script that checks for the member first skips it, and `reflect` leaves it out. fn later(link: &Link, class: &'static str, name: &'static str) -> Described { let message = format!("{class}.{name} is not available yet"); let l = link.clone(); @@ -2036,6 +2038,56 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)})) } +/// The members of `BlendModes` with the blend mode each one names. +const BLEND_MODES: [(&str, BlendMode); 16] = [ + ("COLORBLEND", BlendMode::Color), + ("COLORBURN", BlendMode::ColorBurn), + ("COLORDODGE", BlendMode::ColorDodge), + ("DARKEN", BlendMode::Darken), + ("DIFFERENCE", BlendMode::Difference), + ("EXCLUSION", BlendMode::Exclusion), + ("HARDLIGHT", BlendMode::HardLight), + ("HUE", BlendMode::Hue), + ("LIGHTEN", BlendMode::Lighten), + ("LUMINOSITY", BlendMode::Luminosity), + ("MULTIPLY", BlendMode::Multiply), + ("NORMAL", BlendMode::Normal), + ("OVERLAY", BlendMode::Overlay), + ("SATURATIONBLEND", BlendMode::Saturation), + ("SCREEN", BlendMode::Screen), + ("SOFTLIGHT", BlendMode::SoftLight), +]; + +fn item_blending_mode(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| { + let name = BLEND_MODES.iter().find(|(_, m)| *m == n.blend).map_or("NORMAL", |(name, _)| name); + Ok(text(format!("BlendModes.{name}"))) + }) +} + +/// `blendingMode = BlendModes.`: the object's own blend mode, as `object.setProps` sets it. +/// The mode the object already has may be assigned while its layer is hidden or locked, unless it +/// would still replace the blend mode a graph keeps for the item's series or kind. +fn item_set_blending_mode(h: &Host, a: &[Data]) -> Answer { + let mode = match arg(a, 1) { + Data::String(s) => s.strip_prefix("BlendModes.").and_then(|m| BLEND_MODES.iter().find(|(name, _)| *name == m)).map(|(_, mode)| *mode), + _ => None, + }; + let mode = mode.ok_or_else(|| HostError::Type("blendingMode needs a BlendModes value".into()))?; + let item = this_item(h, a)?; + let (same, keeps_other) = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + let same = d.node(item.id).is_some_and(|n| n.blend == mode); + let keeps_other = + crate::cmd::graph::series_object_opacity_differs(d, &[item.id]) || crate::cmd::graph::label_object_opacity_differs(d, &[item.id]); + (same, keeps_other) + }); + if !same || keeps_other { + refuse_protected_edit(h, item)?; + } + set_props(h, a, |_| false, json!({"blend": mode.label()})) +} + fn item_selected(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; Ok(Data::Bool(with_doc(h, item.doc, |_, st| st.selection.objects.contains(&item.id)))) @@ -2556,6 +2608,8 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } + let blend_modes = BLEND_MODES.iter().map(|(m, _)| (m.to_string(), HostItem::Value(text(format!("BlendModes.{m}"))))).collect(); + realm.define_host_object("BlendModes", blend_modes)?; variables::define_enums(realm)?; realm.define_host_classes(classes(link), vec![("app".into(), host_ref("Application", &[]))])?; let l = link; @@ -2715,6 +2769,7 @@ fn classes(link: &Link) -> Vec { ("locked", property(l, item_locked, item_set_locked), typed("boolean")), ("selected", property(l, item_selected, item_set_selected), typed("boolean")), ("opacity", property(l, item_opacity, item_set_opacity), MemberInfo { min: Some(0.0), max: Some(100.0), ..typed("number") }), + ("blendingMode", property(l, item_blending_mode, item_set_blending_mode), typed("BlendModes")), ("position", property(l, item_position, item_set_position), typed("Array")), ("left", property(l, item_left, item_set_left), typed("number")), ("top", property(l, item_top, item_set_top), typed("number")), @@ -2740,7 +2795,6 @@ fn classes(link: &Link) -> Vec { page_item.extend( [ "artworkKnockout", - "blendingMode", "isIsolated", "layer", "pixelAligned", diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index cc31e2b858..8d15f1b19e 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -191,7 +191,7 @@ type Spans = [(usize, usize)]; #[derive(Default)] pub(in crate::script) struct TextState { frames: RefCell>, - /// A document's uid, the document, and the ids of its type objects in paint order. + /// A document's uid, the document, and the ids of its type objects, topmost first. list: RefCell>, /// The fonts `app.textFonts` lists, as family and style, read once a run; a font a character /// names that is not installed is added at the end. @@ -334,12 +334,18 @@ fn usize_of(n: f64) -> Option { } /// A new object of `class` for the span `s..e` of the frame `item` at generation `stamp`. Each -/// object is numbered, so setting one range's `length` leaves every other range as it is. +/// object is numbered, so setting one range's `length` leaves every other range as it is. The +/// first five numbers are the frame's page item handle, so a range goes stale with its frame, +/// after `file.revert` too. fn range_ref(h: &Host, item: Item, s: usize, e: usize, stamp: u64, class: &str) -> Data { let [high, low] = id_parts(item.id); + let reverts = h.session.borrow().documents().get(item.doc.index).map_or(0, |d| d.reverts); let made = &h.dom.text.made; made.set(made.get() + 1); - host_ref(class, &[float(h.run), float(item.doc.uid), high, low, float(s as u64), float(e as u64), float(stamp), float(made.get())]) + host_ref( + class, + &[float(h.run), float(item.doc.uid), high, low, float(reverts), float(s as u64), float(e as u64), float(stamp), float(made.get())], + ) } /// The span `d` names, when it is an object of one of `classes`. @@ -350,15 +356,10 @@ fn span_of(h: &Host, d: &Data, classes: &[&str]) -> std::result::Result std::result::Result<(Span, u64), HostError> { let handle = classes.iter().find_map(|c| handle_of(d, c)); - let Some(&[run, uid, high, low, s, e, stamp, number]) = handle.as_deref() else { + let Some(&[run, uid, high, low, reverts, s, e, stamp, number]) = handle.as_deref() else { return Err(HostError::Type(format!("this is not a {}", classes.first().copied().unwrap_or("TextRange")))); }; - // A range outlives `file.revert` only to report itself stale through its edit log, so the - // frame is looked up at the document's current revert count. - let reverts = super::find_doc(h, run, uid) - .and_then(|doc| h.session.borrow().documents().get(doc.index).map(|st| st.reverts)) - .ok_or_else(|| HostError::Error(STALE_RANGE.into()))?; - let frame = item_of(h, &host_ref("TextFrame", &[run, uid, high, low, float(reverts)])).map_err(|_| HostError::Error(STALE_RANGE.into()))?; + let frame = item_of(h, &host_ref("TextFrame", &[run, uid, high, low, reverts])).map_err(|_| HostError::Error(STALE_RANGE.into()))?; let (Some(start), Some(end), Some(stamp), Some(number)) = (usize_of(s), usize_of(e), whole(stamp), whole(number)) else { return Err(HostError::Error(STALE_RANGE.into())); }; @@ -1228,7 +1229,8 @@ pub(super) fn doc_text_frames(link: &Link) -> HostMember { get(link, doc_text_frames_impl) } -/// The ids of the document's type objects in paint order, kept while the document is unchanged. +/// The ids of the document's type objects, topmost first as `pageItems` lists them, kept while the +/// document is unchanged. fn frame_ids(h: &Host, st: &DocState) -> Rc> { if let Some((uid, doc, ids)) = &*h.dom.text.list.borrow() && *uid == st.uid @@ -1671,8 +1673,8 @@ pub(super) fn classes(l: &Link) -> Vec { ("paragraphs", get(l, paragraphs), collection("Paragraphs")), ("characterAttributes", get(l, character_attributes), typed("CharacterAttributes")), ("paragraphAttributes", get(l, paragraph_attributes), typed("ParagraphAttributes")), - ("getParagraphLength", method(l, range_paragraph_length), returns("number", &[])), - ("getTextRunLength", method(l, range_run_length), returns("number", &[])), + ("getParagraphLength", method(l, range_paragraph_length), returns("number", &[("charIndex", "number")])), + ("getTextRunLength", method(l, range_run_length), returns("number", &[("charIndex", "number")])), ("remove", method(l, range_remove), returns("undefined", &[])), ]); range.extend(attr_members(l)); diff --git a/crates/engine/src/tests/large_edits.rs b/crates/engine/src/tests/large_edits.rs index 9fc02b0e88..0394fb18fa 100644 --- a/crates/engine/src/tests/large_edits.rs +++ b/crates/engine/src/tests/large_edits.rs @@ -788,3 +788,28 @@ fn deselecting_a_small_group_beside_a_large_one_takes_out_only_its_objects() { let fills = read() - before; assert!(fills <= 100, "read or took out {fills} fills"); } + +/// Taking a type object of 10,000 runs out of a selection that keeps two squares reads the two +/// squares' stroke weights again instead of taking the 10,000 run weights out of them. +#[test] +fn deselecting_type_of_many_runs_reads_the_objects_left() { + let mut s = session(3, |d, k| match k { + 0 => { + let style = vectorcraft_doc::CharStyle::default(); + let mut t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 40.0), "x", style.clone()); + t.runs = (0..10_000).map(|_| vectorcraft_doc::TextRun::new("x", style.clone())).collect(); + Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))) + } + _ => square(d, k), + }); + let ids = layer(&s, 0); + s.execute("select.none", &json!({})).unwrap(); + s.execute("select.add", &json!({"ids": ids.iter().map(|id| id.0).collect::>()})).unwrap(); + assert!(selected(&s, &ids)); + let read = || crate::cmd::WEIGHTS_READ.with(std::cell::Cell::get); + let before = read(); + s.execute("select.toggle", &json!({"id": ids[0].0})).unwrap(); + assert!(selected(&s, &ids[1..])); + let weights = read() - before; + assert!(weights <= 100, "read or took out {weights} stroke weights"); +} diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index a8fb54aada..9e840ddedf 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -394,6 +394,52 @@ fn an_opacity_a_graph_mark_already_has_replaces_the_one_its_series_keeps() { assert_eq!(kept(&s), None); } +/// A blend mode a graph mark or axis label already has still replaces the blend mode another object +/// of its series or kind left on the graph, and is refused in a hidden or locked layer. +#[test] +fn a_blend_mode_a_graph_mark_or_label_already_has_replaces_the_one_the_graph_keeps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4"; + let r = s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let spec = |s: &Session| s.active().unwrap().doc.node(id).unwrap().extras().graph.as_deref().unwrap().clone(); + let kept_mark = |s: &Session| spec(s).series_paints.first().and_then(|p| p.blend); + let kept_label = |s: &Session| spec(s).label_styles.values_rows.as_ref().and_then(|r| r.paint.blend); + let graph = s.active().unwrap().doc.node(id).unwrap().clone(); + let group = graph.children().unwrap().iter().find(|c| c.extras().series_index == Some(0)).unwrap().clone(); + let marks: Vec = group.children().unwrap().iter().map(|m| m.id).collect(); + let axes = graph.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Axes")).unwrap().clone(); + // The value axis numbers come first among the Axes group's labels. + let labels: Vec = axes.children().unwrap().iter().filter(|c| matches!(c.kind, NodeKind::Text(_))).map(|c| c.id).collect(); + s.execute("object.setProps", &json!({"id": marks[0].0, "blend": "Multiply"})).unwrap(); + s.execute("object.setProps", &json!({"id": labels[0].0, "blend": "Screen"})).unwrap(); + let both = (Some(vectorcraft_color::BlendMode::Multiply), Some(vectorcraft_color::BlendMode::Screen)); + assert_eq!((kept_mark(&s), kept_label(&s)), both); + s.execute("object.setProps", &json!({"id": marks[1].0, "name": "mark"})).unwrap(); + s.execute("object.setProps", &json!({"id": labels[1].0, "name": "label"})).unwrap(); + let layer = s.active().unwrap().doc.layers[0].id; + for (on, off) in [ + (json!({"ids": [layer.0], "visible": false}), json!({"ids": [layer.0], "visible": true})), + (json!({"ids": [layer.0], "locked": true}), json!({"ids": [layer.0], "locked": false})), + ] { + s.execute("object.setProps", &on).unwrap(); + for name in ["mark", "label"] { + let steps = undo_steps(&s); + let e = failure(&mut s, &format!("var m = app.activeDocument.pageItems.getByName('{name}'); m.blendingMode = m.blendingMode;")); + assert!(e.contains("Cannot edit"), "{on} {name}: {e}"); + assert_eq!((kept_mark(&s), kept_label(&s)), both, "{on} {name}"); + assert_eq!(undo_steps(&s), steps, "{on} {name}"); + } + s.execute("object.setProps", &off).unwrap(); + } + log( + &mut s, + "var p = app.activeDocument.pageItems; p.getByName('mark').blendingMode = BlendModes.NORMAL; p.getByName('label').blendingMode = BlendModes.NORMAL;", + ); + assert_eq!((kept_mark(&s), kept_label(&s)), (None, None)); +} + /// `app.redraw()` returns `undefined` and leaves the art and the undo history as they were. #[test] fn redraw_returns_and_changes_nothing() { @@ -431,6 +477,51 @@ fn assigning_the_reported_opacity_changes_nothing() { assert_eq!(undo_steps(&s), steps + 1); } +/// `blendingMode` reads and sets the object's own blend mode as a `BlendModes` value; the mode it +/// already has adds no undo step, and any other value throws and changes nothing. +#[test] +fn blending_mode_reads_and_sets_the_objects_blend_mode() { + let (mut s, a, b) = doc(); + let blend = |s: &Session, id: NodeId| s.active().unwrap().doc.node(id).unwrap().blend; + let steps = undo_steps(&s); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[1]; vc.log(i.blendingMode);\ + i.blendingMode = BlendModes.MULTIPLY; vc.log(i.blendingMode);\ + vc.log([i.hasOwnProperty('blendingMode'), BlendModes.SATURATIONBLEND, BlendModes.COLORBLEND]);", + ); + assert_eq!(out[..2], [json!("BlendModes.NORMAL"), json!("BlendModes.MULTIPLY")]); + assert_eq!(out[2], json!([true, "BlendModes.SATURATIONBLEND", "BlendModes.COLORBLEND"])); + assert_ne!(blend(&s, a), blend(&s, b), "only the assigned object changed"); + assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run"); + let (before, steps) = (blend(&s, a), undo_steps(&s)); + log(&mut s, "var i = app.activeDocument.pageItems[1]; i.blendingMode = BlendModes.MULTIPLY; i.blendingMode = i.blendingMode;"); + assert_eq!((blend(&s, a), undo_steps(&s)), (before, steps), "the mode the object has adds no step"); + // Two modes the help page names with a suffix set the modes the Transparency panel calls Color + // and Saturation. + log(&mut s, "var p = app.activeDocument.pageItems; p[1].blendingMode = BlendModes.COLORBLEND; p[0].blendingMode = BlendModes.SATURATIONBLEND;"); + assert_eq!((blend(&s, a).label(), blend(&s, b).label()), ("Color", "Saturation")); + let (before, steps) = (blend(&s, a), undo_steps(&s)); + for value in + ["'BlendModes.SCREEN '", "'MULTIPLY'", "'Multiply'", "'BlendModes.multiply'", "'BlendModes.NOPE'", "5", "null", "ZOrderMethod.BRINGTOFRONT"] + { + // The error is caught in the script, so the run does not roll back and the mode read right + // after it is the one the setter left. + let out = log( + &mut s, + &format!( + "var i = app.activeDocument.pageItems[1], e = '';\ + try {{ i.blendingMode = {value}; }} catch (x) {{ e = String(x); }}\ + vc.log(e); vc.log(i.blendingMode);" + ), + ); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("blendingMode needs a BlendModes value"), "{value}: {e}"); + assert_eq!(out[1], json!("BlendModes.COLORBLEND"), "{value}"); + assert_eq!((blend(&s, a), undo_steps(&s)), (before, steps), "{value}"); + } +} + #[test] fn selection_assignment_is_atomic_across_invalid_items() { let (mut s, a, b) = doc(); @@ -1138,13 +1229,13 @@ fn a_startup_preset_alone_gives_its_first_size() { fn page_item_members_not_built_yet_throw_on_read_and_assignment() { let (mut s, _, _) = doc(); for source in - ["app.activeDocument.pageItems[0].blendingMode;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"] + ["app.activeDocument.pageItems[0].isIsolated;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"] { assert!(failure(&mut s, source).contains("is not available yet"), "{source}"); } assert!(failure(&mut s, "app.activeDocument.layers = 1;").contains("Document.layers is not available yet")); // A deleted item or an earlier run's document is stale first. - let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.blendingMode;"); + let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.isIsolated;"); assert!(e.contains("Stale page item"), "{e}"); run(&mut s, "#targetengine keep\nvar d = app.activeDocument;").unwrap(); let e = failure(&mut s, "#targetengine keep\nd.layers;"); @@ -1923,7 +2014,7 @@ fn unsupported_members_say_so() { /// A script that names each visible selected object after its place in `app.selection`, testing /// the members it uses with `hasOwnProperty` and `propertyIsEnumerable` first. A member that is not -/// available yet, such as `blendingMode`, is read only when `hasOwnProperty` reports it, so it is +/// available yet, such as `isIsolated`, is read only when `hasOwnProperty` reports it, so it is /// never read. const NAME_PICKED: &str = "\ var picked = app.selection, k = picked.length, named = 0;\ @@ -1931,7 +2022,7 @@ const NAME_PICKED: &str = "\ while (k--) {\ var obj = picked[k];\ var usable = obj.propertyIsEnumerable('name') && obj.hasOwnProperty('hidden') && !obj.hidden;\ - if (obj.hasOwnProperty('blendingMode') && obj.blendingMode) usable = false;\ + if (obj.hasOwnProperty('isIsolated') && obj.isIsolated) usable = false;\ if (usable) { obj.name = 'picked ' + k; named += 1; }\ }\ if (picked.length && named < picked.length) alert('Some objects were skipped.');"; @@ -2010,9 +2101,9 @@ fn page_items_report_their_available_members_as_their_own() { vc.log([p.hasOwnProperty('opacity'), p.hasOwnProperty('typename'), p.hasOwnProperty('duplicate'),\ Object.prototype.hasOwnProperty.call(p, 'name'), p.propertyIsEnumerable('opacity'), d.hasOwnProperty('selection'),\ app.hasOwnProperty('activeDocument')]);\ - vc.log([p.hasOwnProperty('blendingMode'), p.hasOwnProperty('rotate'), d.hasOwnProperty('layers'),\ + vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('rotate'), d.hasOwnProperty('layers'),\ p.hasOwnProperty('nosuch'), p.hasOwnProperty('hasOwnProperty'), p.hasOwnProperty('constructor')]);\ - vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('blendingMode')]);", + vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('isIsolated')]);", ); assert_eq!(out[0], json!([true, true, true, true, true, true, true])); // Members that are not available yet, unknown names and inherited ones are not the object's own. @@ -2141,7 +2232,7 @@ fn a_collection_read_with_a_name_gives_the_named_object() { assert_eq!(out, vec![json!([true, "n", true, false, true]), json!([true, true, false]), json!(["Not found", "Not found"])]); } -/// `opacity`, `hidden`, `locked` and the position and size setters on an object in a hidden or +/// `opacity`, `blendingMode`, `hidden`, `locked` and the position and size setters on an object in a hidden or /// locked layer throw and the run changes nothing, while its name and note still change; an object /// that is hidden or locked itself takes them. #[test] @@ -2161,6 +2252,7 @@ fn setters_refuse_art_in_a_hidden_or_locked_layer() { // `hidden` and `locked` are refused even when the value is the one the object has. for set in [ "opacity = 50", + "blendingMode = BlendModes.MULTIPLY", "hidden = true", "hidden = false", "locked = true", @@ -2182,9 +2274,9 @@ fn setters_refuse_art_in_a_hidden_or_locked_layer() { let out = log( &mut s, "var c = app.activeDocument.pageItems.getByName('closed'); c.note = 'n'; c.name = 'renamed'; c.opacity = c.opacity;\ - vc.log([c.name, c.note, c.opacity]); c.name = 'closed'; c.note = '';", + c.blendingMode = c.blendingMode; vc.log([c.name, c.note, c.opacity, c.blendingMode]); c.name = 'closed'; c.note = '';", ); - assert_eq!(out, vec![json!(["renamed", "n", 100])], "{on}"); + assert_eq!(out, vec![json!(["renamed", "n", 100, "BlendModes.NORMAL"])], "{on}"); s.execute("object.setProps", &off).unwrap(); } s.execute("object.setProps", &json!({"ids": [a.0], "locked": true})).unwrap(); @@ -2192,9 +2284,11 @@ fn setters_refuse_art_in_a_hidden_or_locked_layer() { let out = log( &mut s, "var p = app.activeDocument.pageItems; p.getByName('locked').opacity = 50; p.getByName('free').opacity = 40;\ - vc.log([p.getByName('locked').opacity, p.getByName('free').opacity]);", + p.getByName('locked').blendingMode = BlendModes.SCREEN; p.getByName('free').blendingMode = BlendModes.DARKEN;\ + vc.log([p.getByName('locked').opacity, p.getByName('free').opacity, p.getByName('locked').blendingMode,\ + p.getByName('free').blendingMode]);", ); - assert_eq!(out, vec![json!([50, 40])]); + assert_eq!(out, vec![json!([50, 40, "BlendModes.SCREEN", "BlendModes.DARKEN"])]); } /// `name` takes a number or a Boolean as the text `String` gives it, and nothing else. diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 0272e95212..184f43cc4a 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -182,7 +182,7 @@ fn failed_script_report_keeps_message_and_adds_origin() { ("throw new Error('invalid array length');", "thrown", "Error: invalid array length", "script"), ("throw new RangeError('invalid array length');", "thrown", "RangeError: invalid array length", "script"), ("throw 'invalid array length';", "thrown", "invalid array length", "script"), - ("throw 'ReferenceError: Window is not defined';", "thrown", "ReferenceError: Window is not defined", "script"), + ("throw 'ReferenceError: BridgeTalk is not defined';", "thrown", "ReferenceError: BridgeTalk is not defined", "script"), ("try { new Array(-1); } catch (e) { throw new Error(e.message); }", "thrown", "Error: invalid array length", "script"), ("new Array(-1);", "thrown", "RangeError: invalid array length", "built-in"), ("try { new Array(-1); } catch (e) { throw e; }", "thrown", "RangeError: invalid array length", "built-in"), diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 385ef23028..0a71638c92 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -56,18 +56,22 @@ fn text_frames_add_point_area_and_path_type() { let out = log( &mut s, "var d = app.activeDocument, p = d.pageItems;\ - var area = d.textFrames.areaText(p[0]); area.contents = 'Area';\ - var path = d.textFrames.pathText(p[1]); path.contents = 'Path';\ + var area = d.textFrames.areaText(p[1]); area.contents = 'Area';\ + var path = d.textFrames.pathText(p[0]); path.contents = 'Path';\ var pt = d.textFrames.add(); pt.contents = 'Point';\ var at = d.textFrames.pointText([30, 40]); at.contents = 'At';\ vc.log(d.textFrames.length); vc.log([area.kind, path.kind, pt.kind]);\ vc.log(pt.typename); vc.log(pt instanceof TextFrame && pt instanceof PageItem);\ - vc.log(d.textFrames[0].contents); vc.log(d.textFrames[9] === undefined);\ + vc.log([d.textFrames[0].contents, d.textFrames[3].contents]); vc.log(d.textFrames[9] === undefined);\ vc.log(at.orientation); vc.log(d.textFrames.parent.typename);", ); assert_eq!(out[0], json!(4)); assert_eq!(out[1], json!(["TextType.AREATEXT", "TextType.PATHTEXT", "TextType.POINTTEXT"])); - assert_eq!(out[2..], [json!("TextFrame"), json!(true), json!("At"), json!(true), json!("TextOrientation.HORIZONTAL"), json!("Document")]); + // Topmost first, as `pageItems` lists them: the newest type, then the area type on the rectangle. + assert_eq!( + out[2..], + [json!("TextFrame"), json!(true), json!(["At", "Area"]), json!(true), json!("TextOrientation.HORIZONTAL"), json!("Document")] + ); assert_eq!(undo_steps(&s), before + 1); // A path of another kind, or no path, is refused. assert!(failure(&mut s, "app.activeDocument.textFrames.areaText(app.activeDocument.textFrames[0]);").contains("PathItem")); @@ -174,6 +178,29 @@ fn ranges_made_before_file_revert_go_stale_even_when_the_text_is_the_same() { assert_eq!(out[2], json!("two"), "a range made after the revert reads the reverted text"); } +#[test] +fn a_frame_and_its_ranges_held_across_file_revert_go_stale() { + let (mut s, _) = doc_with("one two"); + let path = std::env::temp_dir().join(format!("vc-text-revert-held-{}.vectorcraft", std::process::id())); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.textRange, w = t.words;\ + vc.run('shape.rectangle', {x: 1, y: 1, width: 5, height: 5}); vc.run('file.revert', {});\ + try { vc.log(t.contents); } catch (e) { vc.log(e.message); }\ + try { vc.log(r.contents); } catch (e) { vc.log(e.message); }\ + try { vc.log(w.length); } catch (e) { vc.log(e.message); }\ + var now = app.activeDocument.textFrames[0], r2 = now.textRange;\ + vc.log(r2.contents); r2.contents = 'three'; vc.log(now.contents);", + ); + let _ = std::fs::remove_file(&path); + assert!(out[0].as_str().is_some_and(|m| m.contains("Stale page item")), "{out:?}"); + assert!(out[1].as_str().is_some_and(|m| m.contains("Stale text range")), "{out:?}"); + assert!(out[2].as_str().is_some_and(|m| m.contains("Stale text range")), "{out:?}"); + assert_eq!(out[3], json!("one two"), "a range made after the revert reads the reverted text"); + assert_eq!(out[4], json!("three"), "a frame found after the revert can be edited"); +} + #[test] fn a_range_an_edit_covers_holds_the_edits_new_text() { let (mut s, _) = doc_with("abc"); @@ -516,6 +543,7 @@ fn collections_of_text_add_words_characters_and_paragraphs() { let (mut s, id) = doc_with("ab"); s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap(); let before = undo_steps(&s); + // `textFrames` lists the topmost first, so the newer "other" is [0]. let out = log(&mut s, "var n = app.activeDocument.textFrames[0].words.add(''); vc.log([n.length, n.start]);"); assert_eq!(out, vec![json!([0, 5])]); for (call, want) in [ diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index fb0add5be3..ea3142e6cc 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -1234,6 +1234,166 @@ fn distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_recor assert_eq!(undo_len(&s), undo); } +/// A type object or (`symbol`) a symbol instance made of a 100 × 60 rectangle, selected alone. +fn type_or_instance(s: &mut Session, symbol: bool) -> NodeId { + let r = if symbol { + rect(s, 20.0, 30.0, 100.0, 60.0); + s.execute("symbol.new", &json!({"name": "Box"})).unwrap() + } else { + s.execute("text.create", &json!({"x": 20, "y": 80, "text": "Distort", "size": 40})).unwrap() + }; + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + id +} + +/// Where the corners of `id`'s box are drawn (top left, top right, bottom right, bottom left). +fn drawn_corners(s: &Session, id: NodeId) -> [Point; 4] { + let doc = &s.doc().unwrap().doc; + doc.node(id).unwrap().drawn_corners(&doc.symbol_boxes()).unwrap() +} + +fn assert_near_corners(got: [Point; 4], want: [Point; 4]) { + for (g, w) in got.iter().zip(want) { + assert!(g.distance(w) < 1e-6, "{got:?} against {want:?}"); + } +} + +/// Perspective Distort and Free Distort put the corners of a type object's box and of a symbol +/// instance's box exactly on the handles, in one undo step: the object stays type or an instance, +/// drawn through the warp, it is bounded by those corners, a move takes them along, and undo gives +/// back the flat object. +#[test] +fn distort_puts_the_corners_of_type_and_symbol_instances_on_the_handles() { + // Perspective Distort, then Free Distort, as fractions of the box. + let quads = [[(0.4, 0.0), (0.6, 0.0), (1.0, 1.0), (0.0, 1.0)], [(0.1, 0.05), (0.9, 0.0), (1.2, 1.1), (0.0, 1.0)]]; + for symbol in [false, true] { + for quad in quads { + let mut s = session(); + let id = type_or_instance(&mut s, symbol); + let b = bounds(&s, id); + let flat = [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)].map(|(x, y)| Point::new(x, y)); + assert_near_corners(drawn_corners(&s, id), flat); + let want = quad.map(|(u, v)| Point::new(b.x0 + u * b.width(), b.y0 + v * b.height())); + let undo = undo_len(&s); + s.execute("object.distort", &json!({ "corners": want.map(|p| [p.x, p.y]) })).unwrap(); + assert_eq!(undo_len(&s), undo + 1); + assert_near_corners(drawn_corners(&s, id), want); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(matches!(n.kind, vectorcraft_doc::NodeKind::Text(_) | vectorcraft_doc::NodeKind::SymbolInstance { .. }), "{:?}", n.kind); + assert!(n.projection().is_some()); + let got = bounds(&s, id); + let (xs, ys) = (want.map(|p| p.x), want.map(|p| p.y)); + let near = |a: f64, b: f64| (a - b).abs() < 1e-6; + assert!( + near(got.x0, xs.iter().copied().fold(f64::MAX, f64::min)) && near(got.x1, xs.iter().copied().fold(f64::MIN, f64::max)), + "{got:?}" + ); + assert!( + near(got.y0, ys.iter().copied().fold(f64::MAX, f64::min)) && near(got.y1, ys.iter().copied().fold(f64::MIN, f64::max)), + "{got:?}" + ); + s.execute("object.move", &json!({"dx": 10, "dy": 20})).unwrap(); + assert_near_corners(drawn_corners(&s, id), want.map(|p| p + Vec2::new(10.0, 20.0))); + // Distorted type opens flat in Edit Text. + assert_eq!(s.execute("perspective.editText", &json!({"id": id.0})).is_ok(), !symbol); + if !symbol { + assert!(s.doc().unwrap().doc.node(id).unwrap().projection().is_none()); + s.execute("object.exitIsolation", &json!({})).unwrap(); + assert_near_corners(drawn_corners(&s, id), want.map(|p| p + Vec2::new(10.0, 20.0))); + } + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + if !symbol { + s.execute("edit.undo", &json!({})).unwrap(); + } + assert!(s.doc().unwrap().doc.node(id).unwrap().projection().is_none()); + assert_near_corners(drawn_corners(&s, id), flat); + } + } +} + +/// Distorted together with paths, the corners of a type object's box and of a symbol instance's +/// box follow the same warp as the anchors of a path drawn on that box. +#[test] +fn distort_moves_type_and_symbol_instances_with_a_path_as_one() { + for symbol in [false, true] { + let mut s = session(); + let id = type_or_instance(&mut s, symbol); + let b = bounds(&s, id); + // A path on the object's box, and one beside it so that the box is not the selection's. + let frame = rect(&mut s, b.x0, b.y0, b.width(), b.height()); + let side = rect(&mut s, b.x1 + 50.0, b.y0 - 40.0, 80.0, 80.0); + s.execute("select.set", &json!({"ids": [id.0, frame.0, side.0]})).unwrap(); + let all = s.doc().unwrap().doc.bounds_of(&[id, frame, side], false).unwrap(); + let corners = [[all.x0 + 30.0, all.y0], [all.x1 - 10.0, all.y0 + 20.0], [all.x1 + 40.0, all.y1], [all.x0, all.y1 - 5.0]]; + s.execute("object.distort", &json!({ "corners": corners })).unwrap(); + let anchors = match &s.doc().unwrap().doc.node(frame).unwrap().kind { + vectorcraft_doc::NodeKind::Path { path, .. } => path.subpaths[0].anchors.iter().map(|a| a.p).collect::>(), + k => panic!("not a path: {k:?}"), + }; + let got = drawn_corners(&s, id); + // The rectangle's first anchor may be any of its corners: each drawn corner is one of them. + for c in got { + assert!(anchors.iter().any(|p| p.distance(c) < 1e-6), "{got:?} against {anchors:?}"); + } + } +} + +/// Corners that would carry a type object's or a symbol instance's box past the warp's horizon, +/// or fold it over, are refused, and nothing changes. +#[test] +fn distort_refuses_corners_type_and_symbol_instances_cannot_follow() { + for symbol in [false, true] { + let mut s = session(); + let id = type_or_instance(&mut s, symbol); + let noun = if symbol { "symbol instance" } else { "type object" }; + let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s)); + // The box (0, 0)-(10, 10) widens toward its bottom so fast that the warp's horizon lies at + // y = 15, across the object. + let e = + s.execute("object.distort", &json!({"from": [0, 0, 10, 10], "corners": [[0, 0], [10, 0], [20, 10], [-10, 10]]})).unwrap_err().to_string(); + assert!(e.contains(&format!("{noun} {}", id.0)) && e.contains("horizon"), "{e}"); + let b = bounds(&s, id); + let folded = [[b.x0, b.y0], [b.x1, b.y1], [b.x1, b.y0], [b.x0, b.y1]]; + let e = s.execute("object.distort", &json!({ "corners": folded })).unwrap_err().to_string(); + assert!(e.contains(&format!("{noun} {}", id.0)) && e.contains("convex"), "{e}"); + assert_eq!(s.doc().unwrap().doc, before); + assert_eq!(undo_len(&s), undo); + // Near the edge of the canvas, the corners still reach the handles. + s.execute("object.move", &json!({"dx": 0, "dy": 3.9e6})).unwrap(); + let b = bounds(&s, id); + let want = [(0.4, 0.0), (0.6, 0.0), (1.0, 1.0), (0.0, 1.0)].map(|(u, v)| Point::new(b.x0 + u * b.width(), b.y0 + v * b.height())); + s.execute("object.distort", &json!({ "corners": want.map(|p| [p.x, p.y]) })).unwrap(); + let got = drawn_corners(&s, id); + assert!(got.iter().zip(want).all(|(g, w)| g.distance(w) < 1e-3), "{got:?} against {want:?}"); + } +} + +/// Projective distort refuses type being edited flat without changing the document or history; +/// the same warp works after Edit Text ends. +#[test] +fn distort_refuses_type_being_edited_flat() { + let mut s = session(); + let id = type_or_instance(&mut s, false); + let b = bounds(&s, id); + let corners = [(0.2, 0.0), (0.8, 0.0), (1.0, 1.0), (0.0, 1.0)].map(|(u, v)| [b.x0 + u * b.width(), b.y0 + v * b.height()]); + let p = json!({"ids": [id.0], "from": [b.x0, b.y0, b.x1, b.y1], "corners": corners}); + s.execute("object.distort", &p).unwrap(); + s.execute("perspective.editText", &json!({"id": id.0})).unwrap(); + let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s)); + let e = s.execute("object.distort", &p).unwrap_err().to_string(); + assert!(e.contains("object.distort") && e.contains(&format!("type object {}", id.0)) && e.contains("being edited flat in Edit Text"), "{e}"); + assert_eq!(s.doc().unwrap().doc, before); + assert_eq!(undo_len(&s), undo); + s.execute("object.exitIsolation", &json!({})).unwrap(); + let before = drawn_corners(&s, id); + let undo = undo_len(&s); + s.execute("object.distort", &p).unwrap(); + assert_ne!(drawn_corners(&s, id), before); + assert_eq!(undo_len(&s), undo + 1); +} + /// Image info gives a distorted image's resolution at its middle, not the resolution it had /// before the distort. #[test] diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index da3ea830aa..0b20de0e23 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -81,7 +81,7 @@ const INSIDE: &[(&str, &str)] = &[ ), ( "", - "activeDocument activeDocument= app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \ + "activeDocument activeDocument= app Application BlendModes CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \ DocumentPreset DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents \ Documents ElementPlacement Layer PageItem PageItems RulerUnits ScreenMode selection selection= Tag Tags View Views \ ZOrderMethod", @@ -132,6 +132,11 @@ const INSIDE: &[(&str, &str)] = &[ ("Tags.prototype.", "add constructor getByName index length parent removeAll typename"), ("Tag.", "prototype"), ("Tag.prototype.", "constructor name name= parent remove typename value value="), + ( + "BlendModes.", + "COLORBLEND COLORBURN COLORDODGE DARKEN DIFFERENCE EXCLUSION HARDLIGHT HUE LIGHTEN LUMINOSITY MULTIPLY NORMAL \ + OVERLAY SATURATIONBLEND SCREEN SOFTLIGHT", + ), ("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"), ("DocumentArtboardLayout.", "Column GridByCol GridByRow RLGridByCol RLGridByRow RLRow Row"), ("DocumentColorSpace.", "CMYK RGB"), diff --git a/crates/engine/tests/plugin_import.rs b/crates/engine/tests/plugin_import.rs index 9bf9b87f0d..11a42a6f90 100644 --- a/crates/engine/tests/plugin_import.rs +++ b/crates/engine/tests/plugin_import.rs @@ -273,7 +273,7 @@ fn failures_open_nothing() { ("test.fail.notjson", "not json", "JSON"), ("test.fail.empty", r#"{"objects":[]}"#, "the importer returned no objects"), ("test.fail.key", r#"{"objects":[],"layers":[]}"#, "an importer returns `objects` and `warnings`, not `layers`"), - ("test.fail.id", r#"{"objects":[{"id":3}]}"#, "is not the id of an input object"), + ("test.fail.id", r#"{"objects":[{"id":3}]}"#, "an importer returns new paths without `id`"), ("test.fail.far", far, "4000000"), ("test.fail.warnings", bad_warnings.as_str(), "`warnings` must be a list of strings"), ]; @@ -441,3 +441,161 @@ fn a_built_in_file_past_the_input_limit_still_opens() { assert_eq!(s.execute("document.open", &encoded).unwrap()["format"], "png"); let _ = std::fs::remove_dir_all(&dir); } + +/// An importer at plug-in API level 4 `id` reading `.trc` files, listing `kinds` (a JSON list) in +/// `outputKinds`, whose output is the file it is given. +fn rich_echo(s: &mut Session, id: &str, kinds: &str) -> Value { + let manifest = + format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"importer","api":4,"extensions":["trc"],"outputKinds":{kinds}}}"#); + install(s, &tpl::module(&manifest, tpl::ECHO, "", 1)) +} + +/// The pixels of a 2 × 1 image: opaque red, then half-transparent blue. +const PIXELS: [u8; 8] = [255, 0, 0, 255, 0, 0, 255, 128]; + +/// Rich importer output: type, the image of [`PIXELS`] and the rectangle of [`RECT`], with two +/// layers (the image and the rectangle in "Art", the type in the hidden, locked "Words") and two +/// artboards. +fn rich_output() -> Value { + let rect: Value = serde_json::from_str(RECT).unwrap(); + json!({ + "objects": [ + {"type": "type", "text": "Hello\nWorld", "fontFamily": "No Such Family Q9617", "fontSize": 24, + "fill": {"type": "solid", "color": {"model": "rgb", "r": 0, "g": 0, "b": 1}}, "transform": [1, 0, 0, 1, 10, 40], "name": "Title"}, + {"type": "image", "pixelSize": [2, 1], "pixelsBase64": vectorcraft_format::base64_encode(&PIXELS), "transform": [10, 0, 0, 10, 0, 100]}, + rect["objects"][0], + ], + "layers": [{"name": "Art", "objects": [1, 2]}, {"name": "Words", "visible": false, "locked": true, "objects": [0]}], + "artboards": [{"name": "Front", "rect": [0, 0, 200, 100]}, {"name": "Back", "rect": [220, 0, 200, 100]}], + "warnings": ["from the importer"], + }) +} + +/// The active document's layers (name, shown, locked, kinds of its objects), its artboards (name +/// and rectangle), its type (text, family, size, fill), the RGBA of its first image, and the transforms +/// of its text and images. +#[allow(clippy::type_complexity)] +fn structure( + s: &Session, +) -> (Vec<(String, bool, bool, Vec<&'static str>)>, Vec<(String, [f64; 4])>, Vec<(String, String, f64, String)>, Vec, Vec<(&'static str, [f64; 6])>) +{ + let d = &s.doc().unwrap().doc; + let kind = |n: &vectorcraft_doc::Node| match &n.kind { + vectorcraft_doc::NodeKind::Text(_) => "type", + vectorcraft_doc::NodeKind::Image(_) => "image", + vectorcraft_doc::NodeKind::Path { .. } => "path", + _ => "other", + }; + let layers = d + .layers + .iter() + .map(|l| (l.name.clone().unwrap_or_default(), l.visible, l.locked, l.children().unwrap().iter().map(|c| kind(c)).collect())) + .collect(); + let boards = d.artboards.iter().map(|a| (a.name.clone(), [a.rect.x0, a.rect.y0, a.rect.x1, a.rect.y1])).collect(); + let (mut types, mut pixels, mut transforms) = (Vec::new(), Vec::new(), Vec::new()); + d.walk(|n| match &n.kind { + vectorcraft_doc::NodeKind::Text(t) => { + transforms.push(("type", t.xf.as_coeffs())); + let st = &t.runs[0].style; + let text: String = t.runs.iter().map(|r| r.text.as_str()).collect(); + types.push((text, st.font_family.clone(), st.size, serde_json::to_string(&st.fill).unwrap())); + } + vectorcraft_doc::NodeKind::Image(im) => { + transforms.push(("image", im.xf.as_coeffs())); + // Read back through the filter input's own decoder, not the importer's. + if pixels.is_empty() { + let o = vectorcraft_plugins::objects::encode_read_only(d, n).unwrap(); + pixels = vectorcraft_format::base64_decode(o["pixelsBase64"].as_str().unwrap()).unwrap(); + } + } + _ => {} + }); + (layers, boards, types, pixels, transforms) +} + +/// An importer at API level 4 that lists every output kind opens editable type, an embedded image, +/// paths, layers and artboards as it returned them; the artboards replace the one around the art, +/// a missing font is reported with the importer's warnings, and the document saves and opens again +/// in the native format with all of it. +#[test] +fn an_api_4_importer_opens_type_images_layers_and_artboards() { + let mut s = Session::new(); + let entry = rich_echo(&mut s, "test.rich", r#"["type","image","layer","artboard"]"#); + assert_eq!((&entry["api"], &entry["outputKinds"]), (&json!(4), &json!(["type", "image", "layer", "artboard"]))); + assert_eq!(entry["permissions"], json!(["import.read"])); + let r = open(&mut s, "Rich.trc", rich_output().to_string().as_bytes(), json!({})).unwrap(); + let warnings = r["warnings"].as_array().unwrap(); + assert_eq!(warnings.first(), Some(&json!("from the importer"))); + assert!(warnings.iter().any(|w| w.as_str().unwrap().contains("No Such Family Q9617")), "{warnings:?}"); + let opened = structure(&s); + let blue = serde_json::to_string(&vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))).unwrap(); + assert_eq!(opened.0, [("Art".to_string(), true, false, vec!["image", "path"]), ("Words".to_string(), false, true, vec!["type"])]); + assert_eq!(opened.1, [("Front".to_string(), [0.0, 0.0, 200.0, 100.0]), ("Back".to_string(), [220.0, 0.0, 420.0, 100.0])]); + assert_eq!(opened.2, [("Hello\nWorld".to_string(), "No Such Family Q9617".to_string(), 24.0, blue)]); + assert_eq!(opened.3, PIXELS); + assert_eq!(opened.4, [("image", [10.0, 0.0, 0.0, 10.0, 0.0, 100.0]), ("type", [1.0, 0.0, 0.0, 1.0, 10.0, 40.0])]); + // The type is laid out at the place the transform gives: its first baseline starts at (10, 40). + let d = &s.doc().unwrap().doc; + let words = d.layers[1].children().unwrap()[0].clone(); + let b = d.bounds_of(&[words.id], false).unwrap(); + assert!(b.x0 >= 9.0 && b.x0 < 12.0 && b.y0 < 40.0 && b.y1 > 40.0, "{b:?}"); + + let native = fileio::encode(&s.doc().unwrap().doc, "vectorcraft", &json!({})).unwrap(); + open(&mut s, "Again.vectorcraft", &native, json!({})).unwrap(); + assert_eq!(structure(&s), opened, "saved and opened again"); +} + +/// An importer at API level 4 that lists only some kinds: output with another kind, a malformed +/// image, a bad layer, or an image or type that reaches past the canvas opens nothing and leaves the open document as it was; a blank document of +/// artboards alone opens. +#[test] +fn rich_output_that_fails_its_checks_changes_nothing() { + let mut s = Session::new(); + rich_echo(&mut s, "test.richsome", r#"["type","image","layer"]"#); + let before = open_edited(&mut s, "test.richsome.edited"); + let mut short = rich_output(); + short["objects"][1]["pixelsBase64"] = json!(vectorcraft_format::base64_encode(&PIXELS[..4])); + let mut twice = rich_output(); + twice["layers"][1]["objects"] = json!([0, 2]); + let mut wide = rich_output(); + wide["objects"][1]["transform"] = json!([4000000, 0, 0, 1, 0, 0]); + let mut far = rich_output(); + far["objects"][0]["transform"] = json!([1, 0, 0, 1, 4000000, 40]); + let cases = [ + (rich_output(), "`artboard`"), + (short, "= 8 bytes"), + (twice, "exactly one layer"), + (wide, "objects[1]: it reaches more than 4000000 pt"), + (far, "objects[0]: it reaches more than 4000000 pt"), + (json!({"objects": [], "layers": [{"name": "A\u{202E}B"}]}), "text direction"), + ]; + for (mut output, says) in cases { + if says != "`artboard`" { + output.as_object_mut().unwrap().remove("artboards"); + } + let e = open(&mut s, "x.trc", output.to_string().as_bytes(), json!({"importer": "plugin.test.richsome"})).unwrap_err(); + assert!(e.to_string().contains(says) && e.to_string().contains("x.trc"), "{says}: {e}"); + assert_eq!(state(&mut s), before, "{says}"); + } + rich_echo(&mut s, "test.richboards", r#"["artboard"]"#); + let blank = json!({"objects": [], "artboards": [{"name": "Only", "rect": [0, 0, 50, 60]}]}); + open(&mut s, "Blank.trc", blank.to_string().as_bytes(), json!({"importer": "plugin.test.richboards"})).unwrap(); + let (layers, boards, types, _, _) = structure(&s); + assert_eq!((layers.len(), layers[0].3.len(), boards, types.len()), (1, 0, vec![("Only".to_string(), [0.0, 0.0, 50.0, 60.0])], 0)); +} + +/// An importer below API level 4 reads paths alone, as it always has: type is not a path, and it +/// can't return layers. +#[test] +fn an_older_importer_reads_paths_alone() { + let mut s = Session::new(); + echo(&mut s, "test.older", r#"["tol"]"#); + let e = open(&mut s, "x.tol", rich_output().to_string().as_bytes(), json!({})).unwrap_err(); + assert!(e.to_string().contains("an importer returns `objects` and `warnings`, not `"), "{e}"); + let typed = json!({"objects": [rich_output()["objects"][0]]}); + let e = open(&mut s, "x.tol", typed.to_string().as_bytes(), json!({})).unwrap_err(); + assert!(e.to_string().contains("`type` must be \"path\" or \"compound\""), "{e}"); + assert!(s.documents().is_empty()); + open(&mut s, "Shapes.tol", RECT.as_bytes(), json!({})).unwrap(); + assert_eq!((objects(&s), artboard(&s), s.doc().unwrap().doc.layers.len()), (1, (10.0, 20.0, 110.0, 70.0), 1)); +} diff --git a/crates/engine/tests/plugin_place.rs b/crates/engine/tests/plugin_place.rs index e5996c7a36..c15982cd07 100644 --- a/crates/engine/tests/plugin_place.rs +++ b/crates/engine/tests/plugin_place.rs @@ -58,6 +58,56 @@ fn state(s: &mut Session) -> (usize, usize, usize, Value) { (d.history.undo.len(), d.history.redo.len(), d.doc.layers.len(), content) } +#[test] +fn placing_importer_checks_the_transformed_bounds_before_editing() { + let image = json!({"objects": [{ + "type": "image", "pixelSize": [1, 1], "pixelsBase64": vectorcraft_format::base64_encode(&[255, 0, 0, 255]), + "transform": [20, 0, 0, 10, 0, 0], + }]}) + .to_string(); + for (index, output, half_width) in [(0, ART, 50.0), (1, image.as_str(), 10.0)] { + let mut s = with_document(); + let mut manifest: Value = serde_json::from_str(&placing(&format!("test.place.canvas{index}"), r#"["tpc"]"#)).unwrap(); + if index == 1 { + manifest["api"] = json!(4); + manifest["outputKinds"] = json!(["image"]); + } + install(&mut s, &tpl::returning(&manifest.to_string(), output)); + let importer = format!("plugin.test.place.canvas{index}"); + let before = state(&mut s); + for at in [[4_000_000.0, 400.0], [-4_000_000.0, 400.0], [400.0, 4_000_000.0], [400.0, -4_000_000.0]] { + for template in [false, true] { + assert!( + place(&mut s, "Art.tpc", b"?", json!({"at": at, "template": template, "importer": importer})).is_err(), + "{index}: {at:?}, template: {template}" + ); + assert_eq!(state(&mut s), before); + } + } + let inside = place(&mut s, "Art.tpc", b"?", json!({"at": [4_000_000.0 - half_width, 400.0], "importer": importer})); + assert!(inside.is_ok(), "{index}: {inside:?}"); + assert_eq!(s.doc().unwrap().history.undo.len(), before.0 + 1); + } +} + +#[test] +fn cropped_svg_placement_checks_art_outside_its_frame_before_editing() { + let svg = br#""#; + for at in [[3_999_940.0, 400.0], [-3_999_940.0, 400.0], [400.0, 3_999_940.0], [400.0, -3_999_940.0]] { + for template in [false, true] { + let mut s = with_document(); + let before = state(&mut s); + assert!( + place(&mut s, "cropped.svg", svg, json!({"at": at, "crop": "crop", "template": template})).is_err(), + "{at:?}, template: {template}" + ); + assert_eq!(state(&mut s), before); + } + } + let mut s = with_document(); + assert!(place(&mut s, "cropped.svg", svg, json!({"at": [3_999_930.0, 400.0], "crop": "crop"})).is_ok()); +} + /// A placed group: its name, the names of its children, and its bounds as `(x0, y0, x1, y1)`. type Placed = (Option, Vec>, (f64, f64, f64, f64)); @@ -159,6 +209,37 @@ fn guides_are_left_out_of_what_is_placed() { assert_eq!(state(&mut s), before); } +/// An importer at plug-in API level 4 places its type and images with its paths: the objects of its +/// visible layers go in the group, in order, the objects of a hidden layer are left out, and its +/// artboards leave the document's as they were. +#[test] +fn an_api_4_importer_places_type_and_images_of_its_visible_layers() { + let mut s = with_document(); + let manifest = r#"{"id":"test.place.rich","name":"Test test.place.rich","version":"1","kind":"importer","api":4,"extensions":["tpr"],"place":true,"outputKinds":["type","image","layer","artboard"]}"#; + let rect: Value = serde_json::from_str(ART).unwrap(); + let output = json!({ + "objects": [ + {"type": "type", "text": "Hello", "fontFamily": "No Such Family P9129", "fontSize": 24, "transform": [1, 0, 0, 1, 10, 40], "name": "Title"}, + {"type": "image", "pixelSize": [2, 1], "pixelsBase64": vectorcraft_format::base64_encode(&[255, 0, 0, 255, 0, 0, 255, 128]), "transform": [10, 0, 0, 10, 0, 100], "name": "Pic"}, + rect["objects"][0], + ], + "layers": [{"name": "Shown", "objects": [0, 1]}, {"name": "Hidden", "visible": false, "objects": [2]}], + "artboards": [{"name": "Front", "rect": [0, 0, 200, 100]}], + }); + install(&mut s, &tpl::returning(manifest, &output.to_string())); + let boards = s.doc().unwrap().doc.artboards.clone(); + let r = place(&mut s, "Rich.tpr", b"?", json!({"at": [300, 400]})).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let d = &s.doc().unwrap().doc; + let NodeKind::Group { children, .. } = &d.node(id).expect("placed").kind else { panic!("not a group") }; + let kinds: Vec<(Option<&str>, bool, bool)> = children + .iter() + .map(|c| (c.name.as_deref(), matches!(c.kind, NodeKind::Text(_)), matches!(&c.kind, NodeKind::Image(im) if d.images.contains_key(&im.key)))) + .collect(); + assert_eq!(kinds, [(Some("Title"), true, false), (Some("Pic"), false, true)]); + assert_eq!(d.artboards, boards); +} + /// The importer is told it places the file (`_context.mode`), with the file's extension and name, /// and is given its parameters. #[test] diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index 49cc392f80..5264414cb3 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -403,11 +403,32 @@ impl SubPath { /// Bend segment `seg` so its point at `t` moves by `dv`: both inner control points move by /// dv / 3t(1-t), since B(t) moves by 3t(1-t) times that. A smooth anchor stays smooth: its other /// handle turns with the moved one. False when there is no such segment. + /// + /// A straight segment's handles lie on its anchors, so moving them as they are curls its ends + /// round (#9225). It is bent as the same line with its handles at its thirds instead, so it + /// bows evenly, the point at `t` still landing `dv` away. pub fn bend_segment(&mut self, seg: usize, t: f64, dv: kurbo::Vec2) -> bool { let n = self.anchors.len(); if seg >= self.segment_count() || n == 0 { return false; } + if dv == kurbo::Vec2::ZERO { + return true; + } + let mut t = t; + if self.segment_is_line(seg) { + let c = self.segment(seg); + let third = (c.p3 - c.p0) / 3.0; + if let Some(a) = self.anchors.get_mut(seg % n) { + a.set_handle(true, c.p0 + third, false); + } + if let Some(b) = self.anchors.get_mut((seg + 1) % n) { + b.set_handle(false, c.p3 - third, false); + } + // With its handles on its anchors, the line is at t²(3 - 2t) of the way along at t; with + // them at its thirds, that far along is where it is at that same parameter. + t = t * t * (3.0 - 2.0 * t); + } let v = dv / (3.0 * t * (1.0 - t)); if let Some(a) = self.anchors.get_mut(seg % n) { a.set_handle(true, a.h_out + v, false); @@ -940,6 +961,28 @@ fn push_curve(cur: &mut Option, last: Point, c1: Point, c2: Point, p: P #[cfg(test)] mod tests { + /// #9225: a straight segment bent from its middle bows evenly: its handles leave from along the + /// line, toward the middle, not straight out of its anchors, and the grabbed point follows. + #[test] + fn bending_a_straight_segment_pulls_its_handles_from_along_the_line() { + for t in [0.5, 0.3, 0.1] { + let mut sp = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(300.0, 0.0)], false); + let grabbed = sp.segment(0).eval(t); + let dv = kurbo::Vec2::new(0.0, 60.0); + assert!(sp.bend_segment(0, t, dv)); + let (a, b) = (sp.anchors[0], sp.anchors[1]); + assert!(a.h_out.x > a.p.x + 1.0 && b.h_in.x < b.p.x - 1.0, "t {t}: {a:?} {b:?}"); + let landed = sp.segment(0).nearest(grabbed + dv, 1e-9).distance_sq.sqrt(); + assert!(landed < 1e-6, "t {t}: the grabbed point is {landed} off the pointer"); + } + // No move leaves it as it was, a smooth end's other handle included. + let mut sp = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(300.0, 0.0)], false); + sp.anchors[1].h_out = Point::new(300.0, 50.0); + sp.anchors[1].kind = AnchorKind::Smooth; + let before = sp.clone(); + assert!(sp.bend_segment(0, 0.5, kurbo::Vec2::ZERO)); + assert_eq!(sp.anchors, before.anchors); + } use super::*; /// `bounds` walks the anchors in place: bit for bit what the kurbo path it stands for gives, diff --git a/crates/js/src/class_ops.rs b/crates/js/src/class_ops.rs index 024fe67320..ed114612d4 100644 --- a/crates/js/src/class_ops.rs +++ b/crates/js/src/class_ops.rs @@ -67,6 +67,27 @@ impl Interp { } } + /// The `new.target` of the function the running code is in, for a direct `eval` it calls: + /// `None` outside a function. A function that calls `eval` keeps its `new.target` in a hidden + /// binding ([`Interp::function_bindings`]). Each scope looked at takes a unit of fuel. + pub(crate) fn caller_new_target(&mut self) -> JsResult> { + let mut cur = Some(self.frame()?.env); + while let Some(e) = cur { + self.use_fuel()?; + cur = match self.heap.env(e) { + Some(Env::Decl { bindings, outer }) => { + if bindings.contains(NEW_TARGET) { + return self.binding_value(e, NEW_TARGET).map(Some); + } + *outer + } + Some(Env::Obj { outer, .. }) => *outer, + None => None, + }; + } + Ok(None) + } + /// Adds the hidden bindings of a call to `code` to its function environment `env`: a derived /// class constructor's `this`, function object and `new.target`, and the `new.target` of a /// function whose arrow functions read it. Gives the environment of a derived constructor's diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index ebe35ba9ee..ee3151cd2d 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -1950,6 +1950,9 @@ impl<'a> FnCompiler<'a> { if eval { self.uses_arguments = true; self.uses_this = true; + // The eval code may read `new.target`, even when a later run reads + // scripts as ECMAScript 2015 and this code was read as ES5.1. + self.uses_new_target = true; } if self.has_spread(args) { self.spread_args(args)?; diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index c25934202a..cc8e246d2d 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -1624,6 +1624,21 @@ fn new_target_names_the_constructor_new_was_applied_to() { truth("function F() { this.t = new.target; } var B = F.bind(null); new B().t === F"); } +/// A direct `eval` inside a function reads the function's `new.target`, from an arrow function +/// and a nested `eval` too; outside a function, and through an indirect `eval`, it is a +/// `SyntaxError`. +#[test] +fn eval_inside_a_function_reads_its_new_target() { + truth("function F() { return eval('new.target'); } new F() === F && F() === undefined"); + truth("function F() { 'use strict'; return eval('new.target'); } new F() === F"); + truth("function F() { return (() => eval('new.target'))(); } new F() === F"); + truth("function F() { return eval('eval(\"new.target\")'); } new F() === F"); + truth("class A { constructor() { this.t = eval('new.target'); } } class B extends A {} new B().t === B"); + throws("eval('new.target')", "SyntaxError"); + throws("(() => eval('new.target'))()", "SyntaxError"); + throws("function F() { return (0, eval)('new.target'); } new F()", "SyntaxError"); +} + #[test] fn deep_class_chains_stay_within_the_limits() { let src = "var C = class {}; for (var i = 0; i < 2000; i++) { C = class extends C {}; } new C();"; diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 29a8a9987a..c8ae5a8c11 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -698,6 +698,8 @@ pub(crate) const ENV_BYTES: usize = 64; pub(crate) const ROPE_BYTES: usize = 48; /// The estimated bytes of each argument a bound function holds. pub(crate) const BOUND_ARG_BYTES: usize = 24; +/// The estimated bytes of each entry an `arguments` object holds in its map of argument names. +pub(crate) const ARG_NAME_BYTES: usize = std::mem::size_of::>(); /// The estimated bytes of an XML node without its names and text. pub(crate) const XML_NODE_BYTES: usize = 160; /// The estimated bytes of an XML list without its items. @@ -1097,7 +1099,10 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u } extra = BOUND_ARG_BYTES * args.len(); } - Class::Arguments(map) => work.push(map.env.0), + Class::Arguments(map) => { + work.push(map.env.0); + extra = ARG_NAME_BYTES * map.names.len(); + } Class::String(s) => strings.add(s), Class::RegExp(re) => { if strings.seen.insert(Rc::as_ptr(re) as *const () as usize) { diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 89821e7734..ffc58e64da 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -561,9 +561,11 @@ fn scope_bytes(code: &Code, i: u32) -> usize { } /// At least the bytes that the `arguments` object of a call with `args` arguments adds to the -/// heap: the object, an element for each argument and its other properties. +/// heap: the object, its map of argument names, an element for each argument and its other +/// properties. fn arguments_bytes(args: usize) -> usize { - OBJECT_BYTES.saturating_add(args.saturating_add(4).saturating_mul(binding_bytes(10))) + let names = crate::heap::ARG_NAME_BYTES.saturating_mul(args); + OBJECT_BYTES.saturating_add(names).saturating_add(args.saturating_add(4).saturating_mul(binding_bytes(10))) } /// A call to a function written in JavaScript, ready to enter; `new_target` is set when it is @@ -3158,7 +3160,8 @@ impl Interp { return Err(Abrupt::Limit(LimitKind::Frames)); } let params = code.params.iter().chain(&code.pattern_names).fold(0usize, |total, p| total.saturating_add(binding_bytes(p.len()))); - let arguments = if code.uses_arguments { arguments_bytes(args.len()) } else { 0 }; + // An arrow function reads the `arguments` object of the function around it. + let arguments = if code.uses_arguments && !code.arrow { arguments_bytes(args.len()) } else { 0 }; // The array a rest parameter gets: its binding and one property for each extra argument. let rest = match &code.rest { Some(name) => { @@ -3373,7 +3376,10 @@ impl Interp { } } let proto = self.intrinsics.object_proto; + let extra = crate::heap::ARG_NAME_BYTES.saturating_mul(names.len()); + self.reserve_heap(crate::heap::OBJECT_BYTES.saturating_add(extra))?; let a = self.heap.alloc_object(Object::new(Class::Arguments(Box::new(ArgMap { env, names })), Some(proto))); + self.heap.bytes = self.heap.bytes.saturating_add(extra); for (i, v) in args.iter().enumerate() { self.define(a, index_key(u32::try_from(i).unwrap_or(u32::MAX)), Prop::Data { value: v.clone(), flags: OPEN })?; } @@ -3539,10 +3545,17 @@ impl Interp { /// [`Interp::compile_source`], with [`crate::bytecode::Source::strict_writes`] set to `writes`. pub(crate) fn compile_source_writes(&mut self, units: &[u16], strict: bool, writes: bool, kind: CodeKind) -> Result, CompileError> { + self.compile_units(units, strict, writes, kind, false) + } + + /// [`Interp::compile_source_writes`]; `in_function` reads eval code run inside a function, + /// where `new.target` is allowed. + fn compile_units(&mut self, units: &[u16], strict: bool, writes: bool, kind: CodeKind, in_function: bool) -> Result, CompileError> { self.source_units = self.source_units.saturating_add(units.len()); let remaining = self.options.max_source_units.saturating_sub(self.source_units.saturating_sub(units.len())); let options = Options { strict, max_source_units: remaining, ..self.options.clone() }; - let program = crate::parse_utf16(units, &options).map_err(CompileError::Syntax)?; + let parse = if in_function { crate::parse_utf16_in_function } else { crate::parse_utf16 }; + let program = parse(units, &options).map_err(CompileError::Syntax)?; let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: self.source_tag, strict_writes: writes }); compile_program(&program, &source, kind).map_err(|e| match e { CompileFail::Syntax(s) => CompileError::Syntax(s), @@ -3569,7 +3582,10 @@ impl Interp { self.prepare_source(s.len())?; let units = self.flat_reserved(s)?; self.observe_code(&units); - let code = self.compile_source(&units, strict, CodeKind::Eval).map_err(|e| self.compile_error_to_abrupt(e))?; + // Inside a function the eval code reads the function's `new.target` (section 18.2.1.1). + let new_target = self.caller_new_target()?; + let writes = self.writes_mode(); + let code = self.compile_units(&units, strict, writes, CodeKind::Eval, new_target.is_some()).map_err(|e| self.compile_error_to_abrupt(e))?; self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES))?; let frame = self.frame()?; let (caller_env, caller_var_env, this, this_in_env) = (frame.env, frame.var_env, frame.this.clone(), frame.this_in_env); @@ -3584,7 +3600,9 @@ impl Interp { let env = self.instantiate_pending(&code, env, var_env, true)?; self.push_code_frame(code, env, var_env, this, false)?; // The eval code reads `this` the way the code that called it does (section 18.2.1.1). - self.frame_mut()?.this_in_env = this_in_env; + let frame = self.frame_mut()?; + frame.this_in_env = this_in_env; + frame.new_target = new_target.and_then(|v| v.as_object()); Ok(()) } diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index 75f240a6d6..2dc3008630 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -600,6 +600,35 @@ fn a_lower_heap_limit_applies_to_what_is_already_live() { assert_eq!(limit(&mut realm, "var more = []; for (var j = 0; j < 20000; j++) more[j] = {j: j};"), LimitKind::Heap); } +#[test] +fn each_arguments_objects_name_map_counts_toward_the_heap() { + let mut realm = Realm::new(); + realm.run("function f() { return arguments; }").unwrap(); + // The growth from 100 objects to 200, each with its elements deleted, so the script's own code + // and strings cancel out and only the map of argument names stays. + let mut per_hundred = |len: usize| { + let mut grown = |count: usize| { + realm.run("var kept = []; var a = null;").unwrap(); + let before = realm.collect_garbage(); + let src = format!( + "var args = []; for (var j = 0; j < {len}; j++) args[j] = 0; \ + for (var i = 0; i < {count}; i++) {{ var a = f.apply(null, args); \ + for (var j = 0; j < {len}; j++) delete a[j]; kept.push(a); }} args = null;" + ); + realm.run(&src).unwrap(); + realm.collect_garbage() - before + }; + grown(200) - grown(100) + }; + // The first runs also leave bindings and names the later ones reuse. + per_hundred(1); + let short = per_hundred(1); + let long = per_hundred(65); + // The longer runs also keep up to a property's worth more per object besides the names. + let names = 100 * 64 * crate::heap::ARG_NAME_BYTES; + assert!((names..names + 100 * crate::heap::PROP_BYTES).contains(&(long - short)), "{} of {names}", long - short); +} + #[test] fn apply_keeps_its_arguments_alive_while_a_native_function_runs() { // The first argument's toString makes 20,000 objects, more than a 1 MiB heap holds, so a diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 0db46fc6a6..346f21eb58 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -219,6 +219,13 @@ pub fn parse_utf16(source: &[u16], options: &Options) -> Result Result { + check_length(source.len(), options)?; + parser::Parser::new(source, options, false)?.with_new_target().parse_program().map(|(program, _)| program) +} + /// The tokens of `source`, in order, as the parser reads them: preprocessor lines included, and /// each `/` read as division or as the start of a regular expression literal as the grammar /// decides. The source must be a valid script. diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index 4ab2cbe2e6..a7852f2d14 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -176,6 +176,12 @@ impl<'s> Parser<'s> { Ok(parser) } + /// Allows `new.target` at the top of the source: eval code run inside a function. + pub(crate) fn with_new_target(mut self) -> Self { + self.supers.new_target = self.es2015; + self + } + pub(crate) fn parse_program(mut self) -> Result<(Program, Vec)> { let body = self.parse_body(false)?; if self.tok.kind != TokenKind::Eof { diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 95719bf965..dc4a942d6c 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -568,6 +568,18 @@ fn a_hidden_or_disabled_ok_button_is_not_the_default_found_by_its_text() { assert_eq!(field(&seen.borrow().descriptions[0], "defaultElement"), &Data::Number(3.0), "the OK button that can be clicked is the default"); } +#[test] +fn an_ok_button_in_a_hidden_or_disabled_group_is_not_the_default_found_by_its_text() { + let (mut r, seen, _) = realm(vec![close()]); + let source = "var w = new Window('dialog'); var off = w.add('group'); off.enabled = false; off.add('button', undefined, 'OK'); \ + var hid = w.add('group'); hid.visible = false; hid.add('group').add('button', undefined, 'Cancel'); \ + w.add('button', undefined, 'OK'); w.add('button', undefined, 'Cancel'); w.show()"; + assert_eq!(r.run(source).unwrap(), JsValue::Number(0.0)); + let described = &seen.borrow().descriptions[0]; + assert_eq!(field(described, "defaultElement"), &Data::Number(6.0), "the OK button outside the disabled group is the default"); + assert_eq!(field(described, "cancelElement"), &Data::Number(7.0), "the Cancel button outside the hidden group is the cancel element"); +} + #[test] fn an_ok_or_cancel_button_in_a_hidden_or_disabled_group_is_not_found_by_its_text() { let (mut r, seen, _) = realm(vec![close()]); diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 04e22ba9ca..be26fc5bca 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1006,7 +1006,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.paramDialog", "Command Dialog", "", - "{command, label?, params} open a parameter dialog for any command. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", + "{command, label?, params} open a parameter dialog for any command. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", ), ( "ui.recolorDialog", @@ -2070,7 +2070,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.runScript", "Other Script…", "Cmd+F12", - "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar", + "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `choice`, `skip`, and `reaches`, which ui.dialog.set cannot set: the `kind`, `needs`, `outside`, `includes` and `truncated` of script.check's report on the script, which the warning lists, or null when the check failed); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar", ), ( "ui.runInstalledScript", diff --git a/crates/pathops/src/boolean.rs b/crates/pathops/src/boolean.rs index 60c2a8b296..977c348409 100644 --- a/crates/pathops/src/boolean.rs +++ b/crates/pathops/src/boolean.rs @@ -1472,8 +1472,10 @@ mod tests { assert_eq!(try_area(&square(1e14, 1e14, 100.0), FillRule::NonZero), Err(PathOpsError::Degenerate)); } - /// #5478: the sweep of a triangle against an operand that crosses itself gives faces windings - /// that don't add up to the operands' areas; resolving the operands first gives ones that do. + /// #5478: the sweep of a triangle against an operand that crosses itself gave faces windings + /// that didn't add up to the operands' areas. The sweep now gives that input windings that add + /// up, and a winding off by one face's worth is still caught. Resolving the operands first + /// gives windings that add up as well. #[test] fn wrong_windings_are_caught_and_resolving_the_operands_fixes_them() { let poly = |pts: &[(f64, f64)]| { @@ -1487,7 +1489,9 @@ mod tests { let a = poly(&[(3.0, 1.0), (3.0, 3.0), (0.0, 1.0)]); let b = poly(&[(3.0, 0.0), (0.0, 2.0), (3.0, 2.0), (0.0, 0.0), (0.0, 1.0)]); let arr = Arrangement::new(vec![(a.clone(), FillRule::NonZero), (b.clone(), FillRule::NonZero)]).unwrap(); - assert!(!arrangement_adds_up(&arr, [&a, &b]), "the sweep's windings are off"); + assert!(arrangement_adds_up(&arr, [&a, &b])); + // Every face of the triangle counted twice is off by the triangle's area. + assert_eq!(windings_add_up(&arr.top, |w: &Multi| 2 * w.get(0), &a), Some(false)); let (ra, rb) = (resolved(&a, FillRule::NonZero).unwrap(), resolved(&b, FillRule::NonZero).unwrap()); let arr = Arrangement::new(vec![(ra.clone(), FillRule::NonZero), (rb.clone(), FillRule::NonZero)]).unwrap(); assert!(arrangement_adds_up(&arr, [&ra, &rb])); diff --git a/crates/pathops/src/planar/graph.rs b/crates/pathops/src/planar/graph.rs index dca4c99e92..b9f881f780 100644 --- a/crates/pathops/src/planar/graph.rs +++ b/crates/pathops/src/planar/graph.rs @@ -59,6 +59,8 @@ pub(super) struct Edge { pub(super) source: usize, /// Every input it lies on, back to front (`source` last). pub(super) sources: Vec, + /// How far [`pin_ends`] moved the start and the end of `segs` from where the sweep put them. + pub(super) pinned: [kurbo::Vec2; 2], } /// `segs` (a chain) moved to start at `a` and end at `b`, the handles next to each moving with it. @@ -107,33 +109,66 @@ pub(super) fn origin(edges: &[Edge], h: usize) -> Option { edges.get(h / 2).map(|e| e.ends[h % 2]) } +/// The segments of half-edge `h` in its direction as the sweep placed them, before [`pin_ends`] +/// moved their ends onto the vertices. +fn swept_seg_iter(edges: &[Edge], h: usize) -> impl Iterator + '_ { + let edge = edges.get(h / 2); + let segs = edge.map(|e| e.segs.as_slice()).unwrap_or_default(); + let [d0, d3] = edge.map_or([kurbo::Vec2::ZERO; 2], |e| e.pinned); + let forward = h.is_multiple_of(2); + (0..segs.len()).filter_map(move |k| { + let i = if forward { k } else { segs.len() - 1 - k }; + let mut s = *segs.get(i)?; + if i == 0 { + s.c.p0 -= d0; + s.c.p1 -= d0; + } + if i + 1 == segs.len() { + s.c.p3 -= d3; + s.c.p2 -= d3; + } + Some(if forward { s } else { Seg { c: CubicBez::new(s.c.p3, s.c.p2, s.c.p1, s.c.p0), line: s.line } }) + }) +} + /// Where half-edge `h` (leaving `v`) first gets `r` away from it, as an angle around `v`. /// /// Edges that only meet at `v` cross a circle around it in the order they leave `v` in, however /// they start out (tangent curves, or the sweep's short straight stubs at a vertex). +/// +/// The edge is measured where the sweep placed it, before [`pin_ends`] moved its ends onto the +/// vertices, so two copies of one curve that the sweep set a few `eps` apart keep the sweep's +/// order around `v`. The point at distance `r` is found on the curve itself by bisection: a +/// flattened curve can be off by more than the gap between the two copies. pub(super) fn leaving_angle(edges: &[Edge], h: usize, v: Point, r: f64) -> f64 { + /// Parameter steps per segment in the search for the first point at distance `r`. + const STEPS: u32 = 32; let first = half_seg_iter(edges, h).next(); - let mut prev = first.map_or(v, |s| s.c.p0); let mut hit: Option = None; // One segment at a time, stopping at the first that gets r away: an edge can run on for - // thousands of segments (a traced outline between two crossings), all of which flattening - // the whole edge to this tolerance would visit, at every vertex. - for s in half_seg_iter(edges, h) { - let path = [kurbo::PathEl::MoveTo(s.c.p0), kurbo::PathEl::CurveTo(s.c.p1, s.c.p2, s.c.p3)]; - kurbo::flatten(path, (r * 1e-4).max(1e-12), |el| { - if let (None, kurbo::PathEl::LineTo(p)) = (hit, el) { - if p.distance(v) >= r { - // The point on prev → p at distance r (prev is closer). - let (d, f) = (p - prev, prev - v); - let (a, b, c) = (d.hypot2(), 2.0 * f.dot(d), f.hypot2() - r * r); - let t = if a > 0.0 { ((-b + (b * b - 4.0 * a * c).max(0.0).sqrt()) / (2.0 * a)).clamp(0.0, 1.0) } else { 1.0 }; - hit = Some(prev + d * t); - } - prev = p; + // thousands of segments (a traced outline between two crossings). + 'segs: for s in swept_seg_iter(edges, h) { + let mut lo = 0.0; + for k in 0..=STEPS { + let t = f64::from(k) / f64::from(STEPS); + if s.c.eval(t).distance(v) < r { + lo = t; + continue; } - }); - if hit.is_some() { - break; + let mut hi = t; + while hi > 0.0 { + let mid = 0.5 * (lo + hi); + if mid <= lo || mid >= hi { + break; + } + if s.c.eval(mid).distance(v) < r { + lo = mid; + } else { + hi = mid; + } + } + hit = Some(s.c.eval(hi)); + break 'segs; } } // An edge too short to reach r (it can't, r is at most half of every chord) leaves along its diff --git a/crates/pathops/src/planar/map.rs b/crates/pathops/src/planar/map.rs index a9b25d24b5..f2c4b200d3 100644 --- a/crates/pathops/src/planar/map.rs +++ b/crates/pathops/src/planar/map.rs @@ -305,6 +305,7 @@ fn sweep_graph(inputs: &[(BezPath, usize)], eps: f64, precision: f64) -> Option< // Every edge at a vertex starts or ends exactly on it, so faces meeting there share its // coordinates: merging them (a union) then cancels their common edge, which it can't when // each face carries its own rounding of the corner (#893). + let pinned = [segs.first().map_or(kurbo::Vec2::ZERO, |s| p0 - s.c.p0), segs.last().map_or(kurbo::Vec2::ZERO, |s| p1 - s.c.p3)]; pin_ends(&mut segs, p0, p1); if sources.is_empty() { sources = mid(&segs).map(|m| outlines.sources_at(m)).unwrap_or_default(); @@ -330,7 +331,7 @@ fn sweep_graph(inputs: &[(BezPath, usize)], eps: f64, precision: f64) -> Option< continue; } between.entry(key).or_default().push(edges.len()); - edges.push(Edge { segs, ends, source, sources }); + edges.push(Edge { segs, ends, source, sources, pinned }); } Some((points, edges)) } diff --git a/crates/pathops/src/planar/tests.rs b/crates/pathops/src/planar/tests.rs index f9b88a27f8..ad888448a7 100644 --- a/crates/pathops/src/planar/tests.rs +++ b/crates/pathops/src/planar/tests.rs @@ -230,6 +230,16 @@ fn curves_and_a_circle_crossed_by_a_line() { assert_eq!(edges.iter().filter(|e| e.key == 0).count(), 2, "two arcs"); } +/// Two copies of one circle are one filled face. +#[test] +fn two_copies_of_a_circle_are_one_filled_face() { + let mut a = circle(25.0, 65.0, 15.0, 0); + a.rule = FillRule::EvenOdd; + let (faces, _) = live_paint(&[a.clone(), a]); + let filled: f64 = faces.iter().filter(|f| !f.sources.is_empty()).map(area).sum(); + assert!((filled - std::f64::consts::PI * 225.0).abs() < 1.0, "{filled}: {faces:?}"); +} + /// Coincident curved boundaries retain the fill coverage of the regions they separate. #[test] fn coincident_curves_keep_their_source_faces() { diff --git a/crates/pathops/tests/it/pathfinder_pinned.rs b/crates/pathops/tests/it/pathfinder_pinned.rs index a6e987d27e..85f9ca423c 100644 --- a/crates/pathops/tests/it/pathfinder_pinned.rs +++ b/crates/pathops/tests/it/pathfinder_pinned.rs @@ -78,46 +78,48 @@ fn every_pathfinder_operation_is_pinned() { assert_eq!(got, PINNED); } -/// Computed with the dense windings (main at b08482d6). +/// Computed with the sweep of craft-libs 610c86792a, which places output curves closer to their +/// inputs than the one before (craft-libs#721): every output keeps its shapes, subpaths and +/// anchors, and its area and length agree with the earlier pins to 1e-6 relative. const PINNED: [u64; 40] = [ - 0x5e62_baae_d8b4_dba5, - 0x2bbc_e138_a97c_5a28, - 0xce78_992e_750b_1092, - 0x30cf_cc0b_861c_48b4, - 0xe6e4_2a29_1e16_5e86, - 0x390b_0633_5066_6292, - 0x06b7_3884_f961_c343, - 0x06b7_3884_f961_c343, - 0x0384_d599_5a03_dafd, - 0x3dcd_029a_dd3f_fa38, - 0x8249_71f8_fda4_2bb6, - 0xe7f2_8633_cef9_a76c, + 0x955c_8b2d_f025_1d4a, + 0x7f0e_0ba6_f322_01d3, + 0xe7b6_dfcc_7d22_84b0, + 0xe65f_7d83_0896_6cb0, + 0xf077_5d80_f61c_2011, + 0x9e74_9802_4395_ea61, + 0x58d2_be7a_b723_a56e, + 0x58d2_be7a_b723_a56e, + 0x5959_96b9_2bf6_4d87, + 0xc194_6236_14c2_0591, + 0xb633_97b1_90e6_a7f8, + 0x3a40_3bb7_87e3_a9d2, 0x1a11_084e_721e_ac3b, 0xcbf2_9ce4_8422_2325, - 0xa786_d973_a0d7_ca2a, - 0x389b_c89a_0ccf_578f, - 0xff9d_cf53_d872_681e, - 0xff9d_cf53_d872_681e, + 0x5302_5520_518c_4b14, + 0x6ab1_e2ae_913c_fd02, + 0x1d33_b251_5b9e_6034, + 0x1d33_b251_5b9e_6034, 0xcbf2_9ce4_8422_2325, - 0x6be3_02a6_d9c9_e80e, - 0x3525_cabe_b235_aaef, - 0xf969_aa07_a44d_1770, - 0xed13_60c7_0aaa_7854, + 0x2c80_b697_1843_0971, + 0x2a36_ff1a_6452_6645, + 0xcc2d_7af8_e01f_e960, + 0x3d9f_67a5_a5bd_ee09, 0xcbf2_9ce4_8422_2325, - 0x6550_a381_db6b_a35f, - 0x1ba9_6dfb_89ea_ac78, - 0x1344_b467_dd20_5f02, - 0x948f_e2a1_d657_0d4c, - 0x49a4_5c3c_2d96_14af, - 0x16a7_ce9e_4a3c_0974, - 0x0b12_c643_a446_da04, + 0x3396_f715_a71b_b1e2, + 0xd1bd_dbfc_4e57_80ac, + 0x15a1_d47a_be5a_dc72, + 0x2548_d208_a79c_4974, + 0x2088_06d5_a0a5_d65e, + 0x597f_2517_c677_5429, + 0x25d0_bc2c_70e1_c3a4, 0xcbf2_9ce4_8422_2325, 0xeb6a_6614_cea5_a508, 0xcbf2_9ce4_8422_2325, - 0xb9c4_2803_7db9_bd4f, - 0x34b6_90d5_e443_b799, - 0xdfaf_ecbd_2d58_3227, - 0x6d5e_6e8d_b05b_8688, + 0x81f7_7a26_7885_0bc5, + 0xfb2d_d20c_1930_44c7, + 0xcd17_209c_b57f_208d, + 0x8fc2_2057_7075_76b4, 0x59dc_9268_a73f_e92e, - 0x5a83_5cbd_1f8c_5143, + 0x5454_509c_877a_852b, ]; diff --git a/crates/plugins/src/import.rs b/crates/plugins/src/import.rs index 453ed75f41..97784d6b01 100644 --- a/crates/plugins/src/import.rs +++ b/crates/plugins/src/import.rs @@ -14,6 +14,8 @@ //! The host hands the importer the file's bytes as they are, at most [`MAX_INPUT_BYTES`] of them, //! and reads back the objects of the new document in the same form filters return them //! ([`crate::objects`]): `{"objects": [...], "warnings"?: ["…"]}`, or `{"error": "…"}` to decline. +//! An importer at plug-in API level 4 whose manifest lists `outputKinds` may also return point type +//! and embedded images in `objects`, and `layers` and `artboards` ([`decode_with`]). //! An import is one run the user asked for, so it gets an export's budget ([`crate::export::FUEL`] //! and [`crate::export::WALL_TIME_MS`]), and Cancel stops it between two slices of the budget //! ([`Error::Cancelled`]). @@ -21,9 +23,11 @@ use std::sync::Arc; use serde_json::{Value, json}; +use vectorcraft_color::Paint; +use vectorcraft_geom::{Affine, Rect}; -use crate::objects::{OutObject, declined, printable}; -use crate::{Error, Kind, Limits, Plugin, Result, registry}; +use crate::objects::{MAX_COORD, MAX_OBJECTS, OutObject, declined, out_err, printable}; +use crate::{Error, Kind, Limits, OutputKind, Plugin, Result, registry}; /// The largest file an importer is given, in bytes: 128 MiB, a quarter of a plug-in's memory /// limit, so the file and the objects made from it fit beside each other. @@ -100,13 +104,109 @@ impl Mode { /// What an importer returned. #[derive(Clone, Debug, PartialEq)] pub struct Imported { - /// The objects of the new document, in paint order (bottom first), checked as a filter's are. - pub objects: Vec, + /// The objects of the new document, in paint order (bottom first): paths and compound paths + /// checked as a filter's are, and type and images when the importer lists them in `outputKinds`. + pub objects: Vec, + /// The top-level layers, bottom first, each holding the objects it lists (`layers`, with + /// `outputKinds` `layer`); empty: every object goes in one layer. + pub layers: Vec, + /// The artboards (`artboards`, with `outputKinds` `artboard`); empty: one artboard around the art. + pub artboards: Vec, /// What the import left out or changed, for the user (at most /// [`crate::export::MAX_WARNINGS`]). pub warnings: Vec, } +impl Imported { + /// Whether it holds paths and compound paths alone, as an importer below API level 4 returns. + pub fn paths_only(&self) -> bool { + self.layers.is_empty() && self.artboards.is_empty() && self.objects.iter().all(|o| matches!(o, ImportObject::Path(_))) + } +} + +/// One object of an import. +#[derive(Clone, Debug, PartialEq)] +pub enum ImportObject { + /// A path or a compound path (`"type": "path"` or `"compound"`, or no `type`). + Path(OutObject), + /// Point type (`"type": "type"`). + Type(OutType), + /// An embedded image (`"type": "image"`). + Image(OutImage), +} + +/// Point type an importer returned: `{"type": "type", text, fontFamily, fontStyle?, fontSize, +/// fill?, transform?, name?}`. +#[derive(Clone, Debug, PartialEq)] +pub struct OutType { + /// Its text, a line break (`\n`) between two paragraphs. + pub text: String, + pub font_family: String, + /// `None`: the family's regular style. + pub font_style: Option, + /// In points, from [`TYPE_SIZES`]`.0` to [`TYPE_SIZES`]`.1`. + pub font_size: f64, + /// `None`: the default fill (black). + pub fill: Option, + /// Maps the type's own space (the first baseline starts at its origin) into the document. + pub transform: Affine, + pub name: Option, +} + +/// An embedded image an importer returned: `{"type": "image", pixelSize: [w, h], pixelsBase64, +/// transform?, name?}`. +#[derive(Clone, Debug, PartialEq)] +pub struct OutImage { + pub width: u32, + pub height: u32, + /// Straight RGBA, 8 bits a channel, row by row from the top: `4 × width × height` bytes. + pub rgba: Vec, + /// Maps pixel space (one unit a pixel, y down) into the document. + pub transform: Affine, + pub name: Option, +} + +/// A top-level layer an importer returned: `{name, visible?, locked?, objects: [index…]}`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OutLayer { + pub name: String, + pub visible: bool, + pub locked: bool, + /// Indexes into [`Imported::objects`], increasing: the layer's objects in paint order. + pub objects: Vec, +} + +/// An artboard an importer returned: `{name, rect: [x, y, width, height]}`. +#[derive(Clone, Debug, PartialEq)] +pub struct OutArtboard { + pub name: String, + pub rect: Rect, +} + +/// Most layers an import may return. +pub const MAX_LAYERS: usize = 256; + +/// Most artboards an import may return. +pub const MAX_ARTBOARDS: usize = 100; + +/// Longest layer, artboard, object or font name an import may return, in characters. +pub const MAX_NAME_CHARS: usize = 256; + +/// Most bytes of UTF-8 text one type object may hold. +pub const MAX_TYPE_TEXT: usize = 1 << 20; + +/// Most bytes of UTF-8 text all the type of one import may hold. +pub const MAX_TEXT_TOTAL: usize = 16 << 20; + +/// Most pixels an image may have along either side. +pub const MAX_IMAGE_SIDE: u64 = 16_384; + +/// Most bytes of RGBA all the images of one import may hold. +pub const MAX_PIXEL_BYTES: u64 = 32 << 20; + +/// The type sizes an import may give, in points (those Character panel sizes take). +pub const TYPE_SIZES: (f64, f64) = (0.1, 1296.0); + /// The file an import reads, as the importer is told in `_context`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Source<'a> { @@ -148,23 +248,68 @@ pub fn run_as(plugin: &Plugin, file: &[u8], params: &Value, source: Source, mode let mut params = Value::Object(m.resolve_params(params)?); params["_context"] = json!({"mode": mode.name(), "extension": source.extension, "name": source.name}); let params = serde_json::to_vec(¶ms).map_err(|e| Error::Params(e.to_string()))?; - decode(&plugin.run_limited(file, ¶ms, &limits(plugin))?) + decode_with(&plugin.run_limited(file, ¶ms, &limits(plugin))?, &m.output_kinds()) } /// An importer's output: `{"objects": [...], "warnings"?: ["…"]}`, or `{"error": "…"}` to decline /// with a message for the user. The objects are new ones (no `id`), checked as a filter's are; an /// output without any, or with keys of its own, is refused. pub fn decode(bytes: &[u8]) -> Result { + decode_with(bytes, &[]) +} + +/// [`decode`] for an importer whose manifest lists `kinds` (`outputKinds`): `objects` may also +/// hold type and images, and the output `layers` and `artboards`, of the kinds listed. Content of +/// a kind not listed is refused naming the kind. Everything is checked before anything is returned, +/// against the limits of this module, and one bad entry refuses the whole output. With `kinds` +/// listing layers or artboards, an output of no objects is an empty document when it has any. +pub fn decode_with(bytes: &[u8], kinds: &[OutputKind]) -> Result { let v: Value = serde_json::from_slice(bytes).map_err(|e| Error::Output(format!("not JSON: {e}")))?; if let Some(e) = declined(&v) { return Err(e); } - if let Some(key) = v.as_object().and_then(|o| o.keys().find(|k| !OUTPUT_KEYS.contains(&k.as_str()))) { - let key = printable(&json!(key), 64); - return Err(Error::Output(format!("an importer returns `objects` and `warnings`, not `{key}`"))); + for key in v.as_object().into_iter().flat_map(|o| o.keys()).filter(|k| !OUTPUT_KEYS.contains(&k.as_str())) { + let rich = match key.as_str() { + "layers" => Some(OutputKind::Layer), + "artboards" => Some(OutputKind::Artboard), + _ => None, + }; + match rich { + Some(kind) if kinds.contains(&kind) => {} + Some(kind) if !kinds.is_empty() => return Err(undeclared(kind)), + _ => { + let key = printable(&json!(key), 64); + return Err(Error::Output(format!("an importer returns `objects` and `warnings`, not `{key}`"))); + } + } } - let objects = crate::objects::decode(bytes)?; - if objects.is_empty() { + let (objects, layers, artboards) = if kinds.is_empty() { + let objects = crate::objects::decode(bytes)?; + (objects.into_iter().map(ImportObject::Path).collect::>(), Vec::new(), Vec::new()) + } else { + let objects = rich_objects(&v, kinds)?; + let layers = match v.get("layers") { + None => Vec::new(), + Some(l) => decode_layers(l, objects.len())?, + }; + let artboards = match v.get("artboards") { + None => Vec::new(), + Some(a) => decode_artboards(a)?, + }; + (objects, layers, artboards) + }; + for (i, object) in objects.iter().enumerate() { + if let ImportObject::Path(path) = object { + let at = format!("objects[{i}]"); + if path.id.is_some() { + return Err(out_err(&at, "an importer returns new paths without `id`")); + } + if path.path.is_none() { + return Err(out_err(&at, "an imported path must include its geometry in `path`")); + } + } + } + if objects.is_empty() && layers.is_empty() && artboards.is_empty() { return Err(Error::Output("the importer returned no objects".into())); } let warnings = match v.get("warnings") { @@ -172,7 +317,299 @@ pub fn decode(bytes: &[u8]) -> Result { Some(Value::Array(w)) => w.iter().take(crate::export::MAX_WARNINGS).map(|w| printable(w, crate::export::MAX_WARNING_CHARS)).collect(), Some(_) => return Err(Error::Output("`warnings` must be a list of strings".into())), }; - Ok(Imported { objects, warnings }) + Ok(Imported { objects, layers, artboards, warnings }) +} + +/// The error of output holding content of `kind`, which the importer's `outputKinds` doesn't list. +fn undeclared(kind: OutputKind) -> Error { + let kind = kind.name(); + Error::Output(format!("the output holds `{kind}`, which the importer's `outputKinds` doesn't list")) +} + +/// The keys a type object may have. +const TYPE_KEYS: &[&str] = &["type", "text", "fontFamily", "fontStyle", "fontSize", "fill", "transform", "name"]; + +/// The keys an image object may have. +const IMAGE_KEYS: &[&str] = &["type", "pixelSize", "pixelsBase64", "transform", "name"]; + +/// The keys a layer may have. +const LAYER_KEYS: &[&str] = &["name", "visible", "locked", "objects"]; + +/// The keys an artboard may have. +const ARTBOARD_KEYS: &[&str] = &["name", "rect"]; + +/// The objects of output `v` of an importer listing `kinds`: paths and compound paths as a +/// filter's, type and images of the kinds listed. +fn rich_objects(v: &Value, kinds: &[OutputKind]) -> Result> { + let objects = v.get("objects").and_then(Value::as_array).ok_or_else(|| Error::Output("expected {\"objects\": [...]}".into()))?; + if objects.len() > MAX_OBJECTS { + return Err(Error::Output(format!("{} objects (limit {MAX_OBJECTS})", objects.len()))); + } + let kind_of = |o: &Value| match o.get("type").and_then(Value::as_str) { + Some("type") => Some(OutputKind::Type), + Some("image") => Some(OutputKind::Image), + _ => None, + }; + if let Some(kind) = objects.iter().filter_map(kind_of).find(|k| !kinds.contains(k)) { + return Err(undeclared(kind)); + } + check_totals(objects)?; + let mut anchors = 0; + objects + .iter() + .enumerate() + .map(|(i, o)| { + let at = format!("objects[{i}]"); + match kind_of(o) { + Some(OutputKind::Type) => decode_type(o, &at).map(ImportObject::Type), + Some(_) => decode_image(o, &at).map(ImportObject::Image), + None => crate::objects::decode_object(o, &at, &mut anchors).map(ImportObject::Path), + } + }) + .collect() +} + +/// Refuses `objects` whose type, all together, holds more than [`MAX_TEXT_TOTAL`] bytes of text, or +/// whose images, by the sizes they give, more than [`MAX_PIXEL_BYTES`] bytes of pixels, before any +/// object is read further or any pixels are decoded. +fn check_totals(objects: &[Value]) -> Result<()> { + let (mut text, mut pixel_bytes) = (0usize, 0u64); + for (i, o) in objects.iter().enumerate() { + let at = format!("objects[{i}]"); + match o.get("type").and_then(Value::as_str) { + Some("type") => { + text = text.saturating_add(o.get("text").and_then(Value::as_str).map_or(0, str::len)); + if text > MAX_TEXT_TOTAL { + return Err(out_err(&at, format!("the type holds more than {MAX_TEXT_TOTAL} bytes of text"))); + } + } + Some("image") => { + let side = |k: usize| o.get("pixelSize").and_then(|s| s.get(k)).and_then(Value::as_u64).unwrap_or(0); + let (w, h) = (side(0), side(1)); + if w > MAX_IMAGE_SIDE || h > MAX_IMAGE_SIDE { + return Err(out_err(&at, format!("{w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side)"))); + } + pixel_bytes = pixel_bytes.saturating_add(w.saturating_mul(h).saturating_mul(4)); + if pixel_bytes > MAX_PIXEL_BYTES { + return Err(out_err(&at, format!("the images hold more than {MAX_PIXEL_BYTES} bytes of pixels"))); + } + } + _ => {} + } + } + Ok(()) +} + +/// Refuses a key of JSON object `o` that isn't one of `keys`. +fn known_keys(o: &serde_json::Map, keys: &[&str], at: &str) -> Result<()> { + match o.keys().find(|k| !keys.contains(&k.as_str())) { + Some(key) => { + let key = printable(&json!(key), 64); + Err(out_err(at, format!("unknown field `{key}`"))) + } + None => Ok(()), + } +} + +/// Is `c` a character that changes the direction text is laid out in (an embedding, override, +/// isolate or mark)? +fn is_direction_mark(c: char) -> bool { + matches!(c, '\u{200E}' | '\u{200F}' | '\u{061C}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}') +} + +/// The name `key` of `o` (`at` names it): 1 to [`MAX_NAME_CHARS`] characters, none of them a +/// control character or a direction mark, and not only spaces. `None` when it is left out and not +/// `required`. +fn name(o: &serde_json::Map, key: &str, required: bool, at: &str) -> Result> { + let v = match o.get(key) { + None | Some(Value::Null) if required => return Err(out_err(at, format!("missing field `{key}`"))), + None | Some(Value::Null) => return Ok(None), + Some(v) => v, + }; + let s = v.as_str().ok_or_else(|| out_err(at, format!("`{key}` must be a string")))?; + let count = s.chars().count(); + if count == 0 || count > MAX_NAME_CHARS || s.trim().is_empty() || s.chars().any(|c| c.is_control() || is_direction_mark(c)) { + return Err(out_err(at, format!("`{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters"))); + } + Ok(Some(s.to_string())) +} + +/// The affine `key` of `o` (`at` names it): six finite numbers within ±[`MAX_COORD`] that don't +/// flatten what it places. Left out, no change of place. +fn transform(o: &serde_json::Map, key: &str, at: &str) -> Result { + let Some(v) = o.get(key).filter(|v| !v.is_null()) else { return Ok(Affine::IDENTITY) }; + let wrong = || out_err(at, format!("`{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object")); + let list = v.as_array().filter(|a| a.len() == 6).ok_or_else(wrong)?; + let mut c = [0.0; 6]; + for (slot, n) in c.iter_mut().zip(list) { + *slot = n.as_f64().filter(|x| x.is_finite() && x.abs() <= MAX_COORD).ok_or_else(wrong)?; + } + let det = c[0] * c[3] - c[1] * c[2]; + if !det.is_normal() { + return Err(wrong()); + } + Ok(Affine::new(c)) +} + +/// A type object of the output (`at` names it). +fn decode_type(v: &Value, at: &str) -> Result { + let o = v.as_object().ok_or_else(|| out_err(at, "an object must be a JSON object"))?; + known_keys(o, TYPE_KEYS, at)?; + let text = match o.get("text") { + None | Some(Value::Null) => { + let key = "text"; + return Err(out_err(at, format!("missing field `{key}`"))); + } + Some(t) => t.as_str().ok_or_else(|| { + let key = "text"; + out_err(at, format!("`{key}` must be a string")) + })?, + }; + let len = text.len(); + if len > MAX_TYPE_TEXT { + return Err(out_err(at, format!("`text` is {len} bytes (limit {MAX_TYPE_TEXT})"))); + } + if text.chars().any(|c| c.is_control() && c != '\n' && c != '\t') { + return Err(out_err(at, "`text` must not hold control characters other than line breaks and tabs")); + } + let font_family = name(o, "fontFamily", true, at)?.unwrap_or_default(); + let font_style = name(o, "fontStyle", false, at)?; + let key = "fontSize"; + let font_size = match o.get(key) { + None | Some(Value::Null) => return Err(out_err(at, format!("missing field `{key}`"))), + Some(s) => s.as_f64().ok_or_else(|| out_err(at, format!("`{key}` must be a number")))?, + }; + let (min, max) = TYPE_SIZES; + if !(min..=max).contains(&font_size) { + let x = font_size; + return Err(out_err(at, format!("`{key}` must be between {min} and {max} (got {x})"))); + } + let fill = match o.get("fill") { + None => None, + Some(f) => { + let paint = crate::objects::decode_paint(f, &format!("{at}.fill"))?; + if matches!(paint, Paint::Pattern { .. }) { + return Err(out_err(at, "a type fill must be a color or a gradient")); + } + Some(crate::objects::unlinked(paint)) + } + }; + Ok(OutType { + text: text.to_string(), + font_family, + font_style, + font_size, + fill, + transform: transform(o, "transform", at)?, + name: name(o, "name", false, at)?, + }) +} + +/// An image object of the output (`at` names it). Its size has been checked against the limits +/// ([`check_totals`]), and its base64's length is checked against its size before anything is +/// decoded. +fn decode_image(v: &Value, at: &str) -> Result { + let o = v.as_object().ok_or_else(|| out_err(at, "an object must be a JSON object"))?; + known_keys(o, IMAGE_KEYS, at)?; + let size = o.get("pixelSize").and_then(Value::as_array).filter(|a| a.len() == 2).and_then(|a| { + let side = |v: &Value| v.as_u64().filter(|n| (1..=MAX_IMAGE_SIDE).contains(n)); + Some((side(a.first()?)?, side(a.get(1)?)?)) + }); + let (w, h) = size.ok_or_else(|| out_err(at, format!("`pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE}")))?; + let want = w * h * 4; + let wrong = || out_err(at, format!("`pixelsBase64` must hold 4 × width × height = {want} bytes as base64")); + let b64 = o.get("pixelsBase64").and_then(Value::as_str).ok_or_else(wrong)?; + // The length is checked first, so nothing of the wrong size is decoded. + if b64.len() as u64 != want.div_ceil(3) * 4 || craft_vectorcraft_format::base64::decoded_len(b64) != want { + return Err(wrong()); + } + let rgba = craft_vectorcraft_format::base64::decode(b64).filter(|p| p.len() as u64 == want).ok_or_else(wrong)?; + Ok(OutImage { width: w as u32, height: h as u32, rgba, transform: transform(o, "transform", at)?, name: name(o, "name", false, at)? }) +} + +/// The `layers` of the output, for `count` objects: 1 to [`MAX_LAYERS`] layers, bottom first, +/// each listing the indexes of its objects in increasing order, and every object in exactly one. +fn decode_layers(v: &Value, count: usize) -> Result> { + let key = "layers"; + let list = entries(v, key, MAX_LAYERS)?; + let mut owner: Vec = vec![false; count]; + let mut layers = Vec::with_capacity(list.len()); + for (i, l) in list.iter().enumerate() { + let at = format!("layers[{i}]"); + let o = l.as_object().ok_or_else(|| out_err(&at, format!("`{key}` must be an object")))?; + known_keys(o, LAYER_KEYS, &at)?; + let flag = |key: &str, default: bool| -> Result { + match o.get(key) { + None | Some(Value::Null) => Ok(default), + Some(v) => v.as_bool().ok_or_else(|| out_err(&at, format!("`{key}` must be true or false"))), + } + }; + let wrong = || out_err(&at, format!("`objects` must list object indexes in increasing order, each below {count}")); + let indexes = match o.get("objects") { + None | Some(Value::Null) => &[][..], + Some(v) => v.as_array().ok_or_else(wrong)?.as_slice(), + }; + let mut objects = Vec::with_capacity(indexes.len().min(count)); + for v in indexes { + let k = v.as_u64().and_then(|k| usize::try_from(k).ok()).filter(|k| *k < count).ok_or_else(wrong)?; + if objects.last().is_some_and(|last| *last >= k) { + return Err(wrong()); + } + if std::mem::replace(&mut owner[k], true) { + return Err(out_err(&at, format!("object {k} must be in exactly one layer"))); + } + objects.push(k); + } + layers.push(OutLayer { + name: name(o, "name", true, &at)?.unwrap_or_default(), + visible: flag("visible", true)?, + locked: flag("locked", false)?, + objects, + }); + } + if let Some(k) = owner.iter().position(|owned| !owned) { + return Err(out_err("layers", format!("object {k} must be in exactly one layer"))); + } + Ok(layers) +} + +/// The `artboards` of the output: 1 to [`MAX_ARTBOARDS`], each named once, their rectangles +/// within ±[`MAX_COORD`]. +fn decode_artboards(v: &Value) -> Result> { + let key = "artboards"; + let list = entries(v, key, MAX_ARTBOARDS)?; + let mut boards: Vec = Vec::with_capacity(list.len()); + for (i, a) in list.iter().enumerate() { + let at = format!("artboards[{i}]"); + let o = a.as_object().ok_or_else(|| out_err(&at, format!("`{key}` must be an object")))?; + known_keys(o, ARTBOARD_KEYS, &at)?; + let name = name(o, "name", true, &at)?.unwrap_or_default(); + if boards.iter().any(|b| b.name == name) { + let shown = printable(&json!(name), 64); + return Err(out_err(&at, format!("artboard name `{shown}` is used twice"))); + } + let wrong = || out_err(&at, format!("`rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0")); + let r = o.get("rect").and_then(Value::as_array).filter(|r| r.len() == 4).ok_or_else(wrong)?; + let n: Vec = r.iter().map(Value::as_f64).collect::>().ok_or_else(wrong)?; + let (x, y, w, h) = (n[0], n[1], n[2], n[3]); + let (x1, y1) = (x + w, y + h); + let inside = |v: f64| v.is_finite() && v.abs() <= MAX_COORD; + if !(w > 0.0 && h > 0.0 && x1 > x && y1 > y && inside(x) && inside(y) && inside(x1) && inside(y1)) { + return Err(wrong()); + } + boards.push(OutArtboard { name, rect: Rect::new(x, y, x1, y1) }); + } + Ok(boards) +} + +/// The list `v`, the output's `key`, of 1 to `max` entries. +fn entries<'a>(v: &'a Value, key: &str, max: usize) -> Result<&'a Vec> { + let list = v.as_array().ok_or_else(|| Error::Output(format!("`{key}` must be an array")))?; + let n = list.len(); + if !(1..=max).contains(&n) { + return Err(Error::Output(format!("`{key}` must hold 1 to {max} entries (it holds {n})"))); + } + Ok(list) } #[cfg(test)] @@ -184,8 +621,9 @@ mod tests { #[test] fn output_is_the_objects_and_the_warnings_or_a_decline() { let out = decode(format!(r#"{{"objects":[{SQUARE}],"warnings":["a",2]}}"#).as_bytes()).unwrap(); + assert!(out.paths_only()); + assert!(out.objects.iter().all(|o| matches!(o, ImportObject::Path(o) if o.id.is_none() && o.path.is_some()))); assert_eq!((out.objects.len(), out.warnings), (1, vec!["a".to_string(), "2".to_string()])); - assert!(out.objects.iter().all(|o| o.id.is_none() && o.path.is_some())); assert_eq!(decode(format!(r#"{{"objects":[{SQUARE}]}}"#).as_bytes()).unwrap().warnings, Vec::::new()); assert_eq!(decode(br#"{"error": "Not a\nplot file."}"#), Err(Error::Failed("Not aplot file.".into()))); // A decline is reported as one, also with keys the host doesn't read beside it. @@ -216,6 +654,175 @@ mod tests { assert!(decode(warns.as_bytes()).unwrap_err().to_string().contains("`warnings`")); } + const ALL: &[OutputKind] = &OutputKind::ALL; + + /// A change made to [`rich`] output. + type Edit = Box; + + /// Type, an image of 2 × 1 pixels, the square, two layers and two artboards. + fn rich() -> Value { + let pixels = craft_vectorcraft_format::base64::encode(&[255, 0, 0, 255, 0, 0, 255, 128]); + json!({ + "objects": [ + {"type": "type", "text": "Hello\nWorld", "fontFamily": "Source Sans 3", "fontStyle": "Bold", "fontSize": 24, + "fill": {"type": "solid", "color": {"model": "rgb", "r": 0, "g": 0, "b": 1}}, "transform": [1, 0, 0, 1, 10, 40], "name": "Title"}, + {"type": "image", "pixelSize": [2, 1], "pixelsBase64": pixels, "transform": [10, 0, 0, 10, 0, 100]}, + serde_json::from_str::(SQUARE).unwrap(), + ], + "layers": [{"name": "Art", "objects": [1, 2]}, {"name": "Words", "visible": false, "locked": true, "objects": [0]}], + "artboards": [{"name": "Front", "rect": [0, 0, 200, 100]}, {"name": "Back", "rect": [220, 0, 200, 100]}], + }) + } + + fn rich_with(edit: impl FnOnce(&mut Value)) -> Result { + let mut v = rich(); + edit(&mut v); + decode_with(v.to_string().as_bytes(), ALL) + } + + #[test] + fn importer_output_rejects_filter_only_path_updates() { + let square: Value = serde_json::from_str(SQUARE).unwrap(); + let mut identified = square.clone(); + identified["id"] = json!(3); + for object in [json!({"id": 3}), json!({"type": "path"}), identified] { + let output = json!({"objects": [object]}); + for kinds in [&[OutputKind::Type][..], &[][..]] { + assert!(decode_with(output.to_string().as_bytes(), kinds).is_err(), "{kinds:?}: {output}"); + } + } + let mut untyped = square.clone(); + untyped.as_object_mut().unwrap().remove("type"); + for object in [square, untyped] { + let output = json!({"objects": [object]}); + for kinds in [&[OutputKind::Type][..], &[][..]] { + assert!(decode_with(output.to_string().as_bytes(), kinds).is_ok(), "{kinds:?}: {output}"); + } + } + } + + #[test] + fn importer_output_rejects_artboards_with_collapsed_endpoints() { + for rect in [[1_000_000.0, 0.0, 1e-12, 10.0], [0.0, 1_000_000.0, 10.0, 1e-12]] { + assert!(rich_with(|v| v["artboards"][0]["rect"] = json!(rect)).is_err(), "{rect:?}"); + } + assert!(rich_with(|v| v["artboards"][0]["rect"] = json!([3_999_999.0, 3_999_999.0, 1.0, 1.0])).is_ok()); + } + + /// An importer listing every output kind returns type, an embedded image, paths, layers and + /// artboards, each read as it was given. + #[test] + fn each_output_kind_is_read_as_given() { + let out = decode_with(rich().to_string().as_bytes(), ALL).unwrap(); + assert!(!out.paths_only()); + let [ImportObject::Type(t), ImportObject::Image(im), ImportObject::Path(p)] = out.objects.as_slice() else { panic!("{:?}", out.objects) }; + assert_eq!( + (t.text.as_str(), t.font_family.as_str(), t.font_style.as_deref(), t.font_size), + ("Hello\nWorld", "Source Sans 3", Some("Bold"), 24.0) + ); + assert_eq!((t.transform, t.name.as_deref()), (Affine::translate((10.0, 40.0)), Some("Title"))); + assert!(matches!(t.fill, Some(Paint::Solid { .. }))); + assert_eq!((im.width, im.height, im.rgba.as_slice()), (2, 1, &[255, 0, 0, 255, 0, 0, 255, 128][..])); + assert!(p.path.is_some()); + let layers: Vec<_> = out.layers.iter().map(|l| (l.name.as_str(), l.visible, l.locked, l.objects.clone())).collect(); + assert_eq!(layers, [("Art", true, false, vec![1, 2]), ("Words", false, true, vec![0])]); + let boards: Vec<_> = out.artboards.iter().map(|a| (a.name.as_str(), a.rect)).collect(); + assert_eq!(boards, [("Front", Rect::new(0.0, 0.0, 200.0, 100.0)), ("Back", Rect::new(220.0, 0.0, 420.0, 100.0))]); + // Artboards alone are a blank document. + let blank = decode_with(br#"{"objects":[],"artboards":[{"name":"A","rect":[0,0,10,10]}]}"#, &[OutputKind::Artboard]).unwrap(); + assert_eq!((blank.objects.len(), blank.artboards.len()), (0, 1)); + } + + /// Output of a kind the manifest doesn't list is refused naming the kind; an importer listing + /// none reads paths alone, as before. + #[test] + fn a_kind_not_listed_is_refused_naming_it() { + let v = rich().to_string(); + for (kinds, named) in [ + (&[OutputKind::Image, OutputKind::Layer, OutputKind::Artboard][..], "`type`"), + (&[OutputKind::Type, OutputKind::Layer, OutputKind::Artboard][..], "`image`"), + (&[OutputKind::Type, OutputKind::Image, OutputKind::Artboard][..], "`layer`"), + (&[OutputKind::Type, OutputKind::Image, OutputKind::Layer][..], "`artboard`"), + ] { + let e = decode_with(v.as_bytes(), kinds).unwrap_err().to_string(); + assert!(e.contains(named) && e.contains("`outputKinds` doesn't list"), "{named}: {e}"); + } + let typed = r#"{"objects":[{"type":"type","text":"a","fontFamily":"x","fontSize":12}]}"#; + assert!(decode(typed.as_bytes()).unwrap_err().to_string().contains("`type` must be \"path\" or \"compound\"")); + let layered = format!(r#"{{"objects":[{SQUARE}],"layers":[{{"name":"A","objects":[0]}}]}}"#); + assert!(decode(layered.as_bytes()).unwrap_err().to_string().contains("not `layers`")); + assert!(decode(br#"{"objects":[],"artboards":[]}"#).unwrap_err().to_string().contains("not `artboards`")); + } + + /// Each limit refuses the whole output and names the limit. + #[test] + fn each_limit_is_enforced_naming_it() { + let names = |n: usize| (0..n).map(|i| json!({"name": format!("L{i}")})).collect::>(); + let cases: Vec<(Edit, String)> = vec![ + (Box::new(move |v: &mut Value| v["layers"] = json!(names(MAX_LAYERS + 1))), format!("1 to {MAX_LAYERS} entries")), + (Box::new(|v: &mut Value| v["layers"] = json!([])), "1 to".into()), + ( + Box::new(|v: &mut Value| { + v["artboards"] = json!((0..=MAX_ARTBOARDS).map(|i| json!({"name": format!("A{i}"), "rect": [0, 0, 1, 1]})).collect::>()) + }), + format!("1 to {MAX_ARTBOARDS} entries"), + ), + (Box::new(|v: &mut Value| v["objects"][0]["text"] = json!("x".repeat(MAX_TYPE_TEXT + 1))), format!("(limit {MAX_TYPE_TEXT})")), + ( + Box::new(|v: &mut Value| v["objects"][1]["pixelSize"] = json!([MAX_IMAGE_SIDE + 1, 1])), + format!("(limit {MAX_IMAGE_SIDE} pixels a side)"), + ), + (Box::new(|v: &mut Value| v["objects"][0]["fontSize"] = json!(TYPE_SIZES.1 * 2.0)), "`fontSize` must be between".into()), + ( + Box::new(|v: &mut Value| v["objects"][0]["fontFamily"] = json!("f".repeat(MAX_NAME_CHARS + 1))), + format!("1-{MAX_NAME_CHARS} characters"), + ), + ]; + for (edit, says) in cases { + let e = rich_with(edit).unwrap_err().to_string(); + assert!(e.contains(&says), "{says}: {e}"); + } + // Totals over all type and all images, found from the sizes they give before any pixels are + // decoded: these images carry no pixels at all. + let big = json!({"type": "image", "pixelSize": [MAX_IMAGE_SIDE, MAX_IMAGE_SIDE]}); + let e = decode_with(json!({"objects": [big]}).to_string().as_bytes(), ALL).unwrap_err().to_string(); + assert!(e.contains(&format!("more than {MAX_PIXEL_BYTES} bytes of pixels")), "{e}"); + let text = "t".repeat(MAX_TYPE_TEXT); + let many: Vec = (0..=MAX_TEXT_TOTAL / MAX_TYPE_TEXT).map(|_| json!({"type": "type", "text": text, "fontSize": 12})).collect(); + let e = decode_with(json!({"objects": many}).to_string().as_bytes(), ALL).unwrap_err().to_string(); + assert!(e.contains(&format!("more than {MAX_TEXT_TOTAL} bytes of text")), "{e}"); + } + + /// An image whose bytes aren't 4 × width × height, or aren't base64, is refused; so are names + /// holding control or direction characters, text holding control characters, layers that don't + /// hold each object once in order, and bad artboards. + #[test] + fn malformed_content_is_refused() { + let cases: Vec<(Edit, &str)> = vec![ + (Box::new(|v: &mut Value| v["objects"][1]["pixelsBase64"] = json!(craft_vectorcraft_format::base64::encode(&[1, 2, 3, 4]))), "= 8 bytes"), + (Box::new(|v: &mut Value| v["objects"][1]["pixelsBase64"] = json!("!!!!!!!!!!!!")), "= 8 bytes"), + (Box::new(|v: &mut Value| v["objects"][1]["pixelSize"] = json!([0, 1])), "`pixelSize`"), + (Box::new(|v: &mut Value| v["objects"][1]["linked"] = json!(true)), "unknown field `linked`"), + (Box::new(|v: &mut Value| v["objects"][0]["kind"] = json!("area")), "unknown field `kind`"), + (Box::new(|v: &mut Value| v["objects"][0]["text"] = json!("a\u{7}b")), "control characters"), + (Box::new(|v: &mut Value| v["objects"][0]["fill"] = json!({"type": "pattern", "pattern": "p"})), "objects[0]"), + (Box::new(|v: &mut Value| v["objects"][0]["transform"] = json!([0, 0, 0, 0, 0, 0])), "six finite numbers"), + (Box::new(|v: &mut Value| v["layers"][0]["name"] = json!("Art\u{202E}txt")), "text direction characters"), + (Box::new(|v: &mut Value| v["artboards"][0]["name"] = json!("A\u{0}")), "text direction characters"), + (Box::new(|v: &mut Value| v["layers"][0]["objects"] = json!([2, 1])), "increasing order"), + (Box::new(|v: &mut Value| v["layers"][0]["objects"] = json!([0, 1, 2])), "object 0 must be in exactly one layer"), + (Box::new(|v: &mut Value| v["layers"][0]["objects"] = json!([1])), "object 2 must be in exactly one layer"), + (Box::new(|v: &mut Value| v["layers"][0]["objects"] = json!([1, 2, 3])), "each below 3"), + (Box::new(|v: &mut Value| v["artboards"][1]["name"] = json!("Front")), "`Front` is used twice"), + (Box::new(|v: &mut Value| v["artboards"][0]["rect"] = json!([0, 0, 0, 10])), "width and height above 0"), + (Box::new(|v: &mut Value| v["artboards"][0]["rect"] = json!([3_999_999, 0, 10, 10])), "within ±4000000"), + ]; + for (edit, says) in cases { + let e = rich_with(edit).unwrap_err().to_string(); + assert!(e.contains(says), "{says}: {e}"); + } + } + #[test] fn warnings_are_capped_in_number_and_length() { let many: Vec = (0..crate::export::MAX_WARNINGS + 5).map(|i| format!("w{i}")).collect(); diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index 4b7ee76f4a..2bc3c73f8a 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -26,7 +26,8 @@ //! time it is drawn, from an appearance stack, and at `api` 2 may paint what it returns //! ([`painted`]); an **exporter** ([`export`]) writes the whole //! document in a file format of its own; an **importer** ([`import`]) reads a file in a format of -//! its own into a new document; a **generator** ([`generate`]) draws art from its parameters alone, +//! its own into a new document, and at `api` 4 may also return type, embedded images, layers and +//! artboards ([`OutputKind`]); a **generator** ([`generate`]) draws art from its parameters alone, //! which the document keeps with them so the art can be drawn again. The process-wide [`registry`] holds the installed //! plug-ins; in [`safe_mode`] none of them loads or runs. A plug-in's parameters ([`manifest`]) come with what the host's dialogs need to show //! them well: labels, units, groups, help and conditions ([`dialog`]). What a plug-in may do is @@ -65,7 +66,8 @@ pub mod worker; pub use dialog::ParamUi; pub use host::{LogLevel, LogLine, Report}; pub use manifest::{ - Budget, Command, ContextMenu, ContextPlace, ContextSection, ContextWhen, InputKind, Kind, Manifest, MenuPlace, Param, ParamSpec, Runtime, + Budget, Command, ContextMenu, ContextPlace, ContextSection, ContextWhen, InputKind, Kind, Manifest, MenuPlace, OutputKind, Param, ParamSpec, + Runtime, }; pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, RunJob, Step, heavy_terms, keep_modules}; #[doc(hidden)] diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index 7fa54caa42..ac27f830dc 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{Map, Value, json}; use crate::dialog::ParamUi; -use crate::permissions::{self, API_LEVEL, APPEARANCE_API, CONTEXT_API, INPUTS_API, PROGRESS_API, Permission, WRITES_API}; +use crate::permissions::{self, API_LEVEL, APPEARANCE_API, CONTEXT_API, INPUTS_API, OUTPUT_KINDS_API, PROGRESS_API, Permission, WRITES_API}; use crate::{Error, Result}; /// Longest manifest the host reads. @@ -289,6 +289,41 @@ impl InputKind { } } +/// A kind of content an importer may return besides paths and compound paths (its manifest's +/// `outputKinds`, plug-in API level 4). Output holding a kind its manifest doesn't list is refused +/// ([`crate::import::decode_with`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum OutputKind { + /// Point type: its text, font family and style, size and fill. + Type, + /// An embedded image: its size in pixels and its RGBA pixels. + Image, + /// Top-level layers: their names, whether they show and are locked, and the objects each holds. + Layer, + /// Artboards: their names and rectangles. + Artboard, +} + +impl OutputKind { + /// Every kind, in the order the docs list them. + pub const ALL: [OutputKind; 4] = [OutputKind::Type, OutputKind::Image, OutputKind::Layer, OutputKind::Artboard]; + + /// Its name in `outputKinds`. A type or an image object's `type` in the output is this name too. + pub fn name(self) -> &'static str { + match self { + OutputKind::Type => "type", + OutputKind::Image => "image", + OutputKind::Layer => "layer", + OutputKind::Artboard => "artboard", + } + } + + /// The kind named `name`. + pub fn parse(name: &str) -> Option { + OutputKind::ALL.into_iter().find(|k| k.name() == name) + } +} + /// A part of the active document a filter or a plug-in command asks to be given in /// `_context.document`, with or without a selection (its manifest's `context`, plug-in API level 3): /// plain values to read, never objects. @@ -639,6 +674,11 @@ pub struct Manifest { /// lists them. Left out or empty, it is given paths and compound paths alone. #[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "input_names")] pub inputs: Vec, + /// The kinds of content an importer returns besides paths and compound paths, by + /// [`OutputKind::name`]: only an importer at `api` 4 or later lists them. Left out or empty, it + /// returns paths and compound paths alone. + #[serde(default, rename = "outputKinds", skip_serializing_if = "Vec::is_empty", deserialize_with = "output_kind_names")] + pub output_kinds: Vec, /// The kinds among `inputs` the filter may change, by [`InputKind::name`]: only a filter at /// `api` 3 or later whose `permissions` list `doc.read` and `doc.write` lists them. Left out or /// empty, every kind it reads stays read-only. @@ -727,6 +767,7 @@ impl Manifest { api: 1, permissions: None, inputs: Vec::new(), + output_kinds: Vec::new(), writes: Vec::new(), context: Vec::new(), params: Vec::new(), @@ -818,6 +859,7 @@ impl Manifest { return Err(Error::Manifest(format!("permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API}"))); } self.validate_inputs()?; + self.validate_output_kinds()?; self.validate_writes()?; self.validate_context()?; if self.paint_output && (self.kind != Kind::Effect || self.api < 2) { @@ -948,6 +990,30 @@ impl Manifest { Ok(()) } + /// `outputKinds` names each [`OutputKind`] at most once, and only an importer at `api` + /// [`OUTPUT_KINDS_API`] or later lists any. + fn validate_output_kinds(&self) -> Result<()> { + if self.output_kinds.is_empty() { + return Ok(()); + } + if self.kind != Kind::Importer { + return Err(Error::Manifest("only an importer declares `outputKinds`".into())); + } + for (i, name) in self.output_kinds.iter().enumerate() { + let shown = permissions::display_text(name, permissions::MAX_SHOWN_FIELD); + if OutputKind::parse(name).is_none() { + return Err(Error::Manifest(format!("`outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard"))); + } + if self.output_kinds.get(..i).is_some_and(|before| before.contains(name)) { + return Err(Error::Manifest(format!("`outputKinds` lists `{shown}` twice"))); + } + } + if self.api < OUTPUT_KINDS_API { + return Err(Error::Manifest(format!("`outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API}"))); + } + Ok(()) + } + /// `writes` names each [`InputKind`] at most once, each one `inputs` lists, and only a filter at /// `api` 3 or later lists any, with a `permissions` list that holds `doc.read` and `doc.write`. fn validate_writes(&self) -> Result<()> { @@ -1001,6 +1067,11 @@ impl Manifest { Ok(()) } + /// The kinds of content besides paths and compound paths an importer returns (`outputKinds`). + pub fn output_kinds(&self) -> Vec { + self.output_kinds.iter().filter_map(|n| OutputKind::parse(n)).collect() + } + /// The parts of the document it asks to be given (`context`). pub fn context_sections(&self) -> Vec { self.context.iter().filter_map(|n| ContextSection::parse(n)).collect() @@ -1226,6 +1297,17 @@ fn input_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result>(d: D) -> std::result::Result, D::Error> { + let wrong = || serde::de::Error::custom("`outputKinds` must be a list of kinds: type, image, layer or artboard"); + match Value::deserialize(d)? { + Value::Null => Ok(Vec::new()), + Value::Array(names) => names.into_iter().map(|n| if let Value::String(s) = n { Ok(s) } else { Err(wrong()) }).collect(), + _ => Err(wrong()), + } +} + /// Reads `writes` as [`input_names`] reads `inputs`. fn write_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result, D::Error> { let wrong = || serde::de::Error::custom("`writes` must be a list of object kinds: type, image or symbolInstance"); @@ -1689,7 +1771,7 @@ mod tests { (r#"{"id":"a","name":"x","kind":"filter","api":1,"permissions":["progress"]}"#, "`progress` needs plug-in API level 2"), (r#"{"id":"a","name":"x","kind":"filter","permissions":["settings"]}"#, "`settings` needs plug-in API level 2"), (r#"{"id":"a","name":"x","kind":"filter","api":1,"permissions":["doc.read","cache"]}"#, "`cache` needs plug-in API level 2"), - (r#"{"id":"a","name":"x","kind":"filter","api":4}"#, "`api` is 4; this host implements plug-in API levels 1 to 3"), + (r#"{"id":"a","name":"x","kind":"filter","api":5}"#, "`api` is 5; this host implements plug-in API levels 1 to 4"), (r#"{"id":"a","name":"x","kind":"filter","api":0}"#, "`api` is 0"), (r#"{"id":"a","name":"x","kind":"filter","api":-1}"#, "manifest"), ] { @@ -1698,6 +1780,46 @@ mod tests { } } + /// An importer at `api` 4 lists the kinds it returns besides paths (`outputKinds`), each once; + /// another kind of plug-in, an earlier level, an unknown kind or a repeat is refused naming + /// `outputKinds`. Left out or empty, it lists none and isn't written back. + #[test] + fn an_importer_at_api_4_lists_the_kinds_it_returns() { + let m = Manifest::parse( + br#"{"id":"a","name":"x","kind":"importer","api":4,"extensions":["tst"],"outputKinds":["type","image","layer","artboard"]}"#, + ) + .unwrap(); + assert_eq!(m.output_kinds(), OutputKind::ALL); + assert_eq!(serde_json::to_value(&m).unwrap()["outputKinds"], json!(["type", "image", "layer", "artboard"])); + assert_eq!(m.permissions(), [Permission::ImportRead]); + for none in [ + r#"{"id":"a","name":"x","kind":"importer","extensions":["tst"]}"#, + r#"{"id":"a","name":"x","kind":"importer","api":4,"extensions":["tst"],"outputKinds":[]}"#, + r#"{"id":"a","name":"x","kind":"importer","extensions":["tst"],"outputKinds":null}"#, + ] { + let m = Manifest::parse(none.as_bytes()).unwrap(); + assert!(m.output_kinds().is_empty(), "{none}"); + assert!(serde_json::to_value(&m).unwrap().get("outputKinds").is_none(), "{none}"); + } + for (bad, says) in [ + (r#"{"id":"a","name":"x","kind":"importer","extensions":["tst"],"outputKinds":["type"]}"#, "`outputKinds` needs plug-in API level 4"), + (r#"{"id":"a","name":"x","kind":"importer","api":2,"extensions":["tst"],"outputKinds":["layer"]}"#, "give `api` 4"), + (r#"{"id":"a","name":"x","kind":"importer","api":3,"extensions":["tst"],"outputKinds":["image"]}"#, "give `api` 4"), + (r#"{"id":"a","name":"x","kind":"filter","api":4,"outputKinds":["type"]}"#, "only an importer declares `outputKinds`"), + ( + r#"{"id":"a","name":"x","kind":"exporter","api":4,"extensions":["tst"],"outputKinds":["image"]}"#, + "only an importer declares `outputKinds`", + ), + (r#"{"id":"a","name":"x","kind":"importer","api":4,"extensions":["tst"],"outputKinds":["text"]}"#, "unknown kind `text`"), + (r#"{"id":"a","name":"x","kind":"importer","api":4,"extensions":["tst"],"outputKinds":["image","image"]}"#, "lists `image` twice"), + (r#"{"id":"a","name":"x","kind":"importer","api":4,"extensions":["tst"],"outputKinds":"type"}"#, "`outputKinds` must be a list"), + (r#"{"id":"a","name":"x","kind":"importer","api":4,"extensions":["tst"],"outputKinds":[1]}"#, "`outputKinds` must be a list"), + ] { + let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string(); + assert!(e.contains(says), "{bad}: {e}"); + } + } + /// A filter at `api` 2 may ask for type, images and symbol instances (`inputs`), each kind once, /// with a `permissions` list holding `doc.read`, so installing it asks for approval. Left out /// or empty, it asks for none and isn't written back. Anything else is refused naming `inputs`. diff --git a/crates/plugins/src/objects.rs b/crates/plugins/src/objects.rs index 4331faf49a..f1081891d5 100644 --- a/crates/plugins/src/objects.rs +++ b/crates/plugins/src/objects.rs @@ -603,7 +603,7 @@ pub(crate) fn clamp_color(c: Color) -> Color { /// A paint from plug-in output (`null`: none), with colors, process plates, opacities and /// offsets clamped and gradient and pattern placements checked. -fn decode_paint(v: &Value, at: &str) -> Result { +pub(crate) fn decode_paint(v: &Value, at: &str) -> Result { if v.is_null() { return Ok(Paint::None); } @@ -693,7 +693,7 @@ fn opt<'a>(o: &'a serde_json::Map, key: &str) -> Option<&'a Value /// Object `v` of a plug-in's output (`at` names it in errors), its anchors added to `anchors` and /// held to [`MAX_ANCHORS`]: each key it has checked, numbers clamped into range, as [`decode`] reads /// them. -fn decode_object(v: &Value, at: &str, anchors: &mut usize) -> Result { +pub(crate) fn decode_object(v: &Value, at: &str, anchors: &mut usize) -> Result { let o = v.as_object().ok_or_else(|| out_err(at, "an object must be a JSON object"))?; let mut out = OutObject::default(); if let Some(id) = opt(o, "id") { @@ -1061,7 +1061,7 @@ fn paints(ap: &Appearance, fill: bool) -> Vec<&Paint> { /// `p` without swatch links: a plug-in's colours are its own, so only paints it returned /// unchanged keep theirs. A gradient stop also loses its process plates, which print only with /// a spot swatch. -fn unlinked(mut p: Paint) -> Paint { +pub(crate) fn unlinked(mut p: Paint) -> Paint { match &mut p { Paint::Solid { swatch, tint, .. } => { *swatch = None; @@ -1358,6 +1358,21 @@ impl Plan { } } +/// New object `o` of a plug-in's output (`at` names it in errors) as a node of `doc`, not yet in it: +/// a path or a compound path made as [`apply_output`] makes one, its effects admitted by `admit`. +/// An object with an `id` or without a `path` is an error. +pub fn new_object(doc: &mut Document, o: OutObject, at: &str, admit: AdmitEffects) -> Result { + if let Some(id) = o.id { + return Err(out_err(at, format!("{} is not the id of an input object", id.0))); + } + if o.path.is_none() { + return Err(out_err(at, "a new object needs a `path`")); + } + let mut n = Node::path(doc.alloc_id(), PathData::default(), Appearance::default()); + write(doc, &mut n, o, at, admit)?; + Ok(n) +} + /// Applies an object filter's output to `doc`. /// /// `inputs` are the objects the plug-in was given, in paint order ([`filter_targets`]). Output diff --git a/crates/plugins/src/permissions.rs b/crates/plugins/src/permissions.rs index f1af2b17ef..a82c5a5335 100644 --- a/crates/plugins/src/permissions.rs +++ b/crates/plugins/src/permissions.rs @@ -16,8 +16,13 @@ use crate::{Error, Kind, Result}; /// The plug-in API level this host implements. A manifest's `api` (1 when left out) may be at most /// this. Level 2 adds the host imports ([`PROGRESS_API`]) and a live effect's `paintOutput` /// ([`crate::painted`]); level 3 adds a filter's `writes` ([`WRITES_API`]), a live effect's -/// `appearanceOutput` ([`APPEARANCE_API`]) and a manifest's `context` ([`CONTEXT_API`]). -pub const API_LEVEL: u32 = 3; +/// `appearanceOutput` ([`APPEARANCE_API`]) and a manifest's `context` ([`CONTEXT_API`]). Level 4 +/// adds an importer's `outputKinds` ([`OUTPUT_KINDS_API`]). +pub const API_LEVEL: u32 = 4; + +/// The API level that adds an importer's `outputKinds` ([`crate::OutputKind`]): type, embedded +/// images, layers and artboards in what it returns ([`crate::import`]). +pub const OUTPUT_KINDS_API: u32 = 4; /// The API level that adds a painted live effect's `appearanceOutput`: opacity, a blending mode /// and effects on the pieces it returns and on their fills and strokes ([`crate::painted`]). diff --git a/crates/render/src/stroke.rs b/crates/render/src/stroke.rs index 307f2c988e..cd5cacac97 100644 --- a/crates/render/src/stroke.rs +++ b/crates/render/src/stroke.rs @@ -9,12 +9,19 @@ use vectorcraft_geom::BezPath; /// Vello flattens the two sides of a filled stroke independently at 0.25 device pixels. /// For strokes narrower than four times the raster tolerance, fit and preflatten the /// band more tightly. Wider strokes and the document/export geometry are unchanged. +/// +/// A plain stroke (no dashes, no width profile) along a line with curves is drawn as lines first +/// ([`thin_line`]) and outlined by [`thin_band`], with one line on each side for each line of the +/// path. Other thin strokes are fitted and flattened at the fine tolerance. pub(crate) fn outline(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64) -> BezPath { if width >= tol * 4.0 { return effects::stroke::line_outline(line, st, width, tol); } // Closed endpoint rounding must not consume a substantial part of a subpixel band. let fine = (tol / 8.0).min(width / 32.0).max(1e-4); + if let Some(band) = thin_line(line, st, width).and_then(|lines| thin_band(&lines, st, width, fine)) { + return band; + } let outline = effects::stroke::line_outline(line, st, width, fine); let mut flat = BezPath::new(); // Keep upstream's per-curve work cap for untrusted or extreme coordinates. @@ -22,6 +29,169 @@ pub(crate) fn outline(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64) -> flat } +/// The lines a thin stroke's curves are drawn with lie within about this share of its width of the +/// curve, before their ends are moved out ([`draw_lines`]). +const THIN_CHORD: f64 = 1.0 / 6.0; +/// Where two lines of a thin stroke meet at an angle whose sine is at most this, and turn by less +/// than a right angle, [`thin_band`] offsets both sides to where the two lines' offsets cross, +/// whatever the stroke's join. +const THIN_SMOOTH: f64 = 0.8; + +/// `line` with all its curves drawn as lines within about [`THIN_CHORD`] of `width` of them, for a +/// stroke `st` narrower than four raster tolerances ([`outline`]). `None` for a stroke with a width +/// profile or dashes, for a line with no curves, and when a curve can't be drawn as lines +/// ([`lines`]). +fn thin_line(line: &BezPath, st: &StrokeLayer, width: f64) -> Option { + if st.profile.is_some() || st.dash.is_some() || !(width > 0.0 && width.is_finite()) { + return None; + } + let lines = lines(line, 0.0, width * THIN_CHORD)?; + lines.elements().iter().all(|el| !matches!(el, PathEl::QuadTo(..) | PathEl::CurveTo(..))).then_some(lines) +} + +/// The outline of stroke `st` at `width` along `lines`, a path of lines only ([`thin_line`]), to fill +/// with the non-zero rule. Each side of each line is offset by half the width. Where two lines meet +/// at a small angle ([`THIN_SMOOTH`]) both sides go to where the offsets cross; elsewhere the +/// stroke's join is drawn, and an open subpath ends in the stroke's caps, with round parts drawn as +/// lines within `fine` of their arcs. `None` when a subpath has fewer than two distinct points or a +/// point that isn't finite, or is closed and no wider or taller than the stroke: those take +/// [`effects::stroke::line_outline`]. +fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option { + let h = width / 2.0; + // The angle between two points of an arc of radius `h` drawn as lines within `fine` of it. + let step = 2.0 * (1.0 - (fine / h).min(1.0)).acos().max(1e-3); + let mut out = BezPath::new(); + let mut pts: Vec = Vec::new(); + let mut closed = false; + let flush = |pts: &mut Vec, closed: bool, out: &mut BezPath| -> Option<()> { + if pts.is_empty() { + return Some(()); + } + if closed && pts.len() > 1 && pts.first() == pts.last() { + pts.pop(); + } + if pts.len() < 2 || !pts.iter().all(|p| p.is_finite()) { + return None; + } + if closed { + let (lo, hi) = + pts.iter().fold((pts[0], pts[0]), |(lo, hi), p| (Point::new(lo.x.min(p.x), lo.y.min(p.y)), Point::new(hi.x.max(p.x), hi.y.max(p.y)))); + if (hi.x - lo.x).min(hi.y - lo.y) <= width { + return None; + } + } + band_sub(out, pts, closed, st, h, step); + pts.clear(); + Some(()) + }; + for el in lines.elements() { + match *el { + PathEl::MoveTo(p) => { + flush(&mut pts, closed, &mut out)?; + closed = false; + pts.push(p); + } + PathEl::LineTo(p) => { + if pts.last() != Some(&p) { + pts.push(p); + } + } + PathEl::ClosePath => closed = true, + PathEl::QuadTo(..) | PathEl::CurveTo(..) => return None, + } + } + flush(&mut pts, closed, &mut out)?; + Some(out) +} + +/// Adds the outline of one subpath with the distinct points `pts` (at least two, the last not +/// repeating the first when `closed`) to `out`: for an open subpath one contour, its left side, +/// the end cap, its right side backward and the start cap; for a closed one its left side and its +/// right side backward, as two contours. `h` is half the width and `step` the angle between the +/// points of a round join or cap. +fn band_sub(out: &mut BezPath, pts: &[Point], closed: bool, st: &StrokeLayer, h: f64, step: f64) { + use vectorcraft_doc::{LineCap, LineJoin}; + let n = pts.len(); + let chords = if closed { n } else { n - 1 }; + // The direction of line `i` (from point `i` to the next) as a unit vector, and its normal. + let dir = |i: usize| (pts[(i + 1) % n] - pts[i % n]).normalize(); + let norm = |u: Vec2| Vec2::new(-u.y, u.x); + // Points on an arc of radius `h` around `c` from `from` to `to` (both of length `h`), turning + // by `angle` (positive: from `from` toward its normal), without its first point. + let arc = |side: &mut Vec, c: Point, from: Vec2, angle: f64| { + let k = (angle.abs() / step).ceil().max(1.0) as usize; + for j in 1..=k { + let a = angle * j as f64 / k as f64; + let (s, co) = a.sin_cos(); + side.push(c + Vec2::new(from.x * co - from.y * s, from.x * s + from.y * co)); + } + }; + let (mut left, mut right) = (Vec::with_capacity(n + 2), Vec::with_capacity(n + 2)); + let join = |left: &mut Vec, right: &mut Vec, p: Point, ua: Vec2, ub: Vec2| { + let (na, nb) = (norm(ua) * h, norm(ub) * h); + let (cross, dot) = (ua.cross(ub), ua.dot(ub)); + // Where the offsets of the two lines cross, on the right side; the left one is opposite. + let miter = (na + nb) / (1.0 + dot); + if dot > 0.0 && cross.abs() <= THIN_SMOOTH { + left.push(p - miter); + right.push(p + miter); + return; + } + // The outer side of the turn: the left side when the path turns toward its normal. + let (outer, inner, sign) = if cross > 0.0 { (left, right, -1.0) } else { (right, left, 1.0) }; + inner.push(p - na * sign); + inner.push(p); + inner.push(p - nb * sign); + outer.push(p + na * sign); + match st.join { + LineJoin::Miter if 2.0 < (1.0 + dot) * st.miter_limit.powi(2) => outer.push(p + miter * sign), + LineJoin::Round => arc(outer, p, na * sign, cross.atan2(dot)), + LineJoin::Miter | LineJoin::Bevel => {} + } + outer.push(p + nb * sign); + }; + if closed { + for (i, &p) in pts.iter().enumerate() { + join(&mut left, &mut right, p, dir(i + n - 1), dir(i)); + } + contour(out, left.iter().copied()); + contour(out, right.iter().rev().copied()); + return; + } + let (first, last) = (dir(0), dir(chords - 1)); + let square = |u: Vec2| if st.cap == LineCap::Square { u * h } else { Vec2::ZERO }; + left.push(pts[0] - norm(first) * h - square(first)); + right.push(pts[0] + norm(first) * h - square(first)); + for (i, &p) in pts.iter().enumerate().take(chords).skip(1) { + join(&mut left, &mut right, p, dir(i - 1), dir(i)); + } + let end = pts[n - 1]; + left.push(end - norm(last) * h + square(last)); + right.push(end + norm(last) * h + square(last)); + let mut ring = left; + if st.cap == LineCap::Round { + arc(&mut ring, end, -norm(last) * h, std::f64::consts::PI); + ring.pop(); + } + ring.extend(right.iter().rev().copied()); + if st.cap == LineCap::Round { + arc(&mut ring, pts[0], norm(first) * h, std::f64::consts::PI); + ring.pop(); + } + contour(out, ring.into_iter()); +} + +/// Adds the closed contour through `pts` to `out`. +fn contour(out: &mut BezPath, mut pts: impl Iterator) { + if let Some(p) = pts.next() { + out.move_to(p); + for p in pts { + out.line_to(p); + } + out.close_path(); + } +} + /// Strokes at least this many tolerances wide (8 device pixels at a tolerance of 0.25 px) have /// their long curves drawn as lines by [`wide`]. const WIDE: f64 = 32.0; @@ -63,7 +233,7 @@ pub(crate) fn wide(outline: BezPath, width: f64, tol: f64) -> BezPath { if !(tol > 0.0 && tol.is_finite() && width >= tol * WIDE) { return outline; } - lines(&outline, tol).unwrap_or(outline) + lines(&outline, tol * SPAN, tol * CHORD).unwrap_or(outline) } /// One subpath: where it starts, its segments, each with the most steps it is drawn with as lines @@ -74,11 +244,11 @@ struct Sub { closed: bool, } -/// `path` with its long curves drawn as lines ([`wide`]); `None` when it has no long curve, would +/// `path` with its curves whose control points span at least `span` across or down drawn as lines +/// within about `chord` of them ([`wide`], [`thin_line`]); `None` when it has no such curve, would /// take more than [`MAX_LINES`] lines, or does not start each subpath with a move. -fn lines(path: &BezPath, tol: f64) -> Option { - let chord = tol * CHORD; - let subs = subpaths(path.elements(), tol, chord)?; +fn lines(path: &BezPath, span: f64, chord: f64) -> Option { + let subs = subpaths(path.elements(), span, chord)?; let mut total = 0usize; for (_, steps) in subs.iter().flat_map(|s| &s.segs) { if *steps > 0 { @@ -98,7 +268,7 @@ fn lines(path: &BezPath, tol: f64) -> Option { /// The subpaths of `els`, each segment with its steps ([`steps`]). A close adds a line back to the /// start when the subpath ends elsewhere. `None` when a segment comes before any move or after a /// close without a move. -fn subpaths(els: &[PathEl], tol: f64, chord: f64) -> Option> { +fn subpaths(els: &[PathEl], span: f64, chord: f64) -> Option> { let mut subs: Vec = Vec::new(); for el in els { if let PathEl::MoveTo(p) = *el { @@ -122,7 +292,7 @@ fn subpaths(els: &[PathEl], tol: f64, chord: f64) -> Option> { continue; } }; - sub.segs.push((seg, steps(seg, tol, chord))); + sub.segs.push((seg, steps(seg, span, chord))); } Some(subs) } @@ -137,10 +307,10 @@ fn cubic(seg: PathSeg) -> Option { } /// How many equal steps of its parameter keep the chords of curve `seg` within `chord` of it (by -/// the second differences of its control points), when its control points span at least [`SPAN`] -/// times `tol`; 0 for a line, a shorter curve, a curve with a point that isn't finite, and a curve -/// that would take more than [`MAX_LINES`] steps. -fn steps(seg: PathSeg, tol: f64, chord: f64) -> usize { +/// the second differences of its control points), when its control points span at least `min` +/// across or down; 0 for a line, a shorter curve, a curve with a point that isn't finite, and a +/// curve that would take more than [`MAX_LINES`] steps. +fn steps(seg: PathSeg, min: f64, chord: f64) -> usize { let Some(c) = cubic(seg) else { return 0 }; let pts = [c.p0, c.p1, c.p2, c.p3]; if !pts.iter().all(|p| p.is_finite()) { @@ -150,7 +320,7 @@ fn steps(seg: PathSeg, tol: f64, chord: f64) -> usize { (Point::new(lo.x.min(p.x), lo.y.min(p.y)), Point::new(hi.x.max(p.x), hi.y.max(p.y))) }); let span = (hi.x - lo.x).max(hi.y - lo.y); - if !span.is_finite() || span < tol * SPAN { + if !span.is_finite() || span < min { return 0; } let second = |a: Point, b: Point, c: Point| (a.to_vec2() - b.to_vec2() * 2.0 + c.to_vec2()).hypot(); @@ -175,13 +345,19 @@ fn end_tangent(c: &CubicBez) -> Option { /// How many pieces of a curve [`params`] measures its bending on. const SAMPLES: usize = 32; +/// A chord whose curve lies more than this many times `chord` from it ([`off_chord`]) is drawn with +/// more steps ([`params`]). +const FIT: f64 = 2.0; + /// The parameters curve `c` has its line ends at, and whether its first and its last step are /// halves. Each step holds an equal share of the curve's bending (the integral of the square root /// of its curvature along it), and there are as many as keep each chord within about `chord` of the -/// curve, at most `most` (its equal steps, [`steps`]). The steps are equal when the bending can't -/// be measured (a cusp, or a point that isn't finite) or is 0. The first or last step is halved -/// when that end stays on the curve (`pin_start`, `pin_end`); a curve of one step is then drawn -/// in two halves. +/// curve, at most `most` (its equal steps, [`steps`]). When the curve between two line ends lies +/// more than [`FIT`] times `chord` from their chord ([`off_chord`]), as where a curve turns back +/// within a step, the count doubles, up to `most`; when `most` such steps still don't fit, the +/// steps are equal. The steps are also equal when the bending can't be measured (a cusp, or a point +/// that isn't finite) or is 0. The first or last step is halved when that end stays on the curve +/// (`pin_start`, `pin_end`); a curve of one step is then drawn in two halves. fn params(c: &CubicBez, most: usize, chord: f64, pin_start: bool, pin_end: bool) -> (Vec, (bool, bool)) { let (d1, d2) = (c.deriv(), c.deriv().deriv()); let bend = |u: f64| { @@ -197,39 +373,109 @@ fn params(c: &CubicBez, most: usize, chord: f64, pin_start: bool, pin_end: bool) } let total = sums[SAMPLES]; let most = most.max(1); - let n = if total.is_finite() && total > 0.0 { ((total / SAMPLES as f64 / (8.0 * chord).sqrt()).ceil() as usize).clamp(1, most) } else { most }; // The parameter at which a share `s` (0 to 1) of the bending lies before it. let at = |s: f64| -> f64 { - if !(total.is_finite() && total > 0.0) { - return s; - } let want = s * total; let j = sums.partition_point(|&x| x <= want).clamp(1, SAMPLES); let (lo, hi) = (sums[j - 1], sums[j]); let part = if hi > lo { ((want - lo) / (hi - lo)).clamp(0.0, 1.0) } else { 0.0 }; (j as f64 - 1.0 + part) / SAMPLES as f64 }; - if n == 1 && (pin_start || pin_end) { - return (vec![0.0, at(0.5), 1.0], (true, true)); + // The line ends of `n` steps, each holding a share `step(s)` of the curve. + let cut = |n: usize, step: &dyn Fn(f64) -> f64| -> (Vec, (bool, bool)) { + if n == 1 && (pin_start || pin_end) { + return (vec![0.0, step(0.5), 1.0], (true, true)); + } + let h = 1.0 / n as f64; + let mut t = Vec::with_capacity(n + 3); + t.push(0.0); + if pin_start { + t.push(step(h / 2.0)); + } + t.extend((1..n).map(|k| step(k as f64 * h))); + if pin_end { + t.push(step(1.0 - h / 2.0)); + } + t.push(1.0); + (t, (pin_start, pin_end)) + }; + if total.is_finite() && total > 0.0 { + let mut n = ((total / SAMPLES as f64 / (8.0 * chord).sqrt()).ceil() as usize).clamp(1, most); + loop { + let fit = cut(n, &at); + if fit.0.windows(2).all(|w| off_chord(c, w[0], w[1]) <= FIT * chord) { + return fit; + } + if n >= most { + break; + } + n = n.saturating_mul(2).min(most); + } } - let h = 1.0 / n as f64; - let mut t = Vec::with_capacity(n + 3); - t.push(0.0); - if pin_start { - t.push(at(h / 2.0)); + cut(most, &|s| s) +} + +/// How far curve `c` between parameters `a` and `b` lies from the chord between its points there: +/// the farthest it lies to either side of the chord's line, or before the chord's start or past its +/// end along it. For a chord of no length, the farthest the curve's control points between `a` and +/// `b` lie from it. +fn off_chord(c: &CubicBez, a: f64, b: f64) -> f64 { + let (p, q) = (c.eval(a), c.eval(b)); + let along = q - p; + let len = along.hypot(); + if !(len > 0.0 && len.is_finite()) { + let s = c.subsegment(a..b); + return [s.p1, s.p2, s.p3].iter().map(|x| (*x - p).hypot()).fold(0.0, f64::max); } - t.extend((1..n).map(|k| at(k as f64 * h))); - if pin_end { - t.push(at(1.0 - h / 2.0)); + let u = along / len; + // The derivative, t² k2 + t k1 + k0. + let d = c.deriv(); + let (k2, k1, k0) = (d.p0.to_vec2() - d.p1.to_vec2() * 2.0 + d.p2.to_vec2(), (d.p1 - d.p0) * 2.0, d.p0.to_vec2()); + let mut far: f64 = 0.0; + // Where the curve moves along the chord's line or across it, its distance across it or its + // position along it is largest or smallest. + for (a2, a1, a0) in [(k2.cross(u), k1.cross(u), k0.cross(u)), (k2.dot(u), k1.dot(u), k0.dot(u))] { + for t in roots(a2, a1, a0) { + if t > a && t < b { + let v = c.eval(t) - p; + let ahead = v.dot(u); + far = far.max(v.cross(u).abs()).max(-ahead).max(ahead - len); + } + } } - t.push(1.0); - (t, (pin_start, pin_end)) + far +} + +/// The real roots of `a2 t² + a1 t + a0`, with NaN in place of a root that doesn't exist (none when +/// every coefficient is 0). +fn roots(a2: f64, a1: f64, a0: f64) -> [f64; 2] { + if a2 == 0.0 { + return [-a0 / a1, f64::NAN]; + } + let disc = a1 * a1 - 4.0 * a2 * a0; + if disc < 0.0 { + return [f64::NAN; 2]; + } + // The root that adds two numbers of the same sign, and the other from their product. + let r = -(a1 + a1.signum() * disc.sqrt()) / 2.0; + if r == 0.0 { + return [0.0, f64::NAN]; + } + [r / a2, a0 / r] } /// How far the curve `c` lies from the chord between parameters `a` and `b`, at its parameter -/// midway: the curve's point there minus the chord's middle. +/// midway: the part across the chord of the curve's point there minus the chord's middle. A chord +/// of no length keeps the whole difference. fn bulge(c: &CubicBez, a: f64, b: f64) -> Vec2 { - c.eval((a + b) / 2.0) - c.eval(a).midpoint(c.eval(b)) + let (p, q) = (c.eval(a), c.eval(b)); + let gap = c.eval((a + b) / 2.0) - p.midpoint(q); + let along = q - p; + let len2 = along.hypot2(); + if !(len2 > 0.0 && len2.is_finite()) { + return gap; + } + gap - along * (gap.dot(along) / len2) } /// A curve of a subpath drawn as lines: the curve, its line ends' parameters, whether its first and diff --git a/crates/render/src/tests/thincoverage.rs b/crates/render/src/tests/thincoverage.rs index 05bbc23573..4017448fd9 100644 --- a/crates/render/src/tests/thincoverage.rs +++ b/crates/render/src/tests/thincoverage.rs @@ -1,6 +1,137 @@ use super::*; use crate::stroke::outline as raster_stroke_outline; -use vectorcraft_doc::StrokeLayer; +use vectorcraft_doc::{LineCap, LineJoin, StrokeLayer}; + +/// How many lines a fill of `path` takes once flattened at `tol`. +fn lines_at(path: &BezPath, tol: f64) -> usize { + let mut n = 0; + vectorcraft_geom::flatten(path.iter(), tol, |el| n += usize::from(matches!(el, kurbo::PathEl::LineTo(_) | kurbo::PathEl::ClosePath))); + n +} + +/// Whether `path` holds lines only. +fn lines_only(path: &BezPath) -> bool { + path.elements().iter().all(|el| !matches!(el, kurbo::PathEl::QuadTo(..) | kurbo::PathEl::CurveTo(..))) +} + +/// A thin curved stroke's outline takes at most twice the lines the stroke's plain outline takes +/// at the raster tolerance (#7257). 200 cubic curves, each about 100 device pixels across. +#[test] +fn thin_curved_strokes_take_at_most_twice_the_lines_of_their_plain_outline() { + let mut seed: u64 = 7; + let mut r = |lo: f64, hi: f64| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + lo + (hi - lo) * ((seed >> 11) as f64 / (1u64 << 53) as f64) + }; + let mut paths = Vec::new(); + for _ in 0..200 { + let (x, y) = (r(20.0, 980.0), r(20.0, 980.0)); + let mut q = [kurbo::Point::ZERO; 3]; + for p in &mut q { + *p = kurbo::Point::new((x + r(-30.0, 30.0)) * 1.71, (y + r(-30.0, 30.0)) * 1.71); + } + let mut path = BezPath::new(); + path.move_to((x * 1.71, y * 1.71)); + path.curve_to(q[0], q[1], q[2]); + paths.push(path); + } + let tol = 0.25; + for width in [0.5, 0.75, 0.99] { + let st = StrokeLayer::new(Paint::solid(Color::BLACK), width); + let (mut plain, mut thin) = (0, 0); + for path in &paths { + plain += lines_at(&crate::effects::stroke::line_outline(path, &st, width, tol), tol); + let outline = raster_stroke_outline(path, &st, width, tol); + assert!(lines_only(&outline), "width {width}: lines only"); + thin += lines_at(&outline, tol); + } + assert!(thin <= plain * 2, "width {width}: {thin} lines, plain outline {plain}"); + } +} + +/// A thin stroke drawn as lines keeps its caps, its joins and the hole of a closed path. +#[test] +fn thin_strokes_drawn_as_lines_keep_caps_joins_and_holes() { + let (w, tol) = (0.5, 0.25); + // A quarter circle from (100, 100) heading right, then a right-angle corner at (200, 200). + let mut open = BezPath::new(); + open.move_to((100.0, 100.0)); + open.curve_to((155.23, 100.0), (200.0, 144.77), (200.0, 200.0)); + open.line_to((100.0, 200.0)); + for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] { + for join in [LineJoin::Miter, LineJoin::Round, LineJoin::Bevel] { + let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), w); + st.cap = cap; + st.join = join; + let o = raster_stroke_outline(&open, &st, w, tol); + assert!(lines_only(&o), "{cap:?} {join:?}: lines only"); + let inside = |x: f64, y: f64| o.winding(kurbo::Point::new(x, y)) != 0; + assert_eq!(inside(100.0 - 0.4 * w, 100.0), cap != LineCap::Butt, "{cap:?} {join:?}: start cap"); + assert!(!inside(100.0 - 0.6 * w, 100.0), "{cap:?} {join:?}: past the start cap"); + assert_eq!(inside(100.0 - 0.45 * w, 100.0 + 0.45 * w), cap == LineCap::Square, "{cap:?} {join:?}: cap corner"); + assert!( + inside(200.0 + 0.4 * w, 199.0) && inside(200.0 - 0.4 * w, 199.0) && !inside(200.0 + 0.6 * w, 199.0), + "{cap:?} {join:?}: curve end" + ); + assert_eq!(inside(200.0 + 0.3 * w, 200.0 + 0.3 * w), join != LineJoin::Bevel, "{cap:?} {join:?}: corner"); + assert_eq!(inside(200.0 + 0.45 * w, 200.0 + 0.45 * w), join == LineJoin::Miter, "{cap:?} {join:?}: miter tip"); + assert!(inside(150.0, 200.0 + 0.4 * w) && !inside(150.0, 200.0 + 0.6 * w), "{cap:?} {join:?}: line"); + } + } + let ring = kurbo::Circle::new((300.0, 300.0), 50.0).to_path(0.01); + let st = StrokeLayer::new(Paint::solid(Color::BLACK), w); + let o = raster_stroke_outline(&ring, &st, w, tol); + assert!(lines_only(&o), "closed: lines only"); + for k in 0..36 { + let a = f64::from(k) * 10f64.to_radians(); + let at = |r: f64| o.winding(kurbo::Point::new(300.0 + r * a.cos(), 300.0 + r * a.sin())); + assert!(at(50.0 - 0.4 * w) != 0 && at(50.0 + 0.4 * w) != 0, "ring band at {k}"); + assert!(at(50.0 - 0.6 * w) == 0 && at(50.0 + 0.6 * w) == 0, "ring edges at {k}"); + } + assert_eq!(o.winding(kurbo::Point::new(300.0, 300.0)), 0, "the hole"); +} + +/// A thin curve that runs out and back along almost the same line ends where the curve turns +/// back. The curve goes from (0, 0) to x = 75 and back; its outline reaches no further than half +/// the stroke's width past that. +#[test] +fn thin_strokes_drawn_as_lines_stop_where_a_curve_turns_back() { + let (w, tol, e) = (0.5, 0.25, 1e-9); + let mut path = BezPath::new(); + path.move_to((0.0, 0.0)); + path.curve_to((100.0, e / 3.0), (100.0, 2.0 * e / 3.0), (0.0, e)); + let st = StrokeLayer::new(Paint::solid(Color::BLACK), w); + let o = raster_stroke_outline(&path, &st, w, tol); + let inside = |x: f64| o.winding(kurbo::Point::new(x, 0.0)) != 0; + assert!(inside(10.0) && inside(70.0), "the band"); + let far = o.bounding_box().x1; + assert!(far <= 75.0 + w / 2.0 + 1e-6, "the outline reaches x = {far}"); +} + +/// A thin curve that turns back twice keeps both of its turns. The curve runs from (0, 0) out to +/// x = 28.87, back past its start to x = -28.87, and back to (0, 0.001). Its outline covers every +/// point of the curve more than a third of the stroke's width from a turn, reaches both turns to +/// within that, and reaches no further than two thirds of the stroke's width past either turn. +#[test] +fn thin_strokes_drawn_as_lines_keep_both_turns_of_a_curve() { + let (w, tol, e) = (0.5, 0.25, 1e-3); + let c = kurbo::CubicBez::new((0.0, 0.0), (100.0, e / 3.0), (-100.0, 2.0 * e / 3.0), (0.0, e)); + let mut path = BezPath::new(); + path.move_to(c.p0); + path.curve_to(c.p1, c.p2, c.p3); + let st = StrokeLayer::new(Paint::solid(Color::BLACK), w); + let o = raster_stroke_outline(&path, &st, w, tol); + assert!(lines_only(&o), "lines only"); + let turn = kurbo::ParamCurve::eval(&c, (3.0 - 3f64.sqrt()) / 6.0).x; + let near = w / 3.0; + for k in 1..200 { + let p = kurbo::ParamCurve::eval(&c, f64::from(k) / 200.0); + assert!(p.x.abs() > turn - near || o.winding(p) != 0, "the curve at {p:?}"); + } + let (bounds, past) = (o.bounding_box(), w * 2.0 / 3.0); + assert!(bounds.x1 >= turn - near && bounds.x0 <= -turn + near, "the outline reaches both turns: {bounds:?}"); + assert!(bounds.x1 <= turn + past && bounds.x0 >= -turn - past, "the outline spans {bounds:?}"); +} /// Independently integrate coverage in radial/angle bins of an original notched ring. Checking /// only the outline geometry misses raster flattening that cancels its two nearby contours. diff --git a/crates/ui-egui/src/addons/packaging.rs b/crates/ui-egui/src/addons/packaging.rs index 52df74f8cf..a6aa04dfc7 100644 --- a/crates/ui-egui/src/addons/packaging.rs +++ b/crates/ui-egui/src/addons/packaging.rs @@ -355,7 +355,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let kept = read_rows(app); let rows = &kept.rows; let source = Positional { rows, label: |row| role_label(&row.0) }; + // The four roles: the list is as tall as its rows, so the Fold Angle row, Check and Fold Preview show under them. let out = List::::new(tl!("Fold line roles").to_string()) + .natural_height(true) .select(SelectMode::None) .activate(ActivateOn::Click) .enabled(selected) diff --git a/crates/ui-egui/src/addons/packaging/tests.rs b/crates/ui-egui/src/addons/packaging/tests.rs index 086ac45e1a..26d9ac729b 100644 --- a/crates/ui-egui/src/addons/packaging/tests.rs +++ b/crates/ui-egui/src/addons/packaging/tests.rs @@ -229,7 +229,6 @@ fn canceling_a_fold_angle_edit_restores_the_angle_and_enter_is_one_undo_step() { let doc = panel.app().session.active().unwrap().doc.clone(); let angle = read_rows(&mut panel.app()).angle; let undo = undo_len(&panel.app()); - // The role list fills the panel's height, so the field below it takes the focus as a screen reader gives it. panel.focus("Fold Angle"); panel.key(Key::A, Modifiers::COMMAND); panel.type_text(text); @@ -250,3 +249,22 @@ fn canceling_a_fold_angle_edit_restores_the_angle_and_enter_is_one_undo_step() { } } } + +/// At the size the panel floats at, the role list is as tall as its rows, and the Fold Angle row, +/// Check and Fold Preview under it lie inside the panel. +#[test] +fn the_fold_angle_row_check_and_fold_preview_show_under_the_roles() { + let (mut app, a, _) = app(); + app.run(SET_ROLE, json!({"role": "crease", "ids": [a]})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let mut panel = Panel::new(app, show); + let room = crate::panel_docking::floating_size(ID); + panel.room(room).frame(); + panel.frame(); + let (list, last) = (panel.rect("Fold line roles"), panel.rect("Perforation Line")); + assert!(list.bottom() <= last.bottom() + 8.0, "the list ends at its last role: {list:?} {last:?}"); + for name in ["Fold Angle", "Check", "Fold Preview"] { + let rect = panel.rect(name); + assert!(rect.top() >= list.bottom() && rect.bottom() <= room.y, "{name} at {rect:?} lies under the list {list:?}, inside {room:?}"); + } +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 2d2f5e9f4c..83998cb77c 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -140,6 +140,7 @@ impl VectorcraftApp { momentary: None, selection_box: None, selection_bounds: None, + selection_marks: None, content_bounds: Vec::new(), variable_rows: None, three_d_exportable: None, diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index dfac727639..61f572a46c 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -82,6 +82,8 @@ pub struct CanvasCache { pub selection_box: Option<((u64, u64, vectorcraft_effects::preview::Measure), Option)>, /// [`VectorcraftApp::selection_bounds`] for (document uid, revision). pub selection_bounds: Option<((u64, u64), Option)>, + /// The selection's outlines, anchors and dots the canvas drew last ([`canvas::selection::SelectionMarks`]). + pub(crate) selection_marks: Option, /// [`VectorcraftApp::content_bounds_of`] for (document uid, revision), one entry for each open document. pub content_bounds: Vec<((u64, u64), Option)>, /// Whether the 3D and Materials panel's Export 3D Object button is available (a selected diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 49878cb2d8..9a7734e494 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -39,7 +39,7 @@ pub(crate) mod panes; mod quick_pen_bar; mod raster; pub(crate) mod rulers; -mod selection; +pub(crate) mod selection; mod selection_widgets; pub(crate) mod task_bar; mod tool_adapter; diff --git a/crates/ui-egui/src/canvas/selection.rs b/crates/ui-egui/src/canvas/selection.rs index c8e0dd5212..e0ac7e7aee 100644 --- a/crates/ui-egui/src/canvas/selection.rs +++ b/crates/ui-egui/src/canvas/selection.rs @@ -631,29 +631,64 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp if let Some(h) = hovered { HoverOutline::new("Object highlight", Some(HoverShape::Path(h.path))).color(DataColor::new(h.color)).show_at(ui, rect); } - for o in outlines(app, st) { + let key = marks_key(app, st, tool, tool_points); + let marks = match app.canvas.selection_marks.take() { + Some(kept) if kept.key == key => kept, + _ => SelectionMarks::build(app, st, tool, tool_points, key), + }; + for o in &marks.outlines { let mut outline = SelectionOutline::solid("Selection", &o.paths).color(DataColor::new(o.color)).revision(o.revision); if let Some(key) = &o.key { outline = outline.key(key); } outline.show_at(ui, rect); } - let marks = anchors(app, st, tool, tool_points); - if !marks.paths.is_empty() { - let mut paths = marks.paths; + let anchors = &marks.anchors; + if !anchors.paths.is_empty() { + let mut paths = anchors.paths.clone(); // The marks only show the selection: the tools make the edits. - let _ = BezierOverlay::new("Anchors", Bind::bound(&mut paths), &marks.selection) + let _ = BezierOverlay::new("Anchors", Bind::bound(&mut paths), &anchors.selection) .tool(BezierTool::Anchors) - .handles(marks.handles) - .anchors(marks.shown) - .segment_mark(marks.segment_mark) - .path_options(&marks.options) + .handles(anchors.handles) + .anchors(anchors.shown) + .segment_mark(anchors.segment_mark) + .path_options(&anchors.options) .show_at(ui, rect); } - let dots = dots(app, st); + let dots = &marks.dots; if !(dots.centers.is_empty() && dots.origins.is_empty() && dots.key_anchor.is_none()) { - SelectionDots { common: Common::new(), dots: &dots }.label("Selection dots").show_at(ui, rect); + SelectionDots { common: Common::new(), dots }.label("Selection dots").show_at(ui, rect); } + app.canvas.selection_marks = Some(marks); +} + +/// The outlines, anchors and dots `show` draws, kept between passes while their [`marks_key`] stays: a frame with +/// nothing changed walks no selected object. +pub(crate) struct SelectionMarks { + key: u64, + outlines: Vec, + anchors: Anchors, + dots: Dots, +} + +impl SelectionMarks { + fn build(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool, key: u64) -> Self { + #[cfg(test)] + tests::MARKS_BUILT.with(|built| built.set(built.get() + 1)); + Self { key, outlines: outlines(app, st), anchors: anchors(app, st, tool, tool_points), dots: dots(app, st) } + } +} + +/// What the selection's marks are built from: the document and its selection (its uid and revision), the parts the +/// view hides, Halftone Preview, the tool whose marks show, whether that tool draws its own points, and the +/// Selection & Anchor Display preferences. +fn marks_key(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool) -> u64 { + let mut h = DefaultHasher::new(); + let hides = ViewHides::of(app); + (st.uid, st.revision, hides.templates, hides.guides, hidden(app), tool, tool_points).hash(&mut h); + let prefs = &app.session.prefs; + (prefs.anchor_size, prefs.show_handles_multiple_anchors, prefs.handle_style.as_str()).hash(&mut h); + h.finish() } #[cfg(test)] diff --git a/crates/ui-egui/src/canvas/selection/tests.rs b/crates/ui-egui/src/canvas/selection/tests.rs index a2c32f5d53..672b07094a 100644 --- a/crates/ui-egui/src/canvas/selection/tests.rs +++ b/crates/ui-egui/src/canvas/selection/tests.rs @@ -881,3 +881,40 @@ fn grouping_selected_anchors_by_path_compares_each_path_a_bounded_number_of_time assert_eq!(grouped[5].1, vec![5, 9]); assert!(compared.get() < 2 * 2001, "{} comparisons for 2,001 entries", compared.get()); } + +thread_local! { + /// How many times the canvas built the selection's marks ([`SelectionMarks::build`]). + pub(super) static MARKS_BUILT: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The marks the canvas drew last, for comparing with what the builders give now. +fn kept(app: &VectorcraftApp) -> (Vec>, usize) { + let marks = app.canvas.selection_marks.as_ref().expect("the canvas drew the selection's marks"); + let boxes = marks.outlines.iter().map(|o| o.paths.iter().map(|p| p.bounding_box()).collect()).collect(); + (boxes, all_selected(&marks.anchors.selection)) +} + +// Whole-app frames build the selection's marks once for each change: none in frames that change nothing, one after +// the selection changes and one after the tool changes, and what the canvas keeps is what the builders give. +#[test] +fn the_canvas_builds_the_selection_marks_once_per_change() { + let (mut app, curve) = scene(); + let ctx = crate::testing::ui_context(); + let frames = |app: &mut VectorcraftApp, n: usize| { + let before = MARKS_BUILT.with(std::cell::Cell::get); + for _ in 0..n { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 850.0)); + crate::testing::app_frame(app, &ctx, egui::RawInput { screen_rect: Some(screen), ..Default::default() }); + } + MARKS_BUILT.with(std::cell::Cell::get) - before + }; + frames(&mut app, 3); + assert_eq!(frames(&mut app, 10), 0, "frames that change nothing build no marks"); + app.run("select.set", json!({"ids": [curve.0]})).unwrap(); + assert_eq!(frames(&mut app, 5), 1, "a new selection builds its marks once"); + let st = app.session.active().unwrap(); + let boxes = outlines(&app, st).iter().map(|o| o.paths.iter().map(|p| p.bounding_box()).collect()).collect::>(); + assert_eq!(kept(&app), (boxes, all_selected(&marks(&app).selection))); + app.select_tool("directSelection"); + assert_eq!(frames(&mut app, 5), 1, "another tool builds the marks once"); +} diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 6a922f0c41..51834cb232 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -14,6 +14,7 @@ use craft::ui::pickers::{Select, SelectLook}; use craft::ui::runtime::env::Env; use craft::ui::style::TypeRole; use craft::ui::text::ZoomField; +use vectorcraft_engine::WindowView; /// Shows the status bar: zoom, rotation, artboard navigator, the info field with its Show menu, the readouts, Stop, /// the background-work progress and last the message, so a narrow bar elides the message before anything else. @@ -47,6 +48,7 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let render = crate::i18n::tr_ctx(lang, "diagnostics", "render"); let ui_name = crate::i18n::tr_ctx(lang, "diagnostics", "ui"); let busy = busy_labels(app); + let shown_zoom = view.map(|v| crate::state::zoom_display_percent(v.zoom, print)); let (mut show_pick, mut stop) = (None, false); let mut snapping = None; @@ -95,6 +97,7 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { document, scaling, print, + shown_zoom, has_view: view.is_some(), turned, degrees, @@ -140,11 +143,12 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { crate::menus::invoke(app, id, params); } // The last choice of each kind counts, as the controls report one choice of each in a pass. - let (mut zoom_to, mut invalid_zoom, mut rotate_to, mut go) = (None, None, None, None); + let (mut zoom_to, mut invalid_zoom, mut preset_pick, mut rotate_to, mut go) = (None, None, None, None, None); for pick in picks { match pick { NavigationPick::Zoom(zoom) => zoom_to = Some(zoom), NavigationPick::InvalidZoom(message) => invalid_zoom = Some(message), + NavigationPick::Preset(preset) => preset_pick = Some(preset), NavigationPick::Rotate(i) => rotate_to = Some(i), NavigationPick::Artboard(to) => go = Some(to), } @@ -153,6 +157,18 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { if let Some(zoom) = zoom_to { app.run("view.setZoom", json!({"zoom": zoom})).ok(); } + match preset_pick { + Some(ZoomPreset::Percent(zoom)) => { + app.run("view.setZoom", json!({ "zoom": zoom })).ok(); + } + Some(ZoomPreset::FitOnScreen) => { + app.run("view.fitArtboard", json!({})).ok(); + } + Some(ZoomPreset::FitAll) => { + app.run("view.fitAll", json!({})).ok(); + } + None => {} + } if let Some(&(_, angle)) = rotate_to.and_then(|i| ROTATE_VIEW_ANGLES.get(i)) { app.run("view.rotate", json!({"angle": angle})).ok(); } @@ -184,6 +200,8 @@ struct Navigation<'a> { scaling: f32, /// The density zoom percentages count from ([`VectorcraftApp::print_ppi`]). print: Option, + /// The view's zoom percentage, which the Zoom Presets menu checks. + shown_zoom: Option, /// Whether the active document has a view to turn. has_view: bool, /// The Rotate View preset the view is turned to, else `usize::MAX`. @@ -208,6 +226,8 @@ enum NavigationPick { Zoom(f64), /// The message of a zoom the Zoom field could not read. InvalidZoom(String), + /// The entry chosen in the Zoom Presets menu. + Preset(ZoomPreset), /// The Rotate View preset chosen (an index into [`ROTATE_VIEW_ANGLES`]). Rotate(usize), /// The `index` of `view.goToArtboard`: an artboard's index, or first, previous, next or last. @@ -232,6 +252,11 @@ fn show_navigation(p: &mut Navigation<'_>, ui: &mut Ui) { p.picked.send(NavigationPick::InvalidZoom(invalid.message(&Env::of(ui)))); } } + let presets = zoom_presets(p.shown_zoom, p.print); + let open_presets = IconButton::new(IconId::new("chevron_down")).label(tl!("Zoom Presets")).enabled(p.has_view).show(ui); + if let Some(preset) = Menu::new(tl!("Zoom Presets")).values().opened_by(open_presets.response(), Trigger::Press).pick(ui, &presets).picked { + p.picked.send(NavigationPick::Preset(preset)); + } let angles: Vec> = ROTATE_VIEW_ANGLES.iter().enumerate().map(|(i, (label, _))| Entry::new(i, *label)).collect(); let (turned, angle, has_view) = (p.turned, format!("{}°", p.degrees), p.has_view); let mut rotate_to = None; @@ -287,6 +312,7 @@ fn show_navigation(p: &mut Navigation<'_>, ui: &mut Ui) { mod tests { use super::*; use crate::tests::panel_harness::Panel; + use craft::ui::canvas::ViewCommands; use craft::ui::contract::Role; #[test] @@ -397,6 +423,83 @@ mod tests { assert!(panel.enabled("Next Artboard") || panel.enabled("Previous Artboard"), "the navigator counts the new artboard"); } + #[test] + fn the_zoom_presets_menu_sets_a_stop_and_fits_the_view() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.view_mut().unwrap().rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0)); + app.run("view.setZoom", json!({"zoom": 800})).unwrap(); + app.view_mut().unwrap().request = None; + // The canvas applies a fit on its next frame; the status bar alone leaves the request queued. + let requested = |panel: &Panel| panel.app().view().and_then(|v| v.request.map(|(r, _)| r.command())); + let document = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, status_bar); + // Room for the whole menu, so the entries at its foot are on screen. + panel.room(egui::vec2(1200.0, 1600.0)); + + panel.click_role("Zoom Presets", Role::BUTTON); + panel.click_role("200%", Role::MENU_ITEM_RADIO); + let print = panel.app().print_ppi(); + assert!((crate::state::zoom_display_percent(panel.app().view().unwrap().zoom, print) - 200.0).abs() < 1e-6, "a stop sets its zoom"); + + panel.click_role("Zoom Presets", Role::BUTTON); + panel.click_role("Fit on Screen", Role::MENU_ITEM_RADIO); + assert_eq!(requested(&panel), Some(ViewCommands::FitArtboard), "Fit on Screen runs view.fitArtboard"); + panel.app().view_mut().unwrap().request = None; + + panel.click_role("Zoom Presets", Role::BUTTON); + panel.click_role("Fit All", Role::MENU_ITEM_RADIO); + assert_eq!(requested(&panel), Some(ViewCommands::FitOnScreen), "Fit All runs view.fitAll"); + + let app = panel.app(); + assert_eq!(app.session.active().unwrap().doc, document); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "zooming records no undo step"); + } + + #[test] + fn the_zoom_presets_list_the_stops_from_the_highest_and_check_the_shown_zoom() { + let presets = zoom_presets(Some(200.0), None); + let labels: Vec = presets.iter().filter(|e| e.is_item()).map(|e| e.label().as_str().to_owned()).collect(); + assert_eq!(labels.first().map(String::as_str), Some("64000%")); + assert_eq!(labels.iter().rev().take(3).rev().map(String::as_str).collect::>(), ["3.13%", "Fit on Screen", "Fit All"]); + let checked: Vec<_> = presets.iter().filter(|e| e.is_checked()).filter_map(|e| e.value().copied()).collect(); + assert_eq!(checked, [ZoomPreset::Percent(200.0)]); + assert!(zoom_presets(None, None).iter().all(|e| !e.is_checked()), "without a view no stop is checked"); + } + + /// With Display Print Size on, 100% is more or less than one screen point per document point, so the stops at + /// the ends of the list can fall outside the view's zoom range; the menu lists only the stops a pick sets exactly. + #[test] + fn the_zoom_presets_leave_out_stops_outside_the_zoom_range_at_print_size() { + let percents = |print: Option| -> Vec { + zoom_presets(None, print) + .iter() + .filter_map(|e| match e.value() { + Some(ZoomPreset::Percent(pct)) => Some(*pct), + _ => None, + }) + .collect() + }; + let stops: Vec = crate::state::zoom_stop_percents().collect(); + let n = stops.len(); + assert_eq!(percents(None).len(), n, "at 1:1 every stop is in range"); + let dense = crate::state::print_ppi(true, Some(96.0)); + assert_eq!(percents(dense).first(), Some(&stops[n - 2]), "64000% at 96 PPI is past the highest zoom, 25600% is not"); + assert_eq!(percents(dense).last(), Some(&stops[0]), "3.13% at 96 PPI is in range"); + let sparse = crate::state::print_ppi(true, Some(40.0)); + assert_eq!(percents(sparse).first(), Some(&stops[n - 1]), "64000% at 40 PPI is in range"); + assert_eq!(percents(sparse).last(), Some(&stops[2]), "3.13% and 4.17% at 40 PPI are below the lowest zoom, 6.25% is not"); + let (min, max) = WindowView::ZOOM_RANGE; + for print in [None, dense, sparse] { + for pct in percents(print) { + let zoom = crate::state::zoom_from_display_percent(pct, print); + let set = crate::state::zoom_display_percent(zoom.clamp(min, max), print); + assert!((set - pct).abs() < 1e-6, "{pct}% at {print:?} sets {set}%"); + } + } + } + #[test] fn with_no_document_the_artboard_navigator_shows_a_dash() { let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); @@ -420,6 +523,41 @@ fn busy_labels(app: &VectorcraftApp) -> Vec<&str> { .collect() } +/// An entry of the Zoom Presets menu beside the status bar's zoom field. +#[derive(Clone, Copy, Debug, PartialEq)] +enum ZoomPreset { + /// A zoom stop, in the percent `view.setZoom` takes. + Percent(f64), + /// Fit on Screen (`view.fitArtboard`). + FitOnScreen, + /// Fit All (`view.fitAll`). + FitAll, +} + +/// The Zoom Presets menu: the zoom stops from the highest, the one at the `shown` percent checked, then Fit on Screen +/// and Fit All. A stop whose zoom falls outside the view's zoom range ([`WindowView::ZOOM_RANGE`]) at the `print` +/// setting is left out, since `view.setZoom` would set the nearest end of the range instead. +fn zoom_presets(shown: Option, print: Option) -> Vec> { + let (min, max) = WindowView::ZOOM_RANGE; + let reachable = |pct: &f64| { + let zoom = crate::state::zoom_from_display_percent(*pct, print); + zoom >= min * (1.0 - 1e-9) && zoom <= max * (1.0 + 1e-9) + }; + let stops = crate::state::zoom_stop_percents(); + let mut entries: Vec> = stops + .rev() + .filter(reachable) + .map(|pct| { + let label = crate::state::zoom_label(crate::state::zoom_from_display_percent(pct, print), print); + Entry::new(ZoomPreset::Percent(pct), label).checked(shown.is_some_and(|s| (s - pct).abs() < 0.01)) + }) + .collect(); + entries.push(Entry::separator()); + entries.push(Entry::new(ZoomPreset::FitOnScreen, tl!("Fit on Screen"))); + entries.push(Entry::new(ZoomPreset::FitAll, tl!("Fit All"))); + entries +} + /// What the status bar's info field shows, chosen from the Show menu that a click on the field /// opens (`view.statusBarShow`). Kept with the UI state ([`crate::UiState::status_bar_show`]). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)] diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 42e7d7e5ff..92f19cb4a8 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -44,8 +44,8 @@ struct Open { preview: LivePreview, /// Set Role Swatch: the role the Swatch row was last filled for. filled_for: Option, - /// The uid of the document whose objects the dialog opened on (`__doc`), for Set Fold Angle, and its revert count - /// then. + /// The uid of the document whose objects the dialog edits, when its caller supplies `__doc`, and its revert count + /// when the dialog opened. doc: Option<(u64, u64)>, /// The document checked for File > Revert, with its revert count when the dialog opened: `doc`, or the active /// document for a dialog that previews. @@ -75,8 +75,13 @@ impl Setting { /// fixed ones, `__rowGutterLinked` for Area Type Options' linked Row Gutter and `__doc` for the uid of the document /// whose objects the dialog edits). pub(crate) fn open(app: &mut VectorcraftApp, command: &str, label: &str, mut params: Map) -> Result { + let doc = match params.remove("__doc") { + None => None, + Some(value) => Some(value.as_u64().ok_or("`__doc` must be a document id")?), + }; let ctx = app.ui_ctx.clone().ok_or("no window")?; if let Some(old) = app.command_dialog.open.take() + && on_document(app, &old) && !reverted(app, &old) { old.preview.cancel(app); @@ -86,7 +91,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, command: &str, label: &str, mut par _ => Map::new(), }; let linked = params.remove("__rowGutterLinked").and_then(|v| v.as_f64()); - let doc = params.remove("__doc").and_then(|v| v.as_u64()).map(|uid| { + let doc = doc.map(|uid| { let reverts = app.session.documents().iter().find(|st| st.uid == uid).map_or(0, |st| st.reverts); (uid, reverts) }); @@ -139,6 +144,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { } fn step(app: &mut VectorcraftApp, open: &mut Open) { + if !on_document(app, open) { + return; + } let Some(dialogs) = app.dialogs() else { return }; let id = open.id; let seen = dialogs.with(|h| h.get_by_id::(id).map(|d| (d.fields().clone(), d.is_previewing()))); @@ -189,8 +197,7 @@ fn confirm(app: &mut VectorcraftApp, token: &Arc<()>, fields: &DialogFields) -> app.command_dialog.open = Some(open); return Err(tl!("The document was reverted. Reopen this dialog to continue.").into()); } - if open.doc.is_some_and(|(uid, _)| app.session.active().is_none_or(|st| st.uid != uid)) { - open.preview.cancel(app); + if !on_document(app, &open) { return Ok(Value::Null); } let params = command_params(&open.command, &open.opening, Setting::of(app)); @@ -214,12 +221,17 @@ fn confirm(app: &mut VectorcraftApp, token: &Arc<()>, fields: &DialogFields) -> /// Cancel: rolls back the preview of the dialog `token` names. fn cancel(app: &mut VectorcraftApp, token: &Arc<()>) { if let Some(open) = app.command_dialog.open.take_if(|o| Arc::ptr_eq(&o.token, token)) + && on_document(app, &open) && !reverted(app, &open) { open.preview.cancel(app); } } +fn on_document(app: &VectorcraftApp, open: &Open) -> bool { + open.doc.is_none_or(|(uid, _)| app.session.active().is_some_and(|st| st.uid == uid)) +} + /// Whether the active document is the one the dialog opened on (`__doc`, or the active one for a dialog that /// previews), with its content replaced by File > Revert since: a preview shown before belonged to the content /// thrown away. @@ -907,6 +919,41 @@ mod tests { /// The choices this dialog lists for Rasterize, Create Gradient Mesh and Repeat Options are the /// values their commands take (#8020, #7991): each one runs, and every language with complete + #[test] + fn document_scoped_dialog_confirms_only_in_its_opening_document() { + for (scoped, switch) in [(true, false), (true, true), (false, true)] { + let mut app = windowed(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let mut params = json!({"x": 10, "y": 10, "width": 20, "height": 20}).as_object().unwrap().clone(); + if scoped { + params.insert("__doc".into(), json!(app.session.active().unwrap().uid)); + } + open(&mut app, "shape.rectangle", "Rectangle", params).unwrap(); + pump(&mut app); + if switch { + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + } + answer_ok(&mut app); + assert!(app.command_dialog.open.is_none()); + assert_eq!(app.session.active().unwrap().selection.is_empty(), scoped && switch); + if switch { + assert!(app.session.set_active(0)); + assert!(app.session.active().unwrap().selection.is_empty()); + } + } + } + + #[test] + fn document_scoped_dialog_rejects_an_invalid_document_id() { + for doc in [json!(null), json!("1"), json!(-1), json!(1.5)] { + let mut app = windowed(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let params = json!({"width": 20, "height": 20, "__doc": doc}).as_object().unwrap().clone(); + assert!(open(&mut app, "shape.rectangle", "Rectangle", params).is_err(), "{doc}"); + assert!(app.command_dialog.open.is_none()); + } + } + /// menus has a row for each label. #[test] fn choice_fields_list_the_values_their_commands_take() { diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index f3d056a219..8e770d3da7 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -26,6 +26,7 @@ use craft::ui::choice::{Checkbox, Segmented}; use craft::ui::contract::{Bind, Entry, FieldLayout, Gap, Props as _, Show as _, ShowContainer as _, SideLabel, Sizing, clicked}; use craft::ui::display::{Shade, Text}; use craft::ui::form::Field; +use craft::ui::layout::CellAlign; use craft::ui::layout_components::{Grid, Row, Stack}; use craft::ui::patterns::form_dialogs::{ CardCx, CardSource, DetailsCx, DocumentCard, DocumentSettings, HostedNewDocument, NewDocumentDialog, Orientation, PresetCategory, @@ -299,10 +300,8 @@ impl DocumentSettings for VcNewDocument { } }); }); - // Three shares: the grid stacks the three fields when the column has no room for them side by side, so - // Artboards is never cut off at its right edge. - Grid::new(&THIRDS).fill().show(ui, |ui, _| { - Field::new(height.clone()).layout(FieldLayout::Above).id_salt("height").show(ui, |ui, _| size_field(ui, &height, &mut s.height, lengths)); + let compact = compact_details(ui); + let mut orientation_field = |ui: &mut egui::Ui| { Field::new(orientation.clone()).layout(FieldLayout::Above).id_salt("orientation").show(ui, |ui, _| { let entries = [ Entry::new(Orientation::Portrait, portrait.clone()).icon(IconId::new("orientation_portrait")), @@ -310,6 +309,15 @@ impl DocumentSettings for VcNewDocument { ]; picked = Segmented::new(orientation.clone(), Bind::given(current), &entries).show(ui).events.committed().cloned(); }); + }; + // A wide column holds Height, Orientation and Artboards in one row. A narrow one holds Height and Artboards in + // two equal shares and Orientation under them, so its two buttons stay side by side. + let columns: &'static [ColumnWidth] = if compact { &HALVES } else { &THIRDS }; + Grid::new(columns).fill().cells(CellAlign::Top).show(ui, |ui, _| { + Field::new(height.clone()).layout(FieldLayout::Above).id_salt("height").show(ui, |ui, _| size_field(ui, &height, &mut s.height, lengths)); + if !compact { + orientation_field(ui); + } Field::new(artboards.clone()).layout(FieldLayout::Above).id_salt("artboards").show(ui, |ui, _| { let field = NumberField::new(artboards.clone(), Bind::given(Some(f64::from(s.artboards)))) .range(1.0..=f64::from(MAX_ARTBOARDS)) @@ -321,6 +329,9 @@ impl DocumentSettings for VcNewDocument { } }); }); + if compact { + orientation_field(ui); + } if let Some(o) = picked && o != current { @@ -329,7 +340,7 @@ impl DocumentSettings for VcNewDocument { } let bleed = text(tl!("Bleed")); - Field::new(bleed.clone()).layout(FieldLayout::Above).id_salt("bleed").show(ui, |ui, _| bleed_row(ui, s, &mut memory, lengths)); + Field::new(bleed.clone()).layout(FieldLayout::Above).id_salt("bleed").show(ui, |ui, _| bleed_row(ui, s, &mut memory, lengths, compact)); Field::new(background.clone()).layout(FieldLayout::Above).id_salt("background").show(ui, |ui, _| { let entries: Vec> = BACKGROUNDS.iter().map(|(b, name)| Entry::new(*b, text(tl!(name)))).collect(); @@ -419,36 +430,55 @@ fn pixels_per_inch() -> f64 { 72.0 / Unit::Pixels.to_pt(1.0) } -/// The four Bleed fields in one row, each under its side's name, and the link button at the end; linked, an edit to -/// one side sets all four, and turning the link on sets all four to Top's. Each field is as wide as the widest bleed it -/// takes, and the row wraps when the column has no room for all of them. -fn bleed_row(ui: &mut egui::Ui, s: &mut DocSettings, memory: &mut Memory, lengths: LengthUnits) { +/// The four Bleed fields, each under its side's name, and the link button at the end; linked, an edit to one side sets +/// all four, and turning the link on sets all four to Top's. Each field is as wide as the widest bleed it takes. A wide +/// column holds them in one row. A narrow (`compact`) column holds them in two rows, Top and Bottom above Left and +/// Right, with the link button after Right. +fn bleed_row(ui: &mut egui::Ui, s: &mut DocSettings, memory: &mut Memory, lengths: LengthUnits, compact: bool) { let mut linked = !memory.bleed_split; let link = LinkMode::Equal.label(&Env::of(ui).words::()); let sides = [text(tl!("Top")), text(tl!("Bottom")), text(tl!("Left")), text(tl!("Right"))]; let mut edited = None; - Row::new().wrap(true).show(ui, |ui, _| { - for (i, side) in sides.iter().enumerate() { - // A drag on the side's name scrubs its field. - let field = Field::new(side.clone()).layout(FieldLayout::Above).side(SideLabel::new().scrub(true)).sizing(Sizing::Content); - field.id_salt(("bleed", i)).show(ui, |ui, _| { - let field = NumberField::length(side.clone(), Bind::given(Some(s.bleed[i])), lengths) - .range(0.0..=vectorcraft_doc::setup::MAX_BLEED) - .scrub_by_label() - .sizing(Sizing::Content); - if let Some(v) = field.show(ui).edit.events.committed().copied().flatten().filter(|v| v.is_finite()) { - edited = Some((i, v.clamp(0.0, vectorcraft_doc::setup::MAX_BLEED))); - } - }); - } - // Turning the link on sets every side to Top's bleed. - if let Some(on) = link_toggle(link.clone(), Bind::given(linked)).id_salt("bleed-link").show(ui).value().copied() { - linked = on; - if on { - s.bleed = [s.bleed[0]; 4]; + let mut side_field = |ui: &mut egui::Ui, i: usize| { + // A drag on the side's name scrubs its field. + let field = Field::new(sides[i].clone()).layout(FieldLayout::Above).side(SideLabel::new().scrub(true)).sizing(Sizing::Content); + field.id_salt(("bleed", i)).show(ui, |ui, _| { + let field = NumberField::length(sides[i].clone(), Bind::given(Some(s.bleed[i])), lengths) + .range(0.0..=vectorcraft_doc::setup::MAX_BLEED) + .scrub_by_label() + .sizing(Sizing::Content); + if let Some(v) = field.show(ui).edit.events.committed().copied().flatten().filter(|v| v.is_finite()) { + edited = Some((i, v.clamp(0.0, vectorcraft_doc::setup::MAX_BLEED))); } + }); + }; + let mut turned_on = None; + // Turning the link on sets every side to Top's bleed. + let mut link_button = |ui: &mut egui::Ui| { + if let Some(on) = link_toggle(link.clone(), Bind::given(linked)).id_salt("bleed-link").show(ui).value().copied() { + turned_on = Some(on); } - }); + }; + if compact { + Stack::new().show(ui, |ui, _| { + Row::new().show(ui, |ui, _| (0..2).for_each(|i| side_field(ui, i))); + Row::new().show(ui, |ui, _| { + (2..4).for_each(|i| side_field(ui, i)); + link_button(ui); + }); + }); + } else { + Row::new().wrap(true).show(ui, |ui, _| { + (0..sides.len()).for_each(|i| side_field(ui, i)); + link_button(ui); + }); + } + if let Some(on) = turned_on { + linked = on; + if on { + s.bleed = [s.bleed[0]; 4]; + } + } if let Some((i, v)) = edited { if linked { s.bleed = follow_equal(s.bleed, i, v); @@ -459,10 +489,21 @@ fn bleed_row(ui: &mut egui::Ui, s: &mut DocSettings, memory: &mut Memory, length memory.bleed_split = !linked; } -/// The Height, Orientation and Artboards row. Orientation's share keeps its two buttons side by side in a 900-point -/// window. +/// The Height, Orientation and Artboards row of a wide details column. const THIRDS: [ColumnWidth; 3] = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.4), ColumnWidth::fill(1.0)]; +/// The Height and Artboards row of a narrow details column. +const HALVES: [ColumnWidth; 2] = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0)]; + +/// The least width of a wide details column, in control heights: the four Bleed fields and the link button in one row, +/// and Orientation's two buttons side by side between Height and Artboards. +const WIDE_DETAILS: f32 = 11.0; + +/// Whether the details column is narrower than [`WIDE_DETAILS`] control heights. +fn compact_details(ui: &egui::Ui) -> bool { + ui.available_width() < WIDE_DETAILS * Env::of(ui).tokens.size.control.md +} + /// A side of the page in points, shown in the chosen units. fn size_field(ui: &mut egui::Ui, name: &Label, points: &mut f64, lengths: LengthUnits) { let field = NumberField::length(name.clone(), Bind::given(Some(*points)), lengths).range(MIN_SIDE..=MAX_SIDE).sizing(Sizing::FillWidth); @@ -1514,4 +1555,30 @@ mod tests { assert!(portrait.y0 == landscape.y0 && portrait.x1 <= landscape.x0, "{width}x{height}: Portrait and Landscape side by side"); } } + + /// In small windows Height and Artboards share a row, Orientation's two buttons stand side by side under them, and + /// the Bleed fields form two rows of two, Top and Bottom above Left and Right, with the link button after Right; + /// before, at 800 by 600 Orientation's buttons stood one above the other between Height and Artboards. + #[test] + fn new_document_details_stay_in_rows_in_small_windows() { + use egui::accesskit::Role; + for (width, height) in [(800.0, 600.0), (640.0, 500.0), (900.0, 700.0)] { + let nodes = dialog_nodes(width, height); + let at = format!("{width}x{height}"); + let dialog = nodes.iter().find(|(r, _, _)| *r == Role::Dialog).map(|(_, _, b)| *b).expect("the dialog"); + let (portrait, landscape) = (node(&nodes, "Portrait", Role::RadioButton), node(&nodes, "Landscape", Role::RadioButton)); + assert!(portrait.y0 == landscape.y0 && portrait.x1 <= landscape.x0, "{at}: Portrait {portrait:?} beside Landscape {landscape:?}"); + let (h, a) = (node(&nodes, "Height", Role::SpinButton), node(&nodes, "Artboards", Role::SpinButton)); + assert!(h.y0 == a.y0 && h.x1 <= a.x0, "{at}: Height {h:?} and Artboards {a:?} share a row"); + assert!(a.y1 <= portrait.y0 || landscape.x1 <= a.x0, "{at}: Orientation {landscape:?} stays clear of Artboards {a:?}"); + let [top, bottom, left, right] = ["Top", "Bottom", "Left", "Right"].map(|side| node(&nodes, side, Role::SpinButton)); + assert!(top.y0 == bottom.y0 && left.y0 == right.y0 && top.y1 <= left.y0, "{at}: two Bleed rows: {top:?} {bottom:?} {left:?} {right:?}"); + assert!( + top.x0 == left.x0 && bottom.x0 == right.x0 && top.x1 <= bottom.x0, + "{at}: two Bleed columns: {top:?} {bottom:?} {left:?} {right:?}" + ); + let link = node(&nodes, "Make all settings the same", Role::Button); + assert!(right.x1 <= link.x0 && link.x1 <= dialog.x1, "{at}: the link button {link:?} follows Right {right:?} inside {dialog:?}"); + } + } } diff --git a/crates/ui-egui/src/dialogs/object_mosaic.rs b/crates/ui-egui/src/dialogs/object_mosaic.rs index 49f355273a..9bb66b6696 100644 --- a/crates/ui-egui/src/dialogs/object_mosaic.rs +++ b/crates/ui-egui/src/dialogs/object_mosaic.rs @@ -94,6 +94,15 @@ pub struct Mosaic { delete_raster: bool, } +/// The warnings the dialog gave for being away from its image, one for each place it shows one. +#[derive(Default)] +struct Away { + /// OK's held refusal. + held: Option