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/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/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 3b2ffa8623..5a4bb380c0 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, @@ -90,6 +92,7 @@ use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView}; mod tags; +mod text; mod variables; pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE}; @@ -165,6 +168,7 @@ pub(super) struct State { items: RefCell>, locked: RefCell>, saving: Cell, + text: text::TextState, presets: RefCell>>, preset_bytes: Cell, preset_limit: u64, @@ -303,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 or page item `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(); @@ -315,9 +319,12 @@ fn later(link: &Link, class: &'static str, name: &'static str) -> Described { "Document" => { doc_of(&h, arg(&a, 0), "Document")?; } - "PageItem" => { + "PageItem" | "TextFrame" => { item_of(&h, arg(&a, 0))?; } + "TextRange" => { + text::check_range(&h, arg(&a, 0))?; + } _ => {} } Err(HostError::Error(message.clone())) @@ -2031,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)))) @@ -2546,10 +2603,13 @@ const ENUMS: &[(&str, &[&str])] = &[ /// Adds `app`, its classes and the enumerations to `realm`; their members act for the run `link` /// holds. pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> { + text::install_enums(realm)?; for (name, members) in ENUMS { 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; @@ -2576,6 +2636,7 @@ fn classes(link: &Link) -> Vec { ("executeMenuCommand", method(l, app_menu_command), returns("undefined", &[("menuCommandString", "string")])), ("toString", class_text("Application"), returns("string", &[])), ]); + application.push(("textFonts".into(), text::app_text_fonts(l), MemberInfo { collection: true, ..typed("TextFonts") })); application.push(later(l, "Application", "beep")); let preset = { let l = link.clone(); @@ -2644,12 +2705,13 @@ fn classes(link: &Link) -> Vec { returns("Array", &[("point", "Array"), ("source", "CoordinateSystem"), ("destination", "CoordinateSystem")]), ), ("pageItems", get(l, doc_page_items), MemberInfo { collection: true, ..typed("PageItems") }), + ("textFrames", text::doc_text_frames(l), MemberInfo { collection: true, ..typed("TextFrames") }), ("selection", property(l, doc_selection, doc_set_selection), typed("*")), ("views", get(l, doc_views), MemberInfo { collection: true, ..typed("Views") }), ("toString", method(l, doc_to_string), returns("string", &[])), ]); document.extend( - ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "activeLayer", "saveAs", "close"] + ["layers", "artboards", "pathItems", "groupItems", "swatches", "symbols", "activeLayer", "saveAs", "close"] .into_iter() .map(|m| later(l, "Document", m)), ); @@ -2706,6 +2768,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")), @@ -2731,7 +2794,6 @@ fn classes(link: &Link) -> Vec { page_item.extend( [ "artworkKnockout", - "blendingMode", "isIsolated", "layer", "pixelAligned", @@ -2752,7 +2814,8 @@ fn classes(link: &Link) -> Vec { ); page_item.extend(variables::page_item_members(l)); classes.push(class("PageItem", None, page_item, None)); - classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), variables::item_members(l, c), None))); + classes.extend(ITEM_CLASSES.iter().filter(|c| **c != "TextFrame").map(|c| class(c, Some("PageItem"), variables::item_members(l, c), None))); + classes.extend(text::classes(l)); classes.extend(variables::classes(l)); classes.push(class( "Layer", diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs new file mode 100644 index 0000000000..7452051580 --- /dev/null +++ b/crates/engine/src/script/dom/text.rs @@ -0,0 +1,1787 @@ +//! Type in the script object model: `document.textFrames`, each `TextFrame`, the `TextRange` of its +//! text with the `characters`, `words` and `paragraphs` in it, their `characterAttributes` and +//! `paragraphAttributes`, and `app.textFonts`, as the help pages +//! , +//! , +//! and +//! describe them. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - Offsets and lengths count UTF-16 code units, as a JavaScript string does, so +//! `frame.contents.length` is `frame.textRange.length`. An offset inside a surrogate pair moves +//! out to the whole character. One item of `characters` is one code point. +//! - `contents` gives each paragraph break as `\r` and each forced line break as `\u0003`; written +//! text may use `\r`, `\n` or `\r\n` for a paragraph break. +//! - A word is a run of characters that are not white space. A paragraph ends after its break, and +//! a range's `words` and `paragraphs` are the whole words and paragraphs it touches. +//! - A range keeps its place while the script edits the frame through the object model: an edit +//! before it moves it, an edit over one of its ends takes that end to the edge of the edit's new +//! text, so a range the edit covers holds the new text, and an insertion at one of its ends joins +//! it. When a member finds the frame's text different from the text the model last saw, because +//! `vc.run` or an undo changed it, every range made before is stale and throws +//! `Stale text range`; a change reversed before that read leaves the ranges as they were. After +//! File › Revert every range made before is stale, even when the file read back holds the same +//! text. +//! - The model keeps the frame's last [`MAX_EDITS`] edits; a range made before an edit that is no +//! longer kept is stale. +//! - Setting a range's `length` moves its end and leaves the text as it is; each read of a member +//! that gives a range gives a new object. +//! - `add` on `characters`, `words` or `paragraphs` inserts after the collection's last item, and +//! `addBefore` before its first. An added word is kept apart from the characters next to it by a +//! space, and an added paragraph by a paragraph break. +//! - A character attribute read on a range whose characters differ gives the first character's +//! value; set on an empty range it changes nothing. A paragraph attribute reads the first +//! paragraph the range touches and sets every one of them. A text range has the members of +//! both its `characterAttributes` and its `paragraphAttributes`. + +use std::cell::{Cell, RefCell}; +use std::collections::{HashMap, VecDeque}; +use std::rc::Rc; +use std::sync::{Arc, Weak}; + +use serde_json::{Value, json}; +use vectorcraft_doc::{CharStyle, Justify, TextKind, TextObject}; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref}; + +use super::{ + Answer, Described, Doc, Host, Item, Link, NOT_FOUND, STALE_ITEM, all_editable, arg, boolean, class, command, doc_of, doc_ref, edit_item, + editable, float, frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc, page_items, point, property, + returns, text, typed, typename_of, whole, with_doc, +}; +use crate::{DocState, Document, NodeId, NodeKind}; + +/// The error of a text range, or of a collection of one, whose frame's text changed other than +/// through the object model. +pub const STALE_RANGE: &str = "Stale text range"; +/// The most edits a frame keeps for moving its ranges; a range made before the oldest kept edit +/// is stale. +const MAX_EDITS: usize = 100_000; + +/// A frame's text with the offsets of its characters, words and paragraphs, in UTF-16 units. +pub(super) struct Index { + text: String, + /// The UTF-16 offset of each character's start, and the text's length last. + chars: Vec, + /// The byte offset of each character's start, and the text's length in bytes last. + bytes: Vec, + words: Vec<(usize, usize)>, + paras: Vec<(usize, usize)>, +} + +impl Index { + fn new(text: String) -> Self { + let mut chars = Vec::with_capacity(text.len() + 1); + let mut bytes = Vec::with_capacity(text.len() + 1); + let (mut words, mut paras) = (Vec::new(), Vec::new()); + let (mut u, mut word, mut para) = (0, None, 0); + for (b, c) in text.char_indices() { + chars.push(u); + bytes.push(b); + if c.is_whitespace() { + if let Some(w) = word.take() { + words.push((w, u)); + } + } else if word.is_none() { + word = Some(u); + } + u += c.len_utf16(); + if c == '\n' { + paras.push((para, u)); + para = u; + } + } + if let Some(w) = word { + words.push((w, u)); + } + paras.push((para, u)); + chars.push(u); + bytes.push(text.len()); + Self { text, chars, bytes, words, paras } + } + + fn len(&self) -> usize { + self.chars.last().copied().unwrap_or(0) + } + + /// The byte offset of UTF-16 offset `u`; inside a surrogate pair, the start of its character, + /// or with `up` the end of it. + fn byte(&self, u: usize, up: bool) -> usize { + let i = self.chars.partition_point(|&c| c < u); + match self.chars.get(i) { + Some(&c) if c == u || up => self.bytes.get(i).copied().unwrap_or(self.text.len()), + _ => i.checked_sub(1).and_then(|i| self.bytes.get(i)).copied().unwrap_or(0), + } + } + + /// The characters whose start is in `s..e`, each as a UTF-16 span. + fn chars_in(&self, s: usize, e: usize) -> std::ops::Range { + let count = self.chars.len().saturating_sub(1); + let a = self.chars[..count].partition_point(|&c| c < s); + let b = self.chars[..count].partition_point(|&c| c < e); + a..b.max(a) + } + + fn char_span(&self, i: usize) -> Option<(usize, usize)> { + Some((*self.chars.get(i)?, *self.chars.get(i + 1)?)) + } +} + +/// The words or paragraphs of `spans` that `s..e` touches: those it overlaps, or, for an empty +/// range, the one with a character at it, or the last one when it ends there. Only an empty range +/// touches the empty paragraph after a break at the end of the text. +fn touched(spans: &[(usize, usize)], s: usize, e: usize) -> std::ops::Range { + if s == e { + let i = spans.partition_point(|&(_, y)| y <= s); + if spans.get(i).is_some_and(|&(x, _)| x <= s) { + return i..i + 1; + } + return match spans.last() { + Some(&(_, y)) if i == spans.len() && y == s => i - 1..i, + _ => i..i, + }; + } + let a = spans.partition_point(|&(_, y)| y <= s); + let b = spans.partition_point(|&(x, _)| x < e); + a..b.max(a) +} + +#[derive(Clone, Copy)] +struct Edit { + stamp: u64, + at: usize, + removed: usize, + inserted: usize, +} + +/// What the object model knows of one frame's text: the document it was read from and its revert +/// count then, the text, the edits made through the model, and the oldest range generation still +/// valid. +struct Log { + doc: Weak, + reverts: u64, + index: Rc, + stamp: u64, + floor: u64, + edits: VecDeque, +} + +impl Log { + /// Records an edit the model made: `removed` units at `at` replaced by `inserted` units. Past + /// [`MAX_EDITS`] the oldest edit is dropped, and ranges made before it go stale. + fn push(&mut self, at: usize, removed: usize, inserted: usize) { + self.stamp += 1; + self.edits.push_back(Edit { stamp: self.stamp, at, removed, inserted }); + if self.edits.len() > MAX_EDITS + && let Some(dropped) = self.edits.pop_front() + { + self.floor = dropped.stamp; + } + } +} + +/// A document's uid, the document, and the ids of its type objects then. +type FrameList = (u64, Weak, Rc>); + +/// Word or paragraph spans, in UTF-16 units. +type Spans = [(usize, usize)]; + +/// The text state of one run. +#[derive(Default)] +pub(in crate::script) struct TextState { + frames: RefCell>, + /// 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. + fonts: RefCell>>, + /// The number of text range objects made, which numbers the next one. + made: Cell, + /// The span of each range object, by its number, whose `length` the script set. + resized: RefCell>, +} + +fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> { + match &st.doc.node(id)?.kind { + NodeKind::Text(t) => Some(t), + _ => None, + } +} + +fn same_text(t: &TextObject, s: &str) -> bool { + let mut rest = s; + for r in &t.runs { + match rest.strip_prefix(r.text.as_str()) { + Some(after) => rest = after, + None => return false, + } + } + rest.is_empty() +} + +/// The frame's index and its generation now, read again when its document changed. After File › +/// Revert every earlier range goes stale, even when the file read back holds the same text. +fn observe(h: &Host, st: &DocState, id: NodeId) -> std::result::Result<(Rc, u64), HostError> { + let t = text_of(st, id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let mut frames = h.dom.text.frames.borrow_mut(); + let key = (st.uid, id.0); + let now = Arc::as_ptr(&st.doc); + match frames.get_mut(&key) { + Some(l) if std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts => {} + Some(l) => { + if l.reverts != st.reverts || !same_text(t, &l.index.text) { + l.stamp += 1; + l.floor = l.stamp; + l.edits.clear(); + l.index = Rc::new(Index::new(t.plain_text())); + } + l.doc = Arc::downgrade(&st.doc); + l.reverts = st.reverts; + } + None => { + let l = Log { + doc: Arc::downgrade(&st.doc), + reverts: st.reverts, + index: Rc::new(Index::new(t.plain_text())), + stamp: 0, + floor: 0, + edits: VecDeque::new(), + }; + frames.insert(key, l); + } + } + let l = frames.get(&key).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok((l.index.clone(), l.stamp)) +} + +/// A text range: its frame, its span in UTF-16 units and the generation it was made at. +#[derive(Clone, Copy)] +struct Span { + item: Item, + start: usize, + end: usize, + stamp: u64, +} + +/// The span and index of `r` now. +fn resolve(h: &Host, r: Span) -> std::result::Result<(Rc, usize, usize, u64), HostError> { + with_doc(h, r.item.doc, |_, st| { + let (index, stamp) = observe(h, st, r.item.id)?; + let frames = h.dom.text.frames.borrow(); + let l = frames.get(&(st.uid, r.item.id.0)).ok_or_else(|| HostError::Error(STALE_RANGE.into()))?; + if r.stamp < l.floor || r.stamp > l.stamp { + return Err(HostError::Error(STALE_RANGE.into())); + } + let (mut s, mut e) = (r.start, r.end); + let from = l.edits.partition_point(|x| x.stamp <= r.stamp); + for x in l.edits.range(from..) { + let moved = |v: usize| v - x.removed + x.inserted; + s = if s <= x.at { + s + } else if s >= x.at + x.removed { + moved(s) + } else { + x.at + }; + // An end inside the removed text goes to the end of the new text. + e = if e < x.at || (e == x.at && x.removed > 0) { + e + } else if e >= x.at + x.removed { + moved(e) + } else { + x.at + x.inserted + }; + } + let len = index.len(); + let e = e.min(len); + Ok((index, s.min(e), e, stamp)) + }) +} + +/// Records an edit the model made to the frame: `removed` units at `at` replaced by `inserted`. +/// When the text is not what that edit gives, every earlier range goes stale. +fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inserted: &str) -> std::result::Result<(), HostError> { + with_doc(h, item.doc, |_, st| { + let t = text_of(st, item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let now = t.plain_text(); + let (a, b) = (before.byte(at, false), before.byte(at + removed, true)); + let expected = before.text.len() - (b - a) + inserted.len() == now.len() + && now.as_bytes().starts_with(&before.text.as_bytes()[..a]) + && now.as_bytes().ends_with(&before.text.as_bytes()[b..]) + && now.get(a..a + inserted.len()) == Some(inserted); + let mut frames = h.dom.text.frames.borrow_mut(); + let l = frames.get_mut(&(st.uid, item.id.0)).ok_or_else(|| HostError::Error(STALE_RANGE.into()))?; + if expected && l.reverts == st.reverts { + l.push(at, removed, inserted.encode_utf16().count()); + } else { + l.stamp += 1; + l.floor = l.stamp; + l.edits.clear(); + } + l.index = Rc::new(Index::new(now)); + l.doc = Arc::downgrade(&st.doc); + l.reverts = st.reverts; + Ok(()) + }) +} + +// ---- handles ---- + +fn usize_of(n: f64) -> Option { + whole(n).and_then(|v| usize::try_from(v).ok()) +} + +/// 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. 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(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`. +fn span_of(h: &Host, d: &Data, classes: &[&str]) -> std::result::Result { + span_and_number(h, d, classes).map(|(span, _)| span) +} + +/// The span `d` names and the number of its object, when it is an object of one of `classes`. +fn span_and_number(h: &Host, d: &Data, classes: &[&str]) -> std::result::Result<(Span, u64), HostError> { + let handle = classes.iter().find_map(|c| handle_of(d, c)); + 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")))); + }; + 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())); + }; + let (start, end, stamp) = h.dom.text.resized.borrow().get(&number).copied().unwrap_or((start, end, stamp)); + Ok((Span { item: frame, start, end, stamp }, number)) +} + +/// The text frame `this` names. +fn this_frame(h: &Host, a: &[Data]) -> std::result::Result { + if handle_of(arg(a, 0), "TextFrame").is_none() { + return Err(HostError::Type("this is not a TextFrame".into())); + } + item_of(h, arg(a, 0)) +} + +/// The whole text of the frame as a span. +fn whole_span(h: &Host, item: Item) -> std::result::Result<(Rc, Span), HostError> { + with_doc(h, item.doc, |_, st| { + let (index, stamp) = observe(h, st, item.id)?; + let len = index.len(); + Ok((index, Span { item, start: 0, end: len, stamp })) + }) +} + +fn this_range(h: &Host, a: &[Data]) -> std::result::Result { + span_of(h, arg(a, 0), &["TextRange"]) +} + +/// Fails when `d` is not a text range, or is a stale one. +pub(super) fn check_range(h: &Host, d: &Data) -> std::result::Result<(), HostError> { + resolve(h, span_of(h, d, &["TextRange"])?).map(|_| ()) +} + +/// The span of `this`: a text range, or a text frame's whole text. +fn this_text(h: &Host, a: &[Data], class: &str) -> std::result::Result { + if handle_of(arg(a, 0), "TextFrame").is_some() { + return Ok(whole_span(h, item_of(h, arg(a, 0))?)?.1); + } + span_of(h, arg(a, 0), &[class]) +} + +// ---- contents ---- + +/// The model's text as `contents` gives it. +fn to_script(s: &str) -> String { + s.chars() + .map(|c| match c { + '\n' => '\r', + '\u{2028}' => '\u{3}', + c => c, + }) + .collect() +} + +/// Text a script wrote, as the model keeps it. +fn from_script(s: &str) -> String { + s.replace("\r\n", "\n") + .chars() + .map(|c| match c { + '\r' => '\n', + '\u{3}' => '\u{2028}', + c => c, + }) + .collect() +} + +fn read_contents(h: &Host, r: Span) -> Answer { + let (index, s, e, _) = resolve(h, r)?; + let (a, b) = (index.byte(s, false), index.byte(e, true)); + Ok(text(to_script(&index.text[a..b]))) +} + +/// The text a script gives as `contents`: a string, or a number as `String(number)` writes it. +fn contents_of(value: &Data) -> std::result::Result { + match value { + Data::String(v) => Ok(from_script(v)), + Data::Number(n) => Ok(vectorcraft_js::number_to_string(*n)), + _ => Err(HostError::Type("contents must be a string or a number".into())), + } +} + +/// Replaces the text of `r` with `value`, as one `text.editRange`. +fn write_contents(h: &Host, r: Span, value: &Data) -> Answer { + let insert = contents_of(value)?; + let (index, s, e, _) = resolve(h, r)?; + let (a, b) = (index.byte(s, false), index.byte(e, true)); + if index.text[a..b] == insert { + return Ok(Data::Undefined); + } + let (s, e) = (index.text[..a].encode_utf16().count(), index.text[..b].encode_utf16().count()); + edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": a, "end": b, "insert": insert}))?; + record(h, r.item, &index, s, e - s, &insert)?; + Ok(Data::Undefined) +} + +fn frame_contents(h: &Host, a: &[Data]) -> Answer { + let (_, r) = whole_span(h, this_frame(h, a)?)?; + read_contents(h, r) +} + +fn frame_set_contents(h: &Host, a: &[Data]) -> Answer { + let (_, r) = whole_span(h, this_frame(h, a)?)?; + write_contents(h, r, arg(a, 1)) +} + +fn range_contents(h: &Host, a: &[Data]) -> Answer { + read_contents(h, this_range(h, a)?) +} + +fn range_set_contents(h: &Host, a: &[Data]) -> Answer { + write_contents(h, this_range(h, a)?, arg(a, 1)) +} + +// ---- TextFrame ---- + +fn frame_kind(h: &Host, a: &[Data]) -> Answer { + let item = this_frame(h, a)?; + with_doc(h, item.doc, |_, st| { + let t = text_of(st, item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok(text(match t.kind { + TextKind::Point => "TextType.POINTTEXT", + TextKind::Area { .. } => "TextType.AREATEXT", + TextKind::OnPath { .. } => "TextType.PATHTEXT", + })) + }) +} + +fn frame_orientation(h: &Host, a: &[Data]) -> Answer { + let item = this_frame(h, a)?; + with_doc(h, item.doc, |_, st| { + let t = text_of(st, item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok(text(if t.vertical { "TextOrientation.VERTICAL" } else { "TextOrientation.HORIZONTAL" })) + }) +} + +fn frame_range(h: &Host, a: &[Data]) -> Answer { + let item = this_frame(h, a)?; + let (_, r) = whole_span(h, item)?; + Ok(range_ref(h, item, r.start, r.end, r.stamp, "TextRange")) +} + +fn sub(h: &Host, a: &[Data], class: &str) -> Answer { + let r = this_text(h, a, "TextRange")?; + let (_, s, e, stamp) = resolve(h, r)?; + Ok(range_ref(h, r.item, s, e, stamp, class)) +} + +fn characters(h: &Host, a: &[Data]) -> Answer { + sub(h, a, "Characters") +} + +fn words(h: &Host, a: &[Data]) -> Answer { + sub(h, a, "Words") +} + +fn paragraphs(h: &Host, a: &[Data]) -> Answer { + sub(h, a, "Paragraphs") +} + +fn character_attributes(h: &Host, a: &[Data]) -> Answer { + sub(h, a, "CharacterAttributes") +} + +fn paragraph_attributes(h: &Host, a: &[Data]) -> Answer { + sub(h, a, "ParagraphAttributes") +} + +/// The id a command's result, as the command gave it, holds under `ids` (the first) or `id`. It is +/// read from the JSON, where an id above 2^53 is still exact. +fn result_id(v: &Value) -> Option { + v.get("ids").and_then(|ids| ids.get(0)).or_else(|| v.get("id")).and_then(Value::as_u64).map(NodeId) +} + +fn new_ref(h: &Host, doc: Doc, id: Option) -> Answer { + let id = id.ok_or_else(|| HostError::Error("the command made no object".into()))?; + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; + Ok(item_ref(h, st, id)) +} + +/// `createOutline()`: Type › Create Outlines for the frame alone. → the group of outlines, or +/// `null` when the type has nothing to outline and the command removed it. +fn frame_outline(h: &Host, a: &[Data]) -> Answer { + let item = this_frame(h, a)?; + let (_, r) = on_doc(h, item.doc.uid, true, |h| { + command(h, "select.set", &json!({"ids": [item.id.0]}))?; + super::command_value(h, "type.createOutlines", &json!({})) + })?; + match result_id(&r) { + Some(id) => new_ref(h, item.doc, Some(id)), + None => Ok(Data::Null), + } +} + +/// Converts area type to point type (`area` false) or point type to area type. +fn convert(h: &Host, a: &[Data], to_area: bool) -> Answer { + let item = this_frame(h, a)?; + let kind_ok = with_doc(h, item.doc, |_, st| { + text_of(st, item.id).map(|t| if to_area { matches!(t.kind, TextKind::Point) } else { matches!(t.kind, TextKind::Area { .. }) }) + }); + match kind_ok { + None => return Err(HostError::Error(STALE_ITEM.into())), + Some(false) => return Err(HostError::Error(format!("the text frame is not {} type", if to_area { "point" } else { "area" }))), + Some(true) => {} + } + let id = if to_area { "type.convertToAreaType" } else { "type.convertToPointType" }; + let (_, r) = on_doc(h, item.doc.uid, true, |h| super::command_value(h, id, &json!({"ids": [item.id.0]})))?; + new_ref(h, item.doc, result_id(&r).or(Some(item.id))) +} + +fn frame_to_point(h: &Host, a: &[Data]) -> Answer { + convert(h, a, false) +} + +fn frame_to_area(h: &Host, a: &[Data]) -> Answer { + convert(h, a, true) +} + +// ---- TextRange ---- + +fn range_parent(h: &Host, a: &[Data]) -> Answer { + let r = this_range(h, a)?; + resolve(h, r)?; + Ok(with_doc(h, r.item.doc, |_, st| item_ref(h, st, r.item.id))) +} + +fn range_start(h: &Host, a: &[Data]) -> Answer { + let (_, s, _, _) = resolve(h, this_range(h, a)?)?; + Ok(num(float(s as u64))) +} + +fn range_end(h: &Host, a: &[Data]) -> Answer { + let (_, _, e, _) = resolve(h, this_range(h, a)?)?; + Ok(num(float(e as u64))) +} + +fn range_length(h: &Host, a: &[Data]) -> Answer { + let (_, s, e, _) = resolve(h, this_range(h, a)?)?; + Ok(num(float((e - s) as u64))) +} + +/// Setting `length` moves the range's end to that many UTF-16 units after its start; the text +/// does not change. A length that is not a whole number from 0 to the units left in the frame +/// throws. +fn range_set_length(h: &Host, a: &[Data]) -> Answer { + let (r, number) = span_and_number(h, arg(a, 0), &["TextRange"])?; + let (index, s, _, stamp) = resolve(h, r)?; + let n = super::number(arg(a, 1), "length")?; + let left = index.len() - s; + let Some(n) = usize_of(n).filter(|n| *n <= left) else { + return Err(HostError::Range(format!("length must be a whole number from 0 to {left}"))); + }; + h.dom.text.resized.borrow_mut().insert(number, (s, s + n, stamp)); + Ok(Data::Undefined) +} + +/// `remove()`: deletes the range's text. +fn range_remove(h: &Host, a: &[Data]) -> Answer { + write_contents(h, this_range(h, a)?, &text("")) +} + +/// `getParagraphLength()`: the length of the first paragraph the range touches, its break included. +fn range_paragraph_length(h: &Host, a: &[Data]) -> Answer { + let (index, s, e, _) = resolve(h, this_range(h, a)?)?; + let p = touched(&index.paras, s, e).next().and_then(|i| index.paras.get(i)).map_or(0, |(x, y)| y - x); + Ok(num(float(p as u64))) +} + +/// `getTextRunLength()`: the length from the range's start to the end of the run of characters +/// with one style it starts in, within the range. +fn range_run_length(h: &Host, a: &[Data]) -> Answer { + let r = this_range(h, a)?; + let (index, s, e, _) = resolve(h, r)?; + let b = index.byte(s, false); + let run_end = with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let mut at = 0; + for run in &t.runs { + at += run.text.len(); + if at > b { + return Ok(at); + } + } + Ok(at) + })?; + let u = index.text[..run_end.min(index.text.len())].encode_utf16().count(); + Ok(num(float((u.min(e).max(s) - s) as u64))) +} + +// ---- collections of a range ---- + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Part { + Characters, + Words, + Paragraphs, +} + +const PARTS: [(&str, Part); 3] = [("Characters", Part::Characters), ("Words", Part::Words), ("Paragraphs", Part::Paragraphs)]; + +fn part_of(d: &Data) -> Option { + PARTS.iter().find(|(c, _)| handle_of(d, c).is_some()).map(|(_, p)| *p) +} + +fn this_part(h: &Host, a: &[Data]) -> std::result::Result<(Span, Part), HostError> { + let part = part_of(arg(a, 0)).ok_or_else(|| HostError::Type("this is not a collection of text".into()))?; + Ok((span_of(h, arg(a, 0), &["Characters", "Words", "Paragraphs"])?, part)) +} + +/// The spans of a collection, as a range of item numbers and the spans to look them up in. +fn part_spans(index: &Index, part: Part, s: usize, e: usize) -> (std::ops::Range, Option<&Spans>) { + match part { + Part::Characters => (index.chars_in(s, e), None), + Part::Words => (touched(&index.words, s, e), Some(&index.words)), + Part::Paragraphs => (touched(&index.paras, s, e), Some(&index.paras)), + } +} + +fn part_length(h: &Host, a: &[Data]) -> Answer { + let (r, part) = this_part(h, a)?; + let (index, s, e, _) = resolve(h, r)?; + Ok(num(float(part_spans(&index, part, s, e).0.len() as u64))) +} + +fn part_parent(h: &Host, a: &[Data]) -> Answer { + let (r, _) = this_part(h, a)?; + let (_, s, e, stamp) = resolve(h, r)?; + Ok(range_ref(h, r.item, s, e, stamp, "TextRange")) +} + +fn part_at(h: &Host, a: &[Data]) -> Answer { + let (r, part) = this_part(h, a)?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; + let (index, s, e, stamp) = resolve(h, r)?; + let (items, spans) = part_spans(&index, part, s, e); + let Some(k) = items.start.checked_add(i).filter(|k| *k < items.end) else { return Ok(Data::Undefined) }; + let span = match spans { + None => index.char_span(k), + Some(list) => list.get(k).copied(), + }; + Ok(span.map_or(Data::Undefined, |(x, y)| range_ref(h, r.item, x, y, stamp, "TextRange"))) +} + +/// Where `add` puts its text: before or after the relative object. +fn text_placement(d: &Data) -> std::result::Result { + match d { + Data::Undefined => Ok(true), + Data::String(s) if s == "ElementPlacement.PLACEBEFORE" || s == "ElementPlacement.PLACEATBEGINNING" => Ok(false), + Data::String(s) if s == "ElementPlacement.PLACEAFTER" || s == "ElementPlacement.PLACEATEND" => Ok(true), + _ => Err(HostError::Type("insertionLocation must be PLACEBEFORE, PLACEAFTER, PLACEATBEGINNING or PLACEATEND".into())), + } +} + +/// `add(contents, relativeObject?, insertionLocation?)` and, with `before`, `addBefore(contents)`: +/// inserts `contents` after the collection's last item (`addBefore`: before its first item), or +/// before or after `relativeObject`, a text range or text frame of the same frame, as one +/// `text.editRange`. A word gets a space on each side that touches another character that is not +/// white space; a paragraph gets a paragraph break on each side that touches another paragraph. +/// → the range of `contents`. +fn part_add(h: &Host, a: &[Data], before: bool) -> Answer { + let (r, part) = this_part(h, a)?; + let contents = contents_of(arg(a, 1))?; + let (index, s, e, _) = resolve(h, r)?; + let at = if before || matches!(arg(a, 2), Data::Undefined) { + let (items, spans) = part_spans(&index, part, s, e); + let span = |k: usize| match spans { + None => index.char_span(k), + Some(list) => list.get(k).copied(), + }; + if before { + items.clone().next().and_then(span).map_or(s, |(x, _)| x) + } else { + items.clone().next_back().and_then(span).map_or(e, |(_, y)| y) + } + } else { + let rel = arg(a, 2); + let target = if handle_of(rel, "TextFrame").is_some() { + whole_span(h, item_of(h, rel)?)?.1 + } else { + span_of(h, rel, &["TextRange"]).map_err(|_| HostError::Type("relativeObject must be a TextRange or a TextFrame".into()))? + }; + if target.item.doc.uid != r.item.doc.uid || target.item.id != r.item.id { + return Err(HostError::Error("relativeObject must be text of the same text frame".into())); + } + let (_, ts, te, _) = resolve(h, target)?; + if text_placement(arg(a, 3))? { te } else { ts } + }; + if contents.is_empty() { + let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?; + return Ok(range_ref(h, r.item, at, at, stamp, "TextRange")); + } + let b = index.byte(at, false); + let (prev, next) = (index.text[..b].chars().next_back(), index.text[b..].chars().next()); + let (lead, trail) = match part { + Part::Characters => ("", ""), + Part::Words => { + let apart = |c: Option| c.is_some_and(|c| !c.is_whitespace()); + let lead = if apart(prev) && !contents.starts_with(char::is_whitespace) { " " } else { "" }; + let trail = if apart(next) && !contents.ends_with(char::is_whitespace) { " " } else { "" }; + (lead, trail) + } + Part::Paragraphs => ( + if prev.is_some_and(|c| c != '\n') && !contents.starts_with('\n') { "\n" } else { "" }, + if next.is_some() && !contents.ends_with('\n') { "\n" } else { "" }, + ), + }; + let insert = format!("{lead}{contents}{trail}"); + edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": b, "end": b, "insert": insert}))?; + record(h, r.item, &index, at, 0, &insert)?; + let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?; + let start = at + lead.encode_utf16().count(); + Ok(range_ref(h, r.item, start, start + contents.encode_utf16().count(), stamp, "TextRange")) +} + +fn part_add_after(h: &Host, a: &[Data]) -> Answer { + part_add(h, a, false) +} + +fn part_add_before(h: &Host, a: &[Data]) -> Answer { + part_add(h, a, true) +} + +// ---- character attributes ---- + +#[derive(Clone, Copy)] +enum Attr { + Size, + Leading, + AutoLeading, + Tracking, + BaselineShift, + HorizontalScale, + VerticalScale, + Rotation, + Underline, + StrikeThrough, + TextFont, +} + +const ATTRS: [(&str, Attr); 11] = [ + ("size", Attr::Size), + ("leading", Attr::Leading), + ("autoLeading", Attr::AutoLeading), + ("tracking", Attr::Tracking), + ("baselineShift", Attr::BaselineShift), + ("horizontalScale", Attr::HorizontalScale), + ("verticalScale", Attr::VerticalScale), + ("rotation", Attr::Rotation), + ("underline", Attr::Underline), + ("strikeThrough", Attr::StrikeThrough), + ("textFont", Attr::TextFont), +]; + +/// The styles of the characters in bytes `a..b`, effective as the Character panel shows them, with +/// the paragraph they are in: one entry for each run and paragraph the range covers. For an empty +/// range, the style of the character before it, or of the first one. With `first`, only the first +/// entry. +fn styles_in(t: &TextObject, a: usize, b: usize, first: bool) -> std::result::Result, HostError> { + let mut out = Vec::new(); + let (mut at, mut para) = (0, 0); + let effective = |s: &CharStyle| t.effective_char_style(s).ok_or_else(|| HostError::Error("the text's transform cannot be measured".into())); + for run in &t.runs { + let end = at + run.text.len(); + let bytes = run.text.as_bytes(); + let breaks = |from: usize, to: usize| bytes.get(from - at..to - at).map_or(0, |s| s.iter().filter(|&&c| c == b'\n').count()); + if a == b && at < a.max(1) && a <= end { + let lo = a.saturating_sub(1).max(at); + out.push((effective(&run.style)?, para + breaks(at, lo))); + break; + } + if a < end && at < b { + let (lo, hi) = (a.max(at), b.min(end)); + let style = effective(&run.style)?; + let mut p = para + breaks(at, lo); + out.push((style.clone(), p)); + if first { + return Ok(out); + } + for (k, _) in bytes.get(lo - at..hi - at).unwrap_or_default().iter().enumerate().filter(|&(_, &c)| c == b'\n') { + p += 1; + if lo + k + 1 < hi { + out.push((style.clone(), p)); + } + } + } + para += bytes.iter().filter(|&&c| c == b'\n').count(); + at = end; + } + if out.is_empty() + && let Some(r) = t.runs.first() + { + out.push((effective(&r.style)?, 0)); + } + Ok(out) +} + +/// The bytes in `a..b` whose characters have auto leading, each stretch with the leading its +/// characters' auto leading sets them with, in document points; touching stretches with the same +/// leading are one. +fn auto_leading_spans(t: &TextObject, a: usize, b: usize) -> std::result::Result, HostError> { + let mut out: Vec<(usize, usize, f64)> = Vec::new(); + let mut push = |from: usize, to: usize, leading: f64| match out.last_mut() { + Some(last) if last.1 == from && same(&num(last.2), &num(leading)) => last.1 = to, + _ => out.push((from, to, leading)), + }; + let (mut at, mut para) = (0, 0); + for run in &t.runs { + let end = at + run.text.len(); + let bytes = run.text.as_bytes(); + if a < end && at < b { + let style = t.effective_char_style(&run.style).ok_or_else(|| HostError::Error("the text's transform cannot be measured".into()))?; + if style.leading.is_none() { + let (lo, hi) = (a.max(at), b.min(end)); + let auto = |p: usize| t.para_at(p).justification.auto_leading_for(style.size); + let mut p = para + bytes.get(..lo - at).unwrap_or_default().iter().filter(|&&c| c == b'\n').count(); + let mut from = lo; + for (k, _) in bytes.get(lo - at..hi - at).unwrap_or_default().iter().enumerate().filter(|&(_, &c)| c == b'\n') { + let to = lo + k + 1; + push(from, to, auto(p)); + p += 1; + from = to; + } + if from < hi { + push(from, hi, auto(p)); + } + } + } + para += bytes.iter().filter(|&&c| c == b'\n').count(); + at = end; + } + Ok(out) +} + +fn same(a: &Data, b: &Data) -> bool { + match (a, b) { + (Data::Number(x), Data::Number(y)) => (x - y).abs() < 1e-9, + _ => a == b, + } +} + +fn attr_value(h: &Host, attr: Attr, t: &TextObject, s: &CharStyle, para: usize) -> Data { + match attr { + Attr::Size => num(s.size), + Attr::Leading => num(s.leading.unwrap_or_else(|| t.para_at(para).justification.auto_leading_for(s.size))), + Attr::AutoLeading => Data::Bool(s.leading.is_none()), + Attr::Tracking => num(s.tracking), + Attr::BaselineShift => num(s.baseline_shift), + Attr::HorizontalScale => num(s.h_scale), + Attr::VerticalScale => num(s.v_scale), + Attr::Rotation => num(s.rotation), + Attr::Underline => Data::Bool(s.underline), + Attr::StrikeThrough => Data::Bool(s.strikethrough), + Attr::TextFont => font_ref(h, &s.font_family, &s.font_style), + } +} + +/// The `text.setRangeStyle` parameter for `attr` set to `v`, and the value it reads as after. +fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, &CharStyle, usize)) -> std::result::Result<(Value, Data), HostError> { + let finite = || number(v, name); + Ok(match attr { + Attr::Size => { + let n = finite()?; + if !(0.1..=1296.0).contains(&n) { + return Err(HostError::Range("size must be from 0.1 to 1296 points".into())); + } + (json!({"size": n}), num(n)) + } + Attr::Leading => { + let n = finite()?; + if !(0.1..=5000.0).contains(&n) { + return Err(HostError::Range("leading must be from 0.1 to 5000 points".into())); + } + (json!({"leading": n}), num(n)) + } + Attr::AutoLeading => { + if boolean(v, name)? { + (json!({"leading": "auto"}), Data::Bool(true)) + } else { + let (t, s, para) = first; + let n = s.leading.unwrap_or_else(|| t.para_at(para).justification.auto_leading_for(s.size)); + (json!({"leading": n}), Data::Bool(false)) + } + } + Attr::Tracking => { + let n = finite()?; + if !(-1000.0..=10_000.0).contains(&n) { + return Err(HostError::Range("tracking must be from -1000 to 10000".into())); + } + (json!({"tracking": n}), num(n)) + } + Attr::BaselineShift => { + let n = finite()?; + if n.abs() > 1296.0 { + return Err(HostError::Range("baselineShift must be from -1296 to 1296 points".into())); + } + (json!({"baselineShift": n}), num(n)) + } + Attr::HorizontalScale | Attr::VerticalScale => { + let n = finite()?; + if !(1.0..=10_000.0).contains(&n) { + return Err(HostError::Range(format!("{name} must be from 1 to 10000 percent"))); + } + let key = if matches!(attr, Attr::HorizontalScale) { "hScale" } else { "vScale" }; + (json!({ key: n }), num(n)) + } + Attr::Rotation => { + let n = finite()?; + if n.abs() > 360.0 { + return Err(HostError::Range("rotation must be from -360 to 360 degrees".into())); + } + (json!({"rotation": n}), num(n)) + } + Attr::Underline => { + let b = boolean(v, name)?; + (json!({"underline": b}), Data::Bool(b)) + } + Attr::StrikeThrough => { + let b = boolean(v, name)?; + (json!({"strikethrough": b}), Data::Bool(b)) + } + Attr::TextFont => { + let (family, style) = font_of(h, v)?; + (json!({"font": family, "style": style}), font_ref(h, &family, &style)) + } + }) +} + +/// The span of `this` for a character or paragraph attribute: a text range, its +/// `characterAttributes` or `paragraphAttributes`, or a text frame's whole text. +fn attr_span(h: &Host, a: &[Data], class: &str) -> std::result::Result { + if handle_of(arg(a, 0), "TextRange").is_some() { + return this_range(h, a); + } + this_text(h, a, class) +} + +fn read_attr(h: &Host, a: &[Data], attr: Attr) -> Answer { + let r = attr_span(h, a, "CharacterAttributes")?; + let (index, s, e, _) = resolve(h, r)?; + let (ba, bb) = (index.byte(s, false), index.byte(e, true)); + with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok(styles_in(t, ba, bb, true)?.first().map_or(Data::Undefined, |(st, p)| attr_value(h, attr, t, st, *p))) + }) +} + +fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { + let r = attr_span(h, a, "CharacterAttributes")?; + let (index, s, e, _) = resolve(h, r)?; + let (ba, bb) = (index.byte(s, false), index.byte(e, true)); + let (param, unchanged, fixed) = with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let styles = styles_in(t, ba, bb, false)?; + let first = styles.first().map(|(s, p)| (s.clone(), *p)).unwrap_or_else(|| (CharStyle::default(), 0)); + let (param, wants) = attr_param(h, attr, name, arg(a, 1), (t, &first.0, first.1))?; + // A leading set on characters with auto leading fixes it even where auto gives that value. + let has = |st: &CharStyle, p: usize| (!matches!(attr, Attr::Leading) || st.leading.is_some()) && same(&attr_value(h, attr, t, st, p), &wants); + let unchanged = ba == bb || styles.iter().all(|(st, p)| has(st, *p)); + let fixed = match (attr, &wants) { + (Attr::AutoLeading, Data::Bool(false)) if !unchanged => Some(auto_leading_spans(t, ba, bb)?), + _ => None, + }; + if let Some(bad) = fixed.iter().flatten().map(|(_, _, l)| *l).find(|l| !(0.1..=5000.0).contains(l)) { + return Err(HostError::Range(format!("autoLeading cannot be turned off: the auto leading here is {bad} points, outside 0.1 to 5000"))); + } + Ok::<_, HostError>((param, unchanged, fixed)) + })?; + if unchanged { + return Ok(Data::Undefined); + } + if let Some(spans) = fixed { + // Each character with auto leading keeps the leading it is set with now. + super::atomically(h, |h| { + for (start, end, leading) in &spans { + let p = json!({"id": r.item.id.0, "start": start, "end": end, "leading": leading}); + edit_item(h, r.item, "text.setRangeStyle", &p)?; + } + Ok(()) + })?; + return Ok(Data::Undefined); + } + let mut p = param; + if let Some(o) = p.as_object_mut() { + o.insert("id".into(), json!(r.item.id.0)); + o.insert("start".into(), json!(ba)); + o.insert("end".into(), json!(bb)); + } + let answer = edit_item(h, r.item, "text.setRangeStyle", &p)?; + if let Attr::TextFont = attr { + let wants = |k: &str| p.get(k).and_then(Value::as_str).unwrap_or_default().to_string(); + font_applied(h, r.item, (ba, bb), (&wants("font"), &wants("style")), &answer)?; + } + Ok(Data::Undefined) +} + +/// Fails, after the font is set, when `text.setRangeStyle` warned that the font is not available +/// or when characters in bytes `a..b` kept another font because Missing Glyph Protection is on. +fn font_applied(h: &Host, item: Item, (a, b): (usize, usize), (family, style): (&str, &str), answer: &Data) -> std::result::Result<(), HostError> { + if let Data::Object(o) = answer + && let Some((_, Data::String(w))) = o.iter().find(|(k, _)| k == "warning") + { + return Err(HostError::Error(format!("textFont: {w}"))); + } + let kept = with_doc(h, item.doc, |_, st| { + let Some(t) = text_of(st, item.id) else { return 0 }; + let mut at = 0; + let mut kept = 0; + for run in &t.runs { + let end = at + run.text.len(); + let other = !run.style.font_family.eq_ignore_ascii_case(family) || !run.style.font_style.eq_ignore_ascii_case(style); + if other && a < end && at < b { + kept += run.text.get(a.max(at) - at..b.min(end) - at).map_or(0, |s| s.chars().count()); + } + at = end; + } + kept + }); + if kept > 0 { + let noun = if kept == 1 { "character, which keeps its" } else { "characters, which keep their" }; + return Err(HostError::Error(format!("textFont: the font has no glyph for {kept} {noun} font because Missing Glyph Protection is on"))); + } + Ok(()) +} + +// ---- paragraph attributes ---- + +#[derive(Clone, Copy)] +enum ParaAttr { + Justification, + FirstLineIndent, + LeftIndent, + RightIndent, + SpaceBefore, + SpaceAfter, +} + +const PARA_ATTRS: [(&str, ParaAttr); 6] = [ + ("justification", ParaAttr::Justification), + ("firstLineIndent", ParaAttr::FirstLineIndent), + ("leftIndent", ParaAttr::LeftIndent), + ("rightIndent", ParaAttr::RightIndent), + ("spaceBefore", ParaAttr::SpaceBefore), + ("spaceAfter", ParaAttr::SpaceAfter), +]; + +const JUSTIFICATIONS: [(&str, &str); 7] = [ + ("LEFT", "left"), + ("CENTER", "center"), + ("RIGHT", "right"), + ("FULLJUSTIFYLASTLINELEFT", "justifyLeft"), + ("FULLJUSTIFYLASTLINECENTER", "justifyCenter"), + ("FULLJUSTIFYLASTLINERIGHT", "justifyRight"), + ("FULLJUSTIFY", "justifyAll"), +]; + +/// The text of paragraph `i` of `index`, its break included. +fn para_text(index: &Index, i: usize) -> &str { + index.paras.get(i).and_then(|&(x, y)| index.text.get(index.byte(x, false)..index.byte(y, false))).unwrap_or_default() +} + +/// The value of `attr` in paragraph `i` of `t`, whose text `index` holds. Auto alignment reads as +/// the side it aligns to: right in a right-to-left paragraph, left otherwise. +fn para_value(attr: ParaAttr, t: &TextObject, index: &Index, i: usize) -> Data { + let p = t.para_at(i); + match attr { + ParaAttr::Justification => text(format!( + "Justification.{}", + match p.justify { + Justify::Auto if vectorcraft_text::paragraph_is_rtl(para_text(index, i), p.direction) => "RIGHT", + Justify::Auto | Justify::Left => "LEFT", + Justify::Center => "CENTER", + Justify::Right => "RIGHT", + Justify::JustifyLeft => "FULLJUSTIFYLASTLINELEFT", + Justify::JustifyCenter => "FULLJUSTIFYLASTLINECENTER", + Justify::JustifyRight => "FULLJUSTIFYLASTLINERIGHT", + Justify::JustifyAll => "FULLJUSTIFY", + } + )), + ParaAttr::FirstLineIndent => num(p.first_line_indent), + ParaAttr::LeftIndent => num(p.left_indent), + ParaAttr::RightIndent => num(p.right_indent), + ParaAttr::SpaceBefore => num(p.space_before), + ParaAttr::SpaceAfter => num(p.space_after), + } +} + +/// The command and parameter that set `attr` to `v`, and the value it reads as after. +fn para_param(attr: ParaAttr, name: &str, v: &Data) -> std::result::Result<(&'static str, Value, Data), HostError> { + if let ParaAttr::Justification = attr { + let found = match v { + Data::String(s) => s.strip_prefix("Justification.").and_then(|m| JUSTIFICATIONS.iter().find(|(k, _)| *k == m)), + _ => None, + }; + let (_, value) = found.ok_or_else(|| HostError::Type("justification must be a Justification value".into()))?; + return Ok(("text.setStyle", json!({"justify": value}), v.clone())); + } + let n = number(v, name)?; + if n.abs() > 1296.0 { + return Err(HostError::Range(format!("{name} must be from -1296 to 1296 points"))); + } + let key = match attr { + ParaAttr::FirstLineIndent => "firstLineIndent", + ParaAttr::LeftIndent => "leftIndent", + ParaAttr::RightIndent => "rightIndent", + ParaAttr::SpaceBefore => "spaceBefore", + _ => "spaceAfter", + }; + Ok(("text.setFormat", json!({ key: n }), num(n))) +} + +/// The paragraphs a range touches, by number, and the bytes from the first one's start to the last +/// one's start, which select exactly those paragraphs for `text.setFormat` and `text.setStyle`. +fn para_range(index: &Index, s: usize, e: usize) -> (std::ops::Range, usize, usize) { + let paras = touched(&index.paras, s, e); + let start = |i: usize| index.paras.get(i).map_or(index.text.len(), |&(x, _)| index.byte(x, false)); + let (ba, bb) = (start(paras.start), start(paras.end.saturating_sub(1).max(paras.start))); + (paras, ba, bb) +} + +fn read_para(h: &Host, a: &[Data], attr: ParaAttr) -> Answer { + let r = attr_span(h, a, "ParagraphAttributes")?; + let (index, s, e, _) = resolve(h, r)?; + let (paras, _, _) = para_range(&index, s, e); + with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok(para_value(attr, t, &index, paras.start)) + }) +} + +fn write_para(h: &Host, a: &[Data], attr: ParaAttr, name: &str) -> Answer { + let r = attr_span(h, a, "ParagraphAttributes")?; + let (id, param, wants) = para_param(attr, name, arg(a, 1))?; + let (index, s, e, _) = resolve(h, r)?; + let (paras, ba, bb) = para_range(&index, s, e); + let unchanged = with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + // An explicit alignment replaces Auto even where Auto aligns to the same side. + let auto = |i: usize| matches!(attr, ParaAttr::Justification) && t.para_at(i).justify == Justify::Auto; + Ok::<_, HostError>(paras.clone().all(|i| !auto(i) && same(¶_value(attr, t, &index, i), &wants))) + })?; + if unchanged { + return Ok(Data::Undefined); + } + let mut p = param; + if let Some(o) = p.as_object_mut() { + o.insert("id".into(), json!(r.item.id.0)); + o.insert("start".into(), json!(ba)); + o.insert("end".into(), json!(bb)); + } + edit_item(h, r.item, id, &p)?; + Ok(Data::Undefined) +} + +// ---- TextFrames ---- + +fn doc_text_frames_impl(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("TextFrames", &[float(h.run), float(doc.uid)])) +} + +/// `document.textFrames`. +pub(super) fn doc_text_frames(link: &Link) -> HostMember { + get(link, doc_text_frames_impl) +} + +/// 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 + && std::ptr::eq(doc.as_ptr(), Arc::as_ptr(&st.doc)) + { + return ids.clone(); + } + let ids: Vec = page_items(h, st).iter().copied().filter(|i| text_of(st, *i).is_some()).collect(); + let ids = Rc::new(ids); + *h.dom.text.list.borrow_mut() = Some((st.uid, Arc::downgrade(&st.doc), ids.clone())); + ids +} + +fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "TextFrames") +} + +fn frames_length(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| frame_ids(h, st).len()) as u64))) +} + +fn frames_parent(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn frames_at(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; + Ok(with_doc(h, doc, |_, st| frame_ids(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) +} + +fn frames_by_name(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + with_doc(h, doc, |_, st| { + let ids = frame_ids(h, st); + h.charge_call(ids.len() as u64)?; + let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) + }) +} + +fn frames_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => frames_by_name(h, a), + Data::Number(_) => match frames_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `TextOrientation` as `text.create`'s `vertical`, `undefined` horizontal. +fn vertical_of(d: &Data) -> std::result::Result { + match d { + Data::Undefined => Ok(false), + Data::String(s) if s == "TextOrientation.HORIZONTAL" => Ok(false), + Data::String(s) if s == "TextOrientation.VERTICAL" => Ok(true), + _ => Err(HostError::Type("orientation must be a TextOrientation value".into())), + } +} + +/// Makes point type at `anchor` (script coordinates; `None`: the origin) with `text.create`. +fn point_text(h: &Host, doc: Doc, anchor: Option<[f64; 2]>, vertical: bool) -> Answer { + let at = with_doc(h, doc, |_, st| Ok::<_, HostError>(frame(st)?.to_document(h.dom.coords.get(), anchor.unwrap_or([0.0, 0.0]))))?; + let (_, r) = + on_doc(h, doc.uid, true, |h| super::command_value(h, "text.create", &json!({"x": at.x, "y": at.y, "text": "", "vertical": vertical})))?; + new_ref(h, doc, result_id(&r)) +} + +/// `add()`: empty point type at the origin. +fn frames_add(h: &Host, a: &[Data]) -> Answer { + point_text(h, frames_doc(h, a)?, None, false) +} + +/// `pointText(anchor, orientation?)`. +fn frames_point_text(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + let anchor = point(arg(a, 1), "anchor")?; + point_text(h, doc, Some(anchor), vertical_of(arg(a, 2))?) +} + +/// Turns the path `d` names into area type or type on a path with `text.createInPath`. +fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer { + let doc = frames_doc(h, a)?; + if handle_of(arg(a, 1), "PathItem").is_none() { + return Err(HostError::Type("textPath must be a PathItem".into())); + } + let path = item_of(h, arg(a, 1))?; + if path.doc.uid != doc.uid { + return Err(HostError::Error(super::CROSS_DOCUMENT.into())); + } + if rest.iter().any(|i| !matches!(arg(a, *i), Data::Undefined)) { + return Err(HostError::Error("TextFrames: threading and path positions are not available yet".into())); + } + let orientation = if on_path { 4 } else { 2 }; + let vertical = vertical_of(arg(a, orientation))?; + let mode = if on_path { "onPath" } else { "area" }; + let params = json!({"path": path.id.0, "mode": mode, "text": "", "vertical": vertical}); + let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", ¶ms))?; + new_ref(h, doc, result_id(&r)) +} + +/// `areaText(textPath, orientation?, baseFrame?, postFix?)`. +fn frames_area_text(h: &Host, a: &[Data]) -> Answer { + in_path(h, a, false, &[3, 4]) +} + +/// `pathText(textPath, startTValue?, endTValue?, orientation?, baseFrame?, postFix?)`. +fn frames_path_text(h: &Host, a: &[Data]) -> Answer { + in_path(h, a, true, &[2, 3, 5, 6]) +} + +/// `removeAll()`: deletes every type object in one command; a hidden or locked one stops it first. +fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + let (ids, refused) = with_doc(h, doc, |_, st| { + let ids = frame_ids(h, st); + let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); + let refused: Vec = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect(); + (ids, refused) + }); + if !refused.is_empty() { + let list = refused.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("cannot delete hidden or locked type: {list}"))); + } + if !ids.is_empty() { + on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + } + Ok(Data::Undefined) +} + +// ---- fonts ---- + +/// The run's font list, read once. +fn with_fonts(h: &Host, f: impl FnOnce(&mut Vec<(String, String)>) -> T) -> T { + let mut fonts = h.dom.text.fonts.borrow_mut(); + let list = fonts.get_or_insert_with(|| { + let db = vectorcraft_text::FontDb::global(); + let mut v = Vec::new(); + for family in db.menu_family_list().iter() { + for style in db.styles(family) { + v.push((family.clone(), style)); + } + } + v + }); + f(list) +} + +/// A `TextFont` for `family` and `style`, added to the run's list when it is not there. +fn font_ref(h: &Host, family: &str, style: &str) -> Data { + let i = with_fonts(h, |list| match list.iter().position(|(f, s)| f.eq_ignore_ascii_case(family) && s.eq_ignore_ascii_case(style)) { + Some(i) => i, + None => { + list.push((family.to_string(), style.to_string())); + list.len() - 1 + } + }); + host_ref("TextFont", &[float(h.run), float(i as u64)]) +} + +/// The family and style of the `TextFont` `d`. +fn font_of(h: &Host, d: &Data) -> std::result::Result<(String, String), HostError> { + let Some(&[run, i]) = handle_of(d, "TextFont").as_deref() else { return Err(HostError::Type("textFont must be a TextFont".into())) }; + if whole(run) != Some(h.run) { + return Err(HostError::Error("Stale text font".into())); + } + usize_of(i).and_then(|i| with_fonts(h, |list| list.get(i).cloned())).ok_or_else(|| HostError::Error("Stale text font".into())) +} + +fn fonts_length(h: &Host, _: &[Data]) -> Answer { + Ok(num(float(with_fonts(h, |l| l.len()) as u64))) +} + +fn fonts_at(h: &Host, a: &[Data]) -> Answer { + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; + let found = with_fonts(h, |l| i < l.len()); + Ok(if found { host_ref("TextFont", &[float(h.run), float(i as u64)]) } else { Data::Undefined }) +} + +/// `textFonts.getByName(name)`: the PostScript name of a bundled or installed face, then the family +/// and style with a space. +fn fonts_by_name(h: &Host, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + if name.len() > super::MAX_TEXT_BYTES { + return Err(HostError::Range("the name is too long".into())); + } + let named = vectorcraft_text::FontDb::global().find_postscript(name).map(|f| (f.family.clone(), f.style.clone())); + let i = with_fonts(h, |l| { + h.charge_call(l.len() as u64)?; + let by_ps = named.as_ref().and_then(|(f, s)| l.iter().position(|(lf, ls)| lf.eq_ignore_ascii_case(f) && ls.eq_ignore_ascii_case(s))); + Ok::<_, HostError>(by_ps.or_else(|| l.iter().position(|(f, s)| format!("{f} {s}").eq_ignore_ascii_case(name)))) + })?; + match (i, named) { + (Some(i), _) => Ok(host_ref("TextFont", &[float(h.run), float(i as u64)])), + (None, Some((family, style))) => Ok(font_ref(h, &family, &style)), + (None, None) => Err(HostError::Error(NOT_FOUND.into())), + } +} + +fn fonts_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => fonts_by_name(h, a), + Data::Number(_) => match fonts_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +fn font_family(h: &Host, a: &[Data]) -> Answer { + Ok(text(font_of(h, arg(a, 0))?.0)) +} + +fn font_style(h: &Host, a: &[Data]) -> Answer { + Ok(text(font_of(h, arg(a, 0))?.1)) +} + +/// The font's PostScript name, or its family and style joined by a hyphen when the font is not +/// installed. +fn font_name(h: &Host, a: &[Data]) -> Answer { + let (family, style) = font_of(h, arg(a, 0))?; + let face = vectorcraft_text::FontDb::global().face(&family, &style); + Ok(text(face.map_or_else(|| format!("{family}-{style}").replace(' ', ""), |f| f.postscript_name()))) +} + +fn app_text_fonts_impl(_: &Host, _: &[Data]) -> Answer { + Ok(host_ref("TextFonts", &[])) +} + +/// `app.textFonts`. +pub(super) fn app_text_fonts(link: &Link) -> HostMember { + get(link, app_text_fonts_impl) +} + +fn app_ref(_: &Host, _: &[Data]) -> Answer { + Ok(host_ref("Application", &[])) +} + +/// A font's `parent`, `app`, once the font is checked. +fn font_parent(h: &Host, a: &[Data]) -> Answer { + font_of(h, arg(a, 0))?; + Ok(host_ref("Application", &[])) +} + +// ---- classes ---- + +fn range_typename(h: &Host, a: &[Data]) -> Answer { + resolve(h, this_range(h, a)?)?; + Ok(text("TextRange")) +} + +fn part_typename(h: &Host, a: &[Data]) -> Answer { + let (r, part) = this_part(h, a)?; + resolve(h, r)?; + Ok(text(PARTS.iter().find(|(_, p)| *p == part).map_or("Characters", |(c, _)| c))) +} + +fn char_attrs_typename(h: &Host, a: &[Data]) -> Answer { + resolve(h, span_of(h, arg(a, 0), &["CharacterAttributes"])?)?; + Ok(text("CharacterAttributes")) +} + +fn para_attrs_typename(h: &Host, a: &[Data]) -> Answer { + resolve(h, span_of(h, arg(a, 0), &["ParagraphAttributes"])?)?; + Ok(text("ParagraphAttributes")) +} + +fn frames_typename(h: &Host, a: &[Data]) -> Answer { + frames_doc(h, a)?; + Ok(text("TextFrames")) +} + +fn font_typename(h: &Host, a: &[Data]) -> Answer { + font_of(h, arg(a, 0))?; + Ok(text("TextFont")) +} + +/// A member listed on the help pages that a script cannot set yet. Assigning it throws, after the +/// read's own checks of `this`. +fn read_only(link: &Link, g: super::Member, class: &'static str, name: &'static str) -> HostMember { + let message = format!("{class}.{name} cannot be set yet"); + let get = function(link, g); + let read = get.clone(); + HostMember::Property { + get, + set: Rc::new(move |a: Vec| { + read(a.into_iter().take(1).collect())?; + Err(HostError::Error(message.clone())) + }), + } +} + +fn attr_members(link: &Link) -> Vec { + let mut out = Vec::new(); + for (name, attr) in ATTRS { + let l = link.clone(); + let g: HostFunction = Rc::new(move |a: Vec| { + let h = super::current(&l)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + read_attr(&h, &a, attr) + }); + let l = link.clone(); + let s: HostFunction = Rc::new(move |a: Vec| { + let h = super::current(&l)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + write_attr(&h, &a, attr, name) + }); + let data_type = match attr { + Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean", + Attr::TextFont => "TextFont", + _ => "number", + }; + out.push((name.to_string(), HostMember::Property { get: g, set: s }, typed(data_type))); + } + out +} + +fn para_members(link: &Link) -> Vec { + let mut out = Vec::new(); + for (name, attr) in PARA_ATTRS { + let l = link.clone(); + let g: HostFunction = Rc::new(move |a: Vec| { + let h = super::current(&l)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + read_para(&h, &a, attr) + }); + let l = link.clone(); + let s: HostFunction = Rc::new(move |a: Vec| { + let h = super::current(&l)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + write_para(&h, &a, attr, name) + }); + let data_type = if matches!(attr, ParaAttr::Justification) { "Justification" } else { "number" }; + out.push((name.to_string(), HostMember::Property { get: g, set: s }, typed(data_type))); + } + out +} + +/// The enumerations type uses. +const ENUMS: &[(&str, &[&str])] = &[ + ("TextType", &["AREATEXT", "PATHTEXT", "POINTTEXT"]), + ("TextOrientation", &["HORIZONTAL", "VERTICAL"]), + ( + "Justification", + &["CENTER", "FULLJUSTIFY", "FULLJUSTIFYLASTLINECENTER", "FULLJUSTIFYLASTLINELEFT", "FULLJUSTIFYLASTLINERIGHT", "LEFT", "RIGHT"], + ), +]; + +/// Adds the enumerations type uses to `realm`. +pub(super) fn install_enums(realm: &mut Realm) -> std::result::Result<(), RunError> { + for (name, members) in ENUMS { + let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); + realm.define_host_object(name, items)?; + } + Ok(()) +} + +/// The classes of type, `TextFrame` among them, which inherits from `PageItem`. +pub(super) fn classes(l: &Link) -> Vec { + let mut frame = named(vec![ + ("kind", get(l, frame_kind), typed("TextType")), + ("contents", property(l, frame_contents, frame_set_contents), typed("string")), + ("textRange", get(l, frame_range), typed("TextRange")), + ("characters", get(l, characters), MemberInfo { collection: true, ..typed("Characters") }), + ("words", get(l, words), MemberInfo { collection: true, ..typed("Words") }), + ("paragraphs", get(l, paragraphs), MemberInfo { collection: true, ..typed("Paragraphs") }), + ("orientation", read_only(l, frame_orientation, "TextFrame", "orientation"), typed("TextOrientation")), + ("createOutline", method(l, frame_outline), returns("GroupItem", &[])), + ("convertAreaObjectToPointObject", method(l, frame_to_point), returns("TextFrame", &[])), + ("convertPointObjectToAreaObject", method(l, frame_to_area), returns("TextFrame", &[])), + ]); + frame.extend(super::variables::item_members(l, "TextFrame")); + frame.extend( + [ + "lines", + "insertionPoints", + "textRanges", + "story", + "nextFrame", + "previousFrame", + "textPath", + "anchor", + "antialias", + "columnCount", + "columnGutter", + "rowCount", + "rowGutter", + "startTValue", + "endTValue", + "opticalAlignment", + "matrix", + "textSelection", + ] + .into_iter() + .map(|m| super::later(l, "TextFrame", m)), + ); + let mut range = named(vec![ + ("typename", get(l, range_typename), typed("string")), + ("parent", get(l, range_parent), typed("*")), + ("contents", property(l, range_contents, range_set_contents), typed("string")), + ("start", read_only(l, range_start, "TextRange", "start"), typed("number")), + ("end", read_only(l, range_end, "TextRange", "end"), typed("number")), + ("characterOffset", read_only(l, range_start, "TextRange", "characterOffset"), typed("number")), + ("length", property(l, range_length, range_set_length), typed("number")), + ("characters", get(l, characters), MemberInfo { collection: true, ..typed("Characters") }), + ("words", get(l, words), MemberInfo { collection: true, ..typed("Words") }), + ("paragraphs", get(l, paragraphs), MemberInfo { collection: true, ..typed("Paragraphs") }), + ("characterAttributes", get(l, character_attributes), typed("CharacterAttributes")), + ("paragraphAttributes", get(l, paragraph_attributes), typed("ParagraphAttributes")), + ("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)); + range.extend(para_members(l)); + range.extend( + [ + "lines", + "insertionPoints", + "textRanges", + "story", + "kerning", + "characterStyles", + "paragraphStyles", + "textSelection", + "changeCaseTo", + "select", + "deSelect", + "duplicate", + "move", + "getLocalCharOverridesJSON", + "getLocalParaOverridesJSON", + ] + .into_iter() + .map(|m| super::later(l, "TextRange", m)), + ); + let part = |name: &'static str| { + class( + name, + None, + named(vec![ + ("typename", get(l, part_typename), typed("string")), + ("length", get(l, part_length), typed("number")), + ("parent", get(l, part_parent), typed("*")), + ("add", method(l, part_add_after), returns("TextRange", &[("contents", "string")])), + ("addBefore", method(l, part_add_before), returns("TextRange", &[("contents", "string")])), + ]), + Some(function(l, part_at)), + ) + }; + let mut chars = named(vec![("typename", get(l, char_attrs_typename), typed("string"))]); + chars.extend(attr_members(l)); + let mut paras = named(vec![("typename", get(l, para_attrs_typename), typed("string"))]); + paras.extend(para_members(l)); + vec![ + class("TextFrame", Some("PageItem"), frame, None), + class("TextRange", None, range, None), + part("Characters"), + part("Words"), + part("Paragraphs"), + class("CharacterAttributes", None, chars, None), + class("ParagraphAttributes", None, paras, None), + class( + "TextFrames", + None, + named(vec![ + ("typename", get(l, frames_typename), typed("string")), + ("length", get(l, frames_length), typed("number")), + ("parent", get(l, frames_parent), typed("Document")), + ("index", method(l, frames_index), returns("number", &[("itemKey", "TextFrame")])), + ("getByName", method(l, frames_by_name), returns("TextFrame", &[("name", "string")])), + ("add", method(l, frames_add), returns("TextFrame", &[])), + ("pointText", method(l, frames_point_text), returns("TextFrame", &[("anchor", "Array"), ("orientation", "TextOrientation")])), + ("areaText", method(l, frames_area_text), returns("TextFrame", &[("textPath", "PathItem"), ("orientation", "TextOrientation")])), + ("pathText", method(l, frames_path_text), returns("TextFrame", &[("textPath", "PathItem"), ("startTValue", "number")])), + ("removeAll", method(l, frames_remove_all), returns("undefined", &[])), + ]), + Some(function(l, frames_at)), + ), + class( + "TextFonts", + None, + named(vec![ + ("typename", typename_of("TextFonts"), typed("string")), + ("length", get(l, fonts_length), typed("number")), + ("parent", get(l, app_ref), typed("Application")), + ("index", method(l, fonts_index), returns("number", &[("itemKey", "TextFont")])), + ("getByName", method(l, fonts_by_name), returns("TextFont", &[("name", "string")])), + ]), + Some(function(l, fonts_at)), + ), + class( + "TextFont", + None, + named(vec![ + ("typename", get(l, font_typename), typed("string")), + ("name", get(l, font_name), typed("string")), + ("family", get(l, font_family), typed("string")), + ("style", get(l, font_style), typed("string")), + ("parent", get(l, font_parent), typed("Application")), + ]), + None, + ), + ] +} + +#[cfg(test)] +mod tests { + use std::collections::VecDeque; + use std::rc::Rc; + use std::sync::Weak; + + use super::{Index, Log, MAX_EDITS, touched}; + + #[test] + fn the_edit_log_keeps_the_last_edits_and_drops_only_older_ones() { + let mut l = Log { doc: Weak::new(), reverts: 0, index: Rc::new(Index::new(String::new())), stamp: 0, floor: 0, edits: VecDeque::new() }; + for _ in 0..MAX_EDITS { + l.push(0, 0, 1); + } + assert_eq!((l.edits.len(), l.floor), (MAX_EDITS, 0)); + l.push(0, 0, 1); + // Only the first edit is dropped: a range made after it still moves through every later edit. + assert_eq!((l.edits.len(), l.floor), (MAX_EDITS, 1)); + assert_eq!(l.edits.front().map(|x| x.stamp), Some(2)); + } + + #[test] + fn index_counts_utf16_units_and_splits_words_and_paragraphs() { + let i = Index::new("a\u{1F600}b c\nd".into()); + assert_eq!(i.len(), 8); + assert_eq!(i.chars, vec![0, 1, 3, 4, 5, 6, 7, 8]); + assert_eq!(i.byte(2, false), 1); + assert_eq!(i.byte(2, true), 5); + assert_eq!(i.words, vec![(0, 4), (5, 6), (7, 8)]); + assert_eq!(i.paras, vec![(0, 7), (7, 8)]); + assert_eq!(i.chars_in(1, 4), 1..3); + } + + #[test] + fn only_an_empty_range_touches_the_empty_paragraph_at_the_end() { + let i = Index::new("a\n".into()); + assert_eq!(i.paras, vec![(0, 2), (2, 2)]); + assert_eq!(touched(&i.paras, 0, 2), 0..1); + assert_eq!(touched(&i.paras, 0, 1), 0..1); + assert_eq!(touched(&i.paras, 2, 2), 1..2); + assert_eq!(touched(&i.paras, 1, 1), 0..1); + let e = Index::new(String::new()); + assert_eq!(touched(&e.paras, 0, 0), 0..1); + assert_eq!(touched(&e.words, 0, 0), 0..0); + } +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index cbfd14550b..71d7cc1399 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -186,6 +186,7 @@ mod script_io; mod script_run; mod script_scriptui; mod script_tags; +mod script_text; mod script_variables; mod script_xmp; mod scripts; 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 new file mode 100644 index 0000000000..2935fd0566 --- /dev/null +++ b/crates/engine/src/tests/script_text.rs @@ -0,0 +1,629 @@ +//! Type in the script object model: `textFrames`, text ranges, their attributes and `textFonts`. + +use serde_json::{Value, json}; +use vectorcraft_doc::Justify; + +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// A 400 × 300 pt document with point type holding `text`. +fn doc_with(text: &str) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = s.execute("text.create", &json!({"x": 20, "y": 100, "text": text, "size": 12})).unwrap()["id"].as_u64().unwrap(); + (s, NodeId(id)) +} + +fn plain(s: &Session, id: NodeId) -> String { + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } +} + +fn sizes(s: &Session, id: NodeId) -> Vec<(String, f64)> { + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.size)).collect(), + _ => panic!("not text"), + } +} + +#[test] +fn text_frames_add_point_area_and_path_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 200, "height": 100})).unwrap(); + s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 200}, {"x": 300, "y": 220}], "closed": false})).unwrap(); + let before = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems;\ + 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, 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"])); + // 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")); + assert!(failure(&mut s, "app.activeDocument.textFrames.pointText([1]);").contains("anchor")); + assert!(failure(&mut s, "app.activeDocument.textFrames.pointText([1, 2], 'up');").contains("TextOrientation")); + assert_eq!(undo_steps(&s), before + 1); + // pathText takes its orientation fourth, after the start and end positions it does not take yet. + s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 250}, {"x": 300, "y": 260}], "closed": false})).unwrap(); + let find = "var d = app.activeDocument, p = d.pageItems, q; for (var i = 0; i < p.length; i++) if (p[i].typename == 'PathItem') q = p[i];"; + assert!(failure(&mut s, &format!("{find} d.textFrames.pathText(q, 0.5);")).contains("not available yet")); + let out = log(&mut s, &format!("{find} vc.log(d.textFrames.pathText(q, undefined, undefined, TextOrientation.VERTICAL).orientation);")); + assert_eq!(out, vec![json!("TextOrientation.VERTICAL")]); +} + +#[test] +fn contents_reads_paragraph_breaks_as_r_and_accepts_every_break() { + let (mut s, id) = doc_with("x"); + let out = log(&mut s, "var t = app.activeDocument.textFrames[0]; t.contents = 'a\\rb\\r\\nc\\nd\\u0003e'; vc.log(t.contents);"); + assert_eq!(out, vec![json!("a\rb\rc\rd\u{3}e")]); + assert_eq!(plain(&s, id), "a\nb\nc\nd\u{2028}e"); + assert!(failure(&mut s, "app.activeDocument.textFrames[0].contents = true;").contains("contents must be a string or a number")); +} + +#[test] +fn contents_takes_a_number_as_its_text() { + let (mut s, id) = doc_with("x"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0]; t.contents = 7; vc.log(t.contents);\ + t.textRange.characters[0].contents = 2.5; vc.log(t.contents);", + ); + assert_eq!(out, vec![json!("7"), json!("2.5")]); + assert_eq!(plain(&s, id), "2.5"); +} + +#[test] +fn offsets_count_utf16_units_and_keep_surrogate_pairs_whole() { + let (mut s, _) = doc_with("a\u{1F600}b cd"); + let out = log( + &mut s, + "var r = app.activeDocument.textFrames[0].textRange, c = r.characters;\ + vc.log([r.length, r.start, r.end, c.length]);\ + vc.log([c[1].start, c[1].length, c[2].start, c[2].contents]);\ + vc.log([r.words.length, r.words[1].contents, r.words[0].characters.length]);\ + vc.log(app.activeDocument.textFrames[0].contents.length === r.length);", + ); + assert_eq!(out, vec![json!([7, 0, 7, 6]), json!([1, 2, 3, "b"]), json!([2, "cd", 3]), json!(true)]); +} + +#[test] +fn the_first_character_of_each_word_grows_in_one_undo_step() { + let (mut s, id) = doc_with("one two"); + let before = undo_steps(&s); + log( + &mut s, + "var text = app.activeDocument.textFrames[0].textRange;\ + for (var j = 0; j < text.words.length; j++) { var f = text.words[j].characters[0]; f.size = f.size * 1.5; }", + ); + assert_eq!(sizes(&s, id), vec![("o".into(), 18.0), ("ne ".into(), 12.0), ("t".into(), 18.0), ("wo".into(), 12.0)]); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn ranges_follow_model_edits_and_go_stale_after_other_edits() { + let (mut s, id) = doc_with("one two three"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], w = t.words, second = w[1], third = w[2];\ + w[0].contents = 'first'; vc.log([second.contents, second.start, third.contents]);\ + second.contents = ''; vc.log([second.length, third.contents, t.contents]);", + ); + assert_eq!(out, vec![json!(["two", 6, "three"]), json!([0, "three", "first three"])]); + let source = format!("var r = app.activeDocument.textFrames[0].words[0]; vc.run('text.setText', {{id: {}, text: 'other'}}); r.contents;", id.0); + let e = failure(&mut s, &source); + assert!(e.contains("Stale text range"), "{e}"); + let e = failure(&mut s, "var t = app.activeDocument.textFrames[0], r = t.textRange; t.remove(); r.contents;"); + assert!(e.contains("Stale text range"), "{e}"); + // A change reversed before the range is read leaves the text the range knew. + let (mut s, id) = doc_with("one two"); + let source = format!( + "var r = app.activeDocument.textFrames[0].words[1]; vc.run('text.setText', {{id: {0}, text: 'other'}});\ + vc.run('text.setText', {{id: {0}, text: 'one two'}}); vc.log([r.contents, r.start]);", + id.0 + ); + assert_eq!(log(&mut s, &source), vec![json!(["two", 4])]); +} + +#[test] +fn ranges_made_before_file_revert_go_stale_even_when_the_text_is_the_same() { + let (mut s, _) = doc_with("one two"); + let path = std::env::temp_dir().join(format!("vc-text-revert-{}.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.words[1];\ + vc.run('shape.rectangle', {x: 1, y: 1, width: 5, height: 5}); vc.run('file.revert', {});\ + var now = app.activeDocument.textFrames[0];\ + vc.log(now.contents); try { vc.log(r.contents); } catch (e) { vc.log(e.message); }\ + vc.log(now.words[1].contents);", + ); + let _ = std::fs::remove_file(&path); + assert_eq!(out[0], json!("one two"), "the reverted file holds the same text"); + assert!(out[1].as_str().is_some_and(|m| m.contains("Stale text range")), "{out:?}"); + 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"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], first = t.characters[0], r = t.characters[1];\ + t.characters[2].contents = 'ZZ'; vc.log([first.contents, r.contents]);\ + t.contents = 'XY'; vc.log([r.contents, r.start, r.length, first.contents]);", + ); + // A range that ends where an edit starts keeps its end; one inside the edit takes the new text. + assert_eq!(out, vec![json!(["a", "b"]), json!(["XY", 0, 2, "XY"])]); +} + +#[test] +fn bad_attribute_values_are_refused_without_a_change() { + let (mut s, id) = doc_with("abc"); + let before = undo_steps(&s); + for (src, want) in [ + ("r.size = 0;", "size must be from 0.1"), + ("r.size = 'big';", "size must be a finite number"), + ("r.size = NaN;", "not a finite number"), + ("r.leading = 0;", "leading must be from 0.1"), + ("r.characterAttributes.tracking = 1e9;", "tracking"), + ("r.underline = 1;", "underline must be true or false"), + ("r.textFont = 'Arial';", "textFont must be a TextFont"), + ("r.paragraphAttributes.justification = 'LEFT';", "Justification value"), + ("r.paragraphAttributes.leftIndent = 5000;", "leftIndent"), + ("r.length = -1;", "length must be a whole number from 0 to 3"), + ("r.length = 1.5;", "length must be a whole number from 0 to 3"), + ("r.length = 4;", "length must be a whole number from 0 to 3"), + ("r.length = 'two';", "length must be a finite number"), + ] { + let e = failure(&mut s, &format!("var r = app.activeDocument.textFrames[0].textRange; {src}")); + assert!(e.contains(want), "{src}: {e}"); + } + assert_eq!(undo_steps(&s), before); + assert_eq!(sizes(&s, id), vec![("abc".into(), 12.0)]); +} + +#[test] +fn setting_the_value_a_range_has_records_no_undo_step() { + let (mut s, _) = doc_with("abc"); + let before = undo_steps(&s); + log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.textRange; r.size = r.size; r.underline = false;\ + t.contents = t.contents; r.paragraphAttributes.leftIndent = 0; r.characters[0].characterAttributes.size = 12;", + ); + assert_eq!(undo_steps(&s), before); +} + +#[test] +fn a_leading_equal_to_the_auto_leading_turns_auto_leading_off() { + let (mut s, id) = doc_with("abc"); + let before = undo_steps(&s); + let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.leading = r.leading; vc.log([r.autoLeading, r.leading]);"); + assert_eq!(out, vec![json!([false, 14.4])]); + assert_eq!(undo_steps(&s), before + 1); + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - 14.4).abs() < 1e-9)), "{:?}", t.runs), + _ => panic!("not text"), + } + // A fixed leading set to its own value is still no change. + let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.leading = 14.4; vc.log(r.autoLeading);"); + assert_eq!(out, vec![json!(false)]); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn paragraph_attributes_set_the_paragraphs_a_range_touches() { + let (mut s, _) = doc_with("first\nsecond"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], p = t.paragraphs;\ + vc.log([p.length, p[0].contents, p[1].contents]);\ + p[1].paragraphAttributes.justification = Justification.CENTER; p[1].paragraphAttributes.leftIndent = 9;\ + vc.log([p[0].paragraphAttributes.justification, p[1].paragraphAttributes.justification]);\ + vc.log([p[0].paragraphAttributes.leftIndent, p[1].paragraphAttributes.leftIndent, p[1].getParagraphLength()]);", + ); + assert_eq!(out[0], json!([2, "first\r", "second"])); + assert_eq!(out[1], json!(["Justification.LEFT", "Justification.CENTER"])); + assert_eq!(out[2], json!([0, 9, 6])); + // A paragraph whose range ends after its break sets only itself. + let out = log( + &mut s, + "var p = app.activeDocument.textFrames[0].paragraphs; p[0].paragraphAttributes.justification = Justification.RIGHT;\ + p[0].paragraphAttributes.spaceAfter = 4;\ + vc.log([p[0].justification, p[0].paragraphAttributes.justification, p[1].paragraphAttributes.justification]);\ + vc.log([p[0].paragraphAttributes.spaceAfter, p[1].paragraphAttributes.spaceAfter]);", + ); + assert_eq!(out, vec![json!(["Justification.RIGHT", "Justification.RIGHT", "Justification.CENTER"]), json!([4, 0])]); + // The empty paragraph after a final break belongs only to an empty range at the end. + let (mut s, id) = doc_with("a\n"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], p = t.paragraphs; p[0].paragraphAttributes.spaceAfter = 4;\ + vc.log([p.length, p[0].paragraphs.length, p[0].paragraphAttributes.spaceAfter]);", + ); + assert_eq!(out, vec![json!([1, 1, 4])]); + let after: Vec = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (0..2).map(|i| t.para_at(i).space_after).collect(), + _ => panic!("not text"), + }; + assert_eq!(after, vec![4.0, 0.0]); +} + +#[test] +fn auto_leading_reads_the_paragraph_of_the_range_inside_one_run() { + let (mut s, id) = doc_with("first\nsecond"); + s.execute("text.setFormat", &json!({"id": id.0, "start": 6, "end": 6, "autoLeading": 200})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.textFrames[0].paragraphs; vc.log([p[0].leading, p[1].leading, p[1].characters[0].leading]);\ + p[1].autoLeading = false; vc.log([p[0].autoLeading, p[1].autoLeading, p[1].leading]);", + ); + assert_eq!(out, vec![json!([14.4, 24, 24]), json!([true, false, 24])]); + let leadings: Vec<(String, Option)> = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.leading)).collect(), + _ => panic!("not text"), + }; + assert_eq!(leadings, vec![("first\n".into(), None), ("second".into(), Some(24.0))]); +} + +#[test] +fn a_font_that_missing_glyph_protection_keeps_off_some_characters_throws() { + let (from, to, c) = ("Source Sans 3", "JetBrains Mono", '\u{180}'); + let db = vectorcraft_text::FontDb::global(); + let covers = |f: &str| db.face(f, "Regular").is_some_and(|face| face.covers(c)); + if !covers(from) || covers(to) { + return; // Installed fonts of these names cover other characters. + } + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 50, "text": "a\u{180}c", "font": from})).unwrap(); + let pick = format!("var r = app.activeDocument.textFrames[0].textRange, f = app.textFonts.getByName('{to} Regular');"); + let e = failure(&mut s, &format!("{pick} r.textFont = f;")); + assert!(e.contains("textFont: the font has no glyph for 1 character, which keeps its font"), "{e}"); + // Characters the font can draw take it without an error. + let out = log(&mut s, &format!("{pick} r.characters[0].textFont = f; vc.log(r.characters[0].textFont.family);")); + assert_eq!(out, vec![json!(to)]); +} + +#[test] +fn turning_auto_leading_off_keeps_each_characters_leading() { + let (mut s, id) = doc_with("ab\ncd"); + s.execute("text.setFormat", &json!({"id": id.0, "start": 3, "end": 3, "autoLeading": 200})).unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 1, "end": 2, "size": 24})).unwrap(); + let before = undo_steps(&s); + let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.autoLeading = false; vc.log(r.autoLeading);"); + assert_eq!(out, vec![json!(false)]); + assert_eq!(undo_steps(&s), before + 1); + let leadings: Vec<(String, Option)> = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.leading.map(|l| (l * 1000.0).round() as i64))).collect(), + _ => panic!("not text"), + }; + let want = [("a", 14_400), ("b", 28_800), ("\n", 14_400), ("cd", 24_000)]; + assert_eq!(leadings, want.iter().map(|(t, l)| (t.to_string(), Some(*l))).collect::>()); + // Paragraphs and runs with the same leading take one command. + let (mut s, _) = doc_with("one\ntwo\nthree"); + let r = run(&mut s, "app.activeDocument.textFrames[0].textRange.autoLeading = false;").unwrap(); + let calls: Vec<(Value, Value)> = r["slowestCommands"].as_array().unwrap().iter().map(|c| (c["id"].clone(), c["calls"].clone())).collect(); + assert_eq!(calls, vec![(json!("text.setRangeStyle"), json!(1))]); + // Auto leading that a fixed leading cannot hold is refused before anything changes. + let (mut s, id) = doc_with("ab\ncd"); + s.execute("text.setFormat", &json!({"id": id.0, "start": 3, "end": 3, "autoLeading": 0})).unwrap(); + let before = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.textFrames[0].textRange.autoLeading = false;"); + assert!(e.contains("autoLeading cannot be turned off"), "{e}"); + assert_eq!(undo_steps(&s), before); + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => assert!(t.runs.iter().all(|r| r.style.leading.is_none())), + _ => panic!("not text"), + } +} + +#[test] +fn an_explicit_alignment_replaces_auto_alignment() { + let justify = |s: &Session, id: NodeId| match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.para_at(0).justify, + _ => panic!("not text"), + }; + for (text, reads) in [("abc", "Justification.LEFT"), ("\u{5e9}\u{5dc}\u{5d5}\u{5dd}", "Justification.RIGHT")] { + let (mut s, id) = doc_with(text); + assert_eq!(justify(&s, id), Justify::Auto); + let before = undo_steps(&s); + let out = log( + &mut s, + "var a = app.activeDocument.textFrames[0].textRange.paragraphAttributes; vc.log(a.justification);\ + a.justification = Justification.LEFT; vc.log(a.justification);", + ); + assert_eq!(out, vec![json!(reads), json!("Justification.LEFT")], "{text}"); + assert_eq!(justify(&s, id), Justify::Left, "{text}"); + assert_eq!(undo_steps(&s), before + 1, "{text}"); + } + // Each paragraph on Auto reads by its own text. + let (mut s, _) = doc_with("abc\n\u{5e9}\u{5dc}\u{5d5}\u{5dd}\nd"); + let out = log( + &mut s, + "var p = app.activeDocument.textFrames[0].paragraphs; var j = function (i) { return p[i].paragraphAttributes.justification; }; vc.log([j(0), j(1), j(2)]);", + ); + assert_eq!(out, vec![json!(["Justification.LEFT", "Justification.RIGHT", "Justification.LEFT"])]); +} + +#[test] +fn a_stale_range_has_no_parent() { + let (mut s, id) = doc_with("abc"); + let source = format!("var r = app.activeDocument.textFrames[0].textRange; vc.run('text.setText', {{id: {}, text: 'x'}}); r.parent;", id.0); + let e = failure(&mut s, &source); + assert!(e.contains("Stale text range"), "{e}"); +} + +#[test] +fn a_stale_range_and_its_collections_have_no_typename() { + let (mut s, id) = doc_with("abc"); + let source = format!( + "var r = app.activeDocument.textFrames[0].textRange, all = [r, r.characters, r.words, r.paragraphs, r.characterAttributes, r.paragraphAttributes];\ + var names = []; for (var i = 0; i < all.length; i++) names.push(all[i].typename); vc.log(names);\ + vc.run('text.setText', {{id: {}, text: 'other'}}); var m = [];\ + for (var i = 0; i < all.length; i++) {{ try {{ m.push(all[i].typename); }} catch (e) {{ m.push(e.message); }} }} vc.log(m);", + id.0 + ); + let out = log(&mut s, &source); + assert_eq!(out[0], json!(["TextRange", "Characters", "Words", "Paragraphs", "CharacterAttributes", "ParagraphAttributes"])); + assert_eq!(out[1], json!(vec!["Stale text range"; 6])); +} + +#[test] +fn members_not_built_yet_throw_after_the_stale_check() { + let (mut s, id) = doc_with("abc"); + let e = failure(&mut s, "app.activeDocument.textFrames[0].lines;"); + assert!(e.contains("TextFrame.lines is not available yet"), "{e}"); + let e = failure(&mut s, "var t = app.activeDocument.textFrames[0]; t.remove(); t.lines;"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "app.activeDocument.textFrames[0].textRange.lines;"); + assert!(e.contains("TextRange.lines is not available yet"), "{e}"); + for member in ["r.lines", "r.start = 1"] { + let source = + format!("var r = app.activeDocument.textFrames[0].textRange; vc.run('text.setText', {{id: {}, text: 'other'}}); {member};", id.0); + let e = failure(&mut s, &source); + assert!(e.contains("Stale text range"), "{member}: {e}"); + } +} + +#[test] +fn text_fonts_list_and_assign_fonts_by_name() { + // The last font in the menu that draws "abc", so Missing Glyph Protection keeps no character. + let db = vectorcraft_text::FontDb::global(); + let listed: Vec<(String, String)> = db.menu_family_list().iter().flat_map(|f| db.styles(f).into_iter().map(move |st| (f.clone(), st))).collect(); + let covers = |(f, st): &&(String, String)| db.face(f, st).is_some_and(|face| "abc".chars().all(|c| face.covers(c))); + let Some((pos, (family, style))) = listed.iter().enumerate().rev().find(|(_, fs)| covers(fs)) else { + return; // No installed font draws "abc". + }; + let (mut s, id) = doc_with("abc"); + let out = log( + &mut s, + &format!( + "var f = app.textFonts, m = '';\ + try {{ f.getByName('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ + try {{ f.index('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ + vc.log(f.length > 0); var r = app.activeDocument.textFrames[0].textRange, k = f[{pos}];\ + vc.log([k.family, k.style]); r.textFont = k; vc.log(r.textFont.family === k.family && r.textFont.style === k.style);\ + vc.log(f.getByName(k.family + ' ' + k.style).family === k.family); vc.log(f[f.length] === undefined);" + ), + ); + assert_eq!(out, vec![json!("Not found"), json!("Not found"), json!(true), json!([family, style]), json!(true), json!(true), json!(true)]); + let set = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (t.runs[0].style.font_family.clone(), t.runs[0].style.font_style.clone()), + _ => panic!("not text"), + }; + assert_eq!(&set, &(family.clone(), style.clone())); +} + +#[test] +fn setting_a_ranges_length_moves_its_end_and_leaves_the_text() { + let (mut s, id) = doc_with("hello world"); + let before = undo_steps(&s); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.textRange, w = t.words[1]; r.length = 2;\ + vc.log([r.length, r.contents, r.start, r.end, t.textRange.length]);\ + w.length = 3; vc.log([w.contents, w.start]); r.length = 0; vc.log([r.length, r.contents]);\ + t.characters[0].contents = 'J'; r.length = 5; vc.log(r.contents);", + ); + assert_eq!(out, vec![json!([2, "he", 0, 2, 11]), json!(["wor", 6]), json!([0, ""]), json!("Jello")]); + assert_eq!(plain(&s, id), "Jello world"); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn collections_of_text_add_words_characters_and_paragraphs() { + let cases = [ + ("t.words.add('x')", "hello world", "hello world x", "x"), + ("t.words.addBefore('x')", "hello world", "x hello world", "x"), + ("t.words[0].words.add('x')", "hello world", "hello x world", "x"), + ("t.words.add('x', t.words[0], ElementPlacement.PLACEBEFORE)", "hello world", "x hello world", "x"), + ("t.words.add('x', t.words[1], ElementPlacement.PLACEATBEGINNING)", "hello world", "hello x world", "x"), + ("t.words.add('x', t, ElementPlacement.PLACEATEND)", "hello world", "hello world x", "x"), + ("t.words.add('x')", "hello world ", "hello world x ", "x"), + ("t.words.add('x')", "", "x", "x"), + ("t.words.add(7)", "a", "a 7", "7"), + ("t.characters.add('!')", "hi", "hi!", "!"), + ("t.characters[0].characters.add('x')", "hi", "hxi", "x"), + ("t.paragraphs.add('end')", "one\ntwo", "one\ntwo\nend", "end"), + ("t.paragraphs[0].paragraphs.add('mid')", "one\ntwo", "one\nmid\ntwo", "mid"), + ("t.paragraphs.addBefore('top')", "one", "top\none", "top"), + ]; + for (call, text, after, added) in cases { + let (mut s, id) = doc_with(text); + let before = undo_steps(&s); + let out = log(&mut s, &format!("var t = app.activeDocument.textFrames[0], n = {call}; vc.log([n.typename, n.contents]);")); + assert_eq!(out, vec![json!(["TextRange", added])], "{call} on {text:?}"); + assert_eq!(plain(&s, id), after, "{call} on {text:?}"); + assert_eq!(undo_steps(&s), before + 1, "{call} on {text:?}"); + } + // Empty contents add nothing; bad arguments throw before anything changes. + 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 [ + ("t.words.add(null)", "contents must be a string or a number"), + ("t.words.add('x', t.words[0], 'after')", "insertionLocation must be"), + ("t.words.add('x', t.words[0], ElementPlacement.INSIDE)", "insertionLocation must be"), + ("t.words.add('x', app.activeDocument.textFrames[1])", "same text frame"), + ("t.words.add('x', 5)", "relativeObject must be a TextRange or a TextFrame"), + ] { + let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[0]; {call};")); + assert!(e.contains(want), "{call}: {e}"); + } + assert_eq!(undo_steps(&s), before); + assert_eq!(plain(&s, id), "ab"); +} + +#[test] +fn text_fonts_find_a_bundled_face_by_its_postscript_name() { + let Some(face) = vectorcraft_text::FontDb::global().loaded_faces().into_iter().find(|f| f.family == "Source Sans 3") else { + return; // Built without the bundled fonts. + }; + let ps = face.postscript_name(); + let (mut s, _) = doc_with("abc"); + let out = log(&mut s, &format!("var f = app.textFonts.getByName('{ps}'); vc.log([f.family, f.style, f.name]);")); + assert_eq!(out, vec![json!([face.family, face.style, ps])]); +} + +#[test] +fn a_text_range_sets_the_paragraph_attributes_of_the_paragraphs_it_touches() { + let (mut s, id) = doc_with("first\nsecond\nthird"); + let before = undo_steps(&s); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.textRange; r.justification = Justification.CENTER;\ + vc.log([r.justification, t.paragraphs[2].paragraphAttributes.justification]);\ + t.characters[7].leftIndent = 9; vc.log([t.paragraphs[0].leftIndent, t.paragraphs[1].leftIndent, t.paragraphs[2].leftIndent]);", + ); + assert_eq!(out, vec![json!(["Justification.CENTER", "Justification.CENTER"]), json!([0, 9, 0])]); + let justify: Vec = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (0..3).map(|i| t.para_at(i).justify).collect(), + _ => panic!("not text"), + }; + assert_eq!(justify, vec![Justify::Center; 3]); + assert_eq!(undo_steps(&s), before + 1); + let e = failure(&mut s, "app.activeDocument.textFrames[0].textRange.justification = 'CENTER';"); + assert!(e.contains("Justification value"), "{e}"); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn create_outline_and_conversions_return_the_new_objects() { + let (mut s, id) = doc_with("Hi"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], m = '';\ + try { t.convertAreaObjectToPointObject(); } catch (e) { m = e.message; } vc.log(m);\ + var a = t.convertPointObjectToAreaObject(); vc.log(a.kind);\ + var p = a.convertAreaObjectToPointObject(); vc.log(p.kind); vc.log(p.contents);\ + var g = p.createOutline(); vc.log(g.typename); vc.log(app.activeDocument.textFrames.length);", + ); + assert_eq!(out[0], json!("the text frame is not area type")); + assert_eq!(out[1..], [json!("TextType.AREATEXT"), json!("TextType.POINTTEXT"), json!("Hi"), json!("GroupItem"), json!(0)]); + assert!(s.active().unwrap().doc.node(id).is_none()); +} + +#[test] +fn outlining_type_with_nothing_to_outline_gives_null() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let out = + log(&mut s, "var d = app.activeDocument, t = d.textFrames.add(); var g = t.createOutline(); vc.log([g === null, d.textFrames.length]);"); + assert_eq!(out, vec![json!([true, 0])]); +} + +#[test] +fn type_made_with_a_large_id_is_the_new_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + // The second frame's id, 2^53 + 1, is not exact as a number. + let big = 1u64 << 53; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let out = log( + &mut s, + "var d = app.activeDocument, a = d.textFrames.add(), b = d.textFrames.pointText([5, 5]); b.contents = 'second';\ + vc.log([a === b, a.contents, b.createOutline().typename]);", + ); + assert_eq!(out, vec![json!([false, "", "GroupItem"])]); + assert_eq!(plain(&s, NodeId(big)), ""); +} + +#[test] +fn text_members_refuse_objects_of_other_classes() { + let (mut s, _) = doc_with("abc"); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextFrame.prototype, 'contents').get.call(app.activeDocument.pageItems[0]);"); + assert!(e.contains("this is not a TextFrame"), "{e}"); + let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextRange.prototype, 'contents').get.call(app.activeDocument.textFrames[0]);"); + assert!(e.contains("this is not a TextRange"), "{e}"); + let e = failure(&mut s, "var f = {}; f['\\u0000hostRef'] = ['TextFont', 0, 0]; app.activeDocument.textFrames[0].textRange.textFont = f;"); + assert!(e.contains("not plain data"), "{e}"); + // A font from an earlier run of a named engine is stale. + run(&mut s, "#targetengine keepfont\nvar held = app.textFonts[0];").unwrap(); + for member in ["held.family", "held.parent"] { + let e = failure(&mut s, &format!("#targetengine keepfont\n{member};")); + assert!(e.contains("Stale text font"), "{member}: {e}"); + } +} 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 568f5528eb..a59d50e88b 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", @@ -90,7 +90,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "Application.prototype.", "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents executeMenuCommand \ - getIsFileOpen redraw selection selection= toString typename", + getIsFileOpen redraw selection selection= textFonts toString typename", ), ("DocumentPreset.", "prototype"), ( @@ -107,7 +107,7 @@ const INSIDE: &[(&str, &str)] = &[ "Document.prototype.", "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ - rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= tags textFrames textFrames= toString \ + rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= tags textFrames toString \ typename views width", ), ("Views.", "prototype"), @@ -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"), @@ -147,6 +152,63 @@ const INSIDE: &[(&str, &str)] = &[ ("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"), ("ScreenMode.", "DESKTOP FULLSCREEN MULTIWINDOW"), ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), + ( + "", + "CharacterAttributes Characters Justification ParagraphAttributes Paragraphs TextFont TextFonts TextFrame TextFrames \ + TextOrientation TextRange TextType Words", + ), + ("TextFrames.", "prototype"), + ("TextFrames.prototype.", "add areaText constructor getByName index length parent pathText pointText removeAll typename"), + ("TextFrame.", "prototype"), + ( + "TextFrame.prototype.", + "anchor anchor= antialias antialias= characters columnCount columnCount= columnGutter columnGutter= constructor \ + contents contents= convertAreaObjectToPointObject convertPointObjectToAreaObject createOutline endTValue endTValue= \ + insertionPoints insertionPoints= kind lines lines= matrix matrix= nextFrame nextFrame= opticalAlignment \ + opticalAlignment= orientation orientation= paragraphs previousFrame previousFrame= rowCount rowCount= rowGutter \ + rowGutter= startTValue startTValue= story story= textPath textPath= textRange textRanges textRanges= textSelection \ + textSelection= words", + ), + ("TextRange.", "prototype"), + ( + "TextRange.prototype.", + "autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes characterOffset \ + characterOffset= characterStyles characterStyles= characters constructor contents contents= deSelect deSelect= \ + duplicate duplicate= end end= firstLineIndent firstLineIndent= getLocalCharOverridesJSON getLocalCharOverridesJSON= \ + getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength horizontalScale \ + horizontalScale= insertionPoints insertionPoints= justification justification= kerning kerning= leading leading= \ + leftIndent leftIndent= length length= lines lines= move move= paragraphAttributes paragraphStyles paragraphStyles= \ + paragraphs parent remove rightIndent rightIndent= rotation rotation= select select= size size= spaceAfter spaceAfter= \ + spaceBefore spaceBefore= start start= story story= strikeThrough strikeThrough= textFont textFont= textRanges \ + textRanges= textSelection textSelection= tracking tracking= typename underline underline= verticalScale \ + verticalScale= words", + ), + ("Characters.", "prototype"), + ("Characters.prototype.", "add addBefore constructor length parent typename"), + ("Words.", "prototype"), + ("Words.prototype.", "add addBefore constructor length parent typename"), + ("Paragraphs.", "prototype"), + ("Paragraphs.prototype.", "add addBefore constructor length parent typename"), + ("CharacterAttributes.", "prototype"), + ( + "CharacterAttributes.prototype.", + "autoLeading autoLeading= baselineShift baselineShift= constructor horizontalScale horizontalScale= leading leading= \ + rotation rotation= size size= strikeThrough strikeThrough= textFont textFont= tracking tracking= typename underline \ + underline= verticalScale verticalScale=", + ), + ("ParagraphAttributes.", "prototype"), + ( + "ParagraphAttributes.prototype.", + "constructor firstLineIndent firstLineIndent= justification justification= leftIndent leftIndent= rightIndent \ + rightIndent= spaceAfter spaceAfter= spaceBefore spaceBefore= typename", + ), + ("TextFonts.", "prototype"), + ("TextFonts.prototype.", "constructor getByName index length parent typename"), + ("TextFont.", "prototype"), + ("TextFont.prototype.", "constructor family name parent style typename"), + ("Justification.", "CENTER FULLJUSTIFY FULLJUSTIFYLASTLINECENTER FULLJUSTIFYLASTLINELEFT FULLJUSTIFYLASTLINERIGHT LEFT RIGHT"), + ("TextOrientation.", "HORIZONTAL VERTICAL"), + ("TextType.", "AREATEXT PATHTEXT POINTTEXT"), // Variables and data sets. `importVariables` reads the library file it is given. `PageItem`'s // `visibilityVariable` is in its row above. ("", "Dataset Datasets Variable VariableKind Variables"), @@ -168,7 +230,7 @@ const INSIDE: &[(&str, &str)] = &[ /// The classes the host adds with nothing but a prototype and its constructor: the page item types. const BARE_CLASSES: &str = "BlendItem CompoundPathItem EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ - PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame"; + PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem"; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's /// own API, and what `vc.run` does depends on the command it runs. 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/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/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/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